From gerhard.haering at gmx.de Tue Jul 9 09:30:22 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 15:30:22 +0200 Subject: win32: Leaving Dos Box open In-Reply-To: <3D2AE438.9030205@thomas-guettler.de> References: <3D2AE438.9030205@thomas-guettler.de> Message-ID: <20020709133021.GA17536@lilith.my-fqdn.de> * Thomas Guettler [2002-07-09 15:25 +0200]: > How can the dos box be left open when I run foo.py from the windows > explorer and there is a syntax error? I don't think it's worth bothering with that. Just execute your script on a commandline or in an IDE like IDLE or PythonWin. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From oliver.eichler at dspsolutions.de Thu Jul 18 03:39:56 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Thu, 18 Jul 2002 09:39:56 +0200 Subject: get a list printed in hexadecimal notation References: Message-ID: Another tip I received from Harvey Thomas & Fran?ois Pinard: print [isinstance(x,int) and hex(x) or x for x in l] Oliver From jb at cascade-sys.com Thu Jul 11 10:51:01 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 11 Jul 2002 07:51:01 -0700 Subject: Win32 Registry Manipulation w/PythonWin? References: <3D2CDB4F.4357F810@cascade-sys.com> <005b01c2288a$f3bad1e0$0101010a@local> <3D2D0D8C.8F8B2121@cascade-sys.com> <005101c228d2$a31068c0$0101010a@local> Message-ID: <3D2D9B55.96EC8A02@cascade-sys.com> Chris Gonnerman wrote: > I *was* kidding. I did know who Whatzizname referred to... > but it is a quite (Monty) Pythonic joke to actually *name* > someone Whatzizname. Well, anyway, technically, it's "Whatzernames'". Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From nospam at bigfoot.com Mon Jul 29 06:27:37 2002 From: nospam at bigfoot.com (Gillou) Date: Mon, 29 Jul 2002 12:27:37 +0200 Subject: [ZOPE] Zope, Python, Win2k and Mysql References: <4a4akukkfg92po76t3svc7flen29s3stui@4ax.com> Message-ID: Hi, You should... 1/ Install Python 2.1.3 from www.python.org (even if you lalready got the one provided with Zope) 2/ Install mysqdb from sourceforge on top of this new python installation 3/ change the "start.bat" file to run zope from that python.exe (tipycally c:\python2.1\python.exe) This does the job for me. --Gilles "Rhymes" a ?crit dans le message de news: 4a4akukkfg92po76t3svc7flen29s3stui at 4ax.com... > > I've just installed Zope 2.5.1 on my windows box (Win2k Pro) but it's > built on top its own python version (2.1). During the day I use Py > 2.2.1 and when i tried to install the mysql-bindings (ZMySQLDA) for > Zope a problem raises itself. In the Zope-Ctrl-Panel there is this > error: > > Traceback (most recent call last): > File "C:\PROGRA~1\WEBSITE\lib\python\OFS\Application.py", line 531, > in import_product > product=__import__(pname, global_dict, global_dict, silly) > File "C:\PROGRA~1\WEBSITE\lib\python\Products\ZMySQLDA\__init__.py", > line 91, in ? > import DA > File "C:\PROGRA~1\WEBSITE\lib\python\Products\ZMySQLDA\DA.py", line > 92, in ? > from db import DB > File "C:\PROGRA~1\WEBSITE\lib\python\Products\ZMySQLDA\db.py", line > 89, in ? > import _mysql > ImportError: Module use of python22.dll conflicts with this version of > Python. > > what can i do now? > > -- > Rhymes (rhymes at myself.com) > http://www26.brinkster.com/rhymes > " ride or die " From emile at fenx.com Thu Jul 11 13:30:54 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 11 Jul 2002 17:30:54 GMT Subject: raw.input and other things References: Message-ID: "Seth Ainsley" wrote in message news:mailman.1026404658.11715.python-list at python.org... > Hello, > I'm having trouble with the raw.input thing. try using raw_input (note the underscore) -- Emile van Sebille emile at fenx.com --------- From nospam at bigfoot.com Fri Jul 19 09:06:28 2002 From: nospam at bigfoot.com (Gillou) Date: Fri, 19 Jul 2002 15:06:28 +0200 Subject: Tkinter vs. wxPython References: Message-ID: The full API doc of wxWindows is provided with the Windows distro of wxPython, as well as the list of wxWindows objects available with wxPython. You just need to translate from C/C++ to Python ! Look at the code provided with the demos and sample. It's quite simple. There are so many great widgets provided by wxPython you don't have with Tkinter. --Gilles glenfant AT bigfoot DOT com "Gabe Newcomb" a ?crit dans le message news: mailman.1027027317.26378.python-list at python.org... Ack! I've been trying to get into wxPython, but I'm finding the lack of documentation difficult. There's some, and I'm very grateful for everybody who's contributed it, but I'm somebody who really likes having a decent reference and more examples. My question is this: is there any compelling reason I shouldn't just go with Tkinter instead? I work (for now) exclusively on Win32 boxes, by the way. Thanks all, Gabe From mksql at yahoo.com Wed Jul 10 18:25:52 2002 From: mksql at yahoo.com (mksql at yahoo.com) Date: Wed, 10 Jul 2002 22:25:52 GMT Subject: Python in the enterprise: Pros and cons References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: <37dpiu07qngaq48lljggemtjn1o3jo8ks4@4ax.com> "The Cons:" "Smaller pool of Python developers compared to other languages, such as Java" Some commercial tool vendors, who have thousands of developers, still have bugs in their products that are many years, and product versions, old. It is not the size of your developer base that is important, it is how you use it. "Absence of a commercial support point, even for an Open Source project (though this situation is changing)" Perl, Apache? Lack of a singluar commercial support entity does not seem to have hurt them. With most popular open source tools, support of a variety of types can be found. The thing with Python (and Perl, etc.) is that you do not have to pay for support, unless you really want to. Funny thing is, the support thing seems to get brought up so often, that I believe that it's importance is somewhat inflated. In my experience, support for a language is not nearly as critical is it may be for a commercial database system, for example. If my code does not work, I can re-write it in a way that it will work, to work around a language implementation flaw. In over a decade of developing software, I can recall a single instance where _commercial_ programming language support was needed - and it was not for an open source language. Anyone care to guess who the vendor of the language product was? "Software performance (though benchmarks repeatedly demonstrate Python is comparable to Java in most applications)" Then why is this a problem? Java is very obvious in Enterprise level envrionments. Thus if in "most" situations, if Python performance is comparable to Java, and Java's performance is accepted, should not Python's? There will always be a segment of the market who will choose their tools based on how many other people use them (sheep), and not be concerned on how suited to the task or efficient the tools are. Some of us prefer to be the wolves. On 10 Jul 2002 14:02:33 -0700, sarah.fraser at cnet.com (builder) wrote: >Python has many fans in the open source community, but is it ready for >the enterprise? Here are the advantages and disadvantages of using >Python in the corporate environment. >http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm From mpoulin at verinet.com Fri Jul 12 12:28:05 2002 From: mpoulin at verinet.com (Marc Poulin) Date: Fri, 12 Jul 2002 10:28:05 -0600 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: <3d2f0266$0$40992$75868355@news.frii.net> In article , "Bo M. Maryniuck" wrote: > On Tuesday 09 July 2002 16:59, curt finch wrote: >> ftp://ftp.jump.net/pub/journyx/other/PythonWhtPaper0_1.doc > > Right people will not download this. M$ Word DOC is *evil* format. > Please do PDF, DVI or HTML instead. > Thanks for the link. I enjoyed reading it (in StarOffice on my Linux machine ;-) "You should not have any special fondness for a particular weapon, or anything else, for that matter. Too much is the same as not enough. Without imitating anyone else, you should have as much weaponry as suits you. To entertain likes and dislikes is bad for both commanders and soldiers. Pragmatic thinking is essential." -- Musashi Miyamoto "The Book of Five Rings" From mgerrans at mindspring.com Thu Jul 11 02:09:27 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 10 Jul 2002 23:09:27 -0700 Subject: os.path and Windows UNC paths References: Message-ID: > the trailing \ is escaping the ending ' of the r'...' string. I just ran > across the caution about having odd numbers of \ at the end of an r'...' > string last evening. I noticed this a while back. It doesn't seem to make sense. I thought nothing inside a raw was escaped, so why is the last character? I suppose you can resort to stuff like this: path = os.sep.join(('','','server','share','')) or this: path = r'\\server\share' + '\\' or just give up and do the old: path = '\\\\server\\share\\' but I thought the idea behind the raw strings was to save a little typing and make code a bit more readable since, as in c/c++ you can do everything with cooked strings, it is just more tedious and ugly. I see in the Python doc where it says """ r"\" is not a value [sic. -- I think he intended "valid"] string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). """ I don't understand why this is the case, though. Is a raw string really treated as a standard string until some later time when it is translated to raw? From johan at weknowthewayout.com Fri Jul 19 04:45:29 2002 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Fri, 19 Jul 2002 10:45:29 +0200 Subject: PDF creating again! Message-ID: <3D37D1A9.1030909@weknowthewayout.com> Hi again, I got some advices from some time ago, but it don't seems to work :( I can't use Type1 fonts in the modules or libraries! I have been very interested in TKinter but I can ony use bitmaps font, and I need Type1 fonts at least (maybe other too). Isn't there any kinds of libraries that can do this for me? Output have to be PS or PDF... -- Best Regards - Venlig hilsen Johan Holst Nielsen From jromero at platea.pntic.mec.es Sun Jul 14 21:21:40 2002 From: jromero at platea.pntic.mec.es (Joaquin Romero) Date: Mon, 15 Jul 2002 03:21:40 +0200 Subject: maaxlength in Entry() / Tkinter Message-ID: I can set an maxlength (max number of characters) in a Entry() in Tkinter? Tanks From brueckd at tbye.com Wed Jul 10 12:12:47 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 10 Jul 2002 09:12:47 -0700 (PDT) Subject: How to grab a part of web page? In-Reply-To: Message-ID: On 10 Jul 2002, William Park wrote: > Gerhard H?ring wrote: > >> I think it's possible. When I use 'wget -c' to download HTML, sometimes > >> I see it start from an offset, rather than from the beginning. > > > > Doing this while having a packet sniffer running showed me what the > > corresponding HTTP header is. > > >From the docs that I came across, > > HTTP/1.1: > - "Range" header in request > - "multipart/byteranges" type in the response > > Older HTTP: > - "Request-Range" header > - "multipart/x-byteranges" type > > but the exact syntax I don't remember. (sorry this isn't replying to the OP's post..) Byte range requests can request multiple ranges, but both the requests and the responses are more complex and ill-supported, so it's usually best to just go with the straightforward single-range request: GET /foo HTTP/1.1 Range: bytes=500-1000 With a single-range request the response comes back as a normal response (i.e. not as a multipart MIME message): HTTP/1.1 206 Partial content Content-Range: bytes 500-1000/2000 Content-Length: 501 (500-1000/2000 means the response includes bytes of data from offset 500 to 1000, inclusive, and the total size of the object is 2000 bytes and the content-length header shows that 501 bytes are in the response). You can also include an If-Range request header (plus an etag or last-modified date) to have the server respond with either the requested range or the entire object if the object is now out of date. -Dave From renzo.tomaselli at tecnotp.it Wed Jul 17 03:43:54 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 17 Jul 2002 00:43:54 -0700 Subject: inheriting from C types References: <878dc260.0207161005.6fec78ec@posting.google.com> Message-ID: <878dc260.0207162343.b67770f@posting.google.com> martin at v.loewis.de (Martin v. Loewis) wrote in message news:... > renzo.tomaselli at tecnotp.it (Renzo Tomaselli) writes: > > > import ype > > class k(ype.ype): > > pass > > What is k.__mro__? > > Regards, > Martin I see it contains base classes, but only their dictionary is used in _PyType_Lookup. I did not provide my C type with a tp_dict slot, since I thought its attributes are accessed through tp_getattr. Should I ? Meaning and management of tp_dict is somewhat obscure to me. Renzo From peter at engcorp.com Sat Jul 6 12:28:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 06 Jul 2002 12:28:01 -0400 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: <3D271A91.3D571053@engcorp.com> Thomas Jensen wrote: > > However the CEO (small company, told you :-), made a couple of somewhat > valid points against it. > [...] > I was hoping someone in this group could help with some really > compelling arguments, as I'd really to use Python for this job. If you email me offline I'd be happy to give you details from my current employer's extensive use of Python as a highly reliable and effective tool, and how it has never been an issue that developers who know Python before they start working with it are not as common as weeds. (The offer is open to anyone, by the way.) (Thomas, I assume null at obscure.dk.X is not a valid email address. ;-) -Peter From grante at visi.com Wed Jul 31 12:40:36 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 31 Jul 2002 16:40:36 GMT Subject: Can't detect EOF with pylibpcap Message-ID: <8qU19.30825$eH2.13210511@ruti.visi.com> I'm using pylibpcap 0.4 to analyze capture files created by Ethereal. It works nicely except I can't detect end of file. When you use the next() method, it just never returns when it hits end of file. Calling dispatch() or loop() returns without doing anything, but neither return the number of packets processed, so there's no simple way to determine if you're at end of file or not. The C versions of the dispatch() and loop() calls return the number of packets processed (0 == EOF). Has anybody else figured out how to detect EOF with pylibpcap? -- Grant Edwards grante Yow! HOORAY, Ronald!! Now at YOU can marry LINDA visi.com RONSTADT too!! From drew_csillag at yahoo.com Thu Jul 18 07:06:46 2002 From: drew_csillag at yahoo.com (Drew Csillag) Date: Thu, 18 Jul 2002 16:06:46 +0500 Subject: Appication server other than zope References: <20020718194213.22848.28280.Mailman@mail.python.org> Message-ID: <3D36A146.2010408@yahoo.com> > Hi. > I'm searching for application servers other than zope. Would somebody > tell me where to get such thing? I know of at least two (I know there are more), there's SkunkWeb (http://skunkweb.sourceforge.net) and WebWare (http://webware.sf.net). There are a bunch listed at http://www.python.org/cgi-bin/moinmoin/WebProgramming. I myself am partial to SkunkWeb, but don't take that as too strong of an endorsement as I am one of it's authors. Drew Csillag From tdelaney at avaya.com Wed Jul 24 20:36:56 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 25 Jul 2002 10:36:56 +1000 Subject: A better self Message-ID: > From: Terry Reedy [mailto:tjreedy at udel.edu] > > "Michael Chermside" wrote in message > news:mailman.1027533340.29544.python-list at python.org... > > # A program to sort lines. Takes, as command-line argument, a > ... > > But all of these are dwarfed (for large file sizes... let's say 1 GB > of > > text) by the fact that you are running a REALLY FAST sort algorithm. > > Few of us appreciate the days that Tim Peters spent writing a portable > sort program that is significantly better than standard quicksort for > several classes of input (such as a sorted list with new items > appended to the end). He is currently working on another that may be > even better. (Three horn toots for Tim.) That latest figures are *most* impressive. *No* categories of data (random, partially-ordered, etc) where there is a significant slowdown, most categories have a performance improvement, and it's a stable sort to boot. And he says that he can get a bit more improvement in a couple of cases ... (without special-casing mind you). I'm really looking forward to timsort replacing samplesort :) > > Of course, you could code the same sort algorithm in C yourself. > > Hmm. How many of us have both the skill and patience to develop and > test such a delicate and complex algorithm tweaked for various special > cases -- and apparently release it bug free (Tim says there has never > been a report of the current sort malfunctioning). And timsort manages to remove most of the special cases that samplesort was testing for. Of course, he claims the source of timsort is just as hairy and convoluted as samplesort ... Tim Delaney From sorry at no.mail.address Thu Jul 4 17:04:11 2002 From: sorry at no.mail.address (Tom Seddon) Date: Thu, 04 Jul 2002 21:04:11 GMT Subject: SSE With Swig References: Message-ID: In article , ajw126NO at SPAMyork.ac.uk says... > Hi, > > I'm trying to develop a Vector class that uses Intel's SSE extension. It > works very well when called using c or c++, but when I wrap the class with > Swig I get a privileged instruction exception error (this is under Windows > 2000 using MSVC++ 6sp5 with the processor pack installed). > > I've included the code below, any suggestions would be greatly appreciated > Andrew Wilkinson You probably need an align(16) in both declarations. Your class will come out at 32 bytes in size (4 bytes vtbl 12 bytes filler 16 bytes xyzw) but the class in the .I file is only 20 bytes in size. This might cause the problem. I assume swig needs to know about the class size to be copying the class around? But, and here is why I'm replying even though I know next to nothing about swig... it is bad form to return a pointer from an overloaded operator, particularly when that object was allocated on the heap. Who deallocates it? It is quite easy to lose the object entirely, producing a memory leak. (See Scott Meyers' book "effective C++". The short of it is: whilst you can get away from returning a fresh by value object, it is a bad idea and will bite you up the arse.) In addition, the time taken by new will DWARF the time taken by the add. I don't see the point of using SSE here. My suggestion is to replace your + with: const Vector operator+(const Vector &rhs) const { return Vector(this->x+rhs.x,this->y+rhs.y,this->z+rhs.z,this-> w+rhs.w); } Then replace this with the SSE version when this proves to be the bottleneck. Save yourself time and effort, and let the PC do the work... it won't mind, that's what it's there for. Also you have a virtual function in your Vector object. Why? This will increase the size of each Vector. -- -- --Tom tom under score seddon snail gmx stop co stop uk (spam paranoia) PS effective C++ ISBN is 0-201-92488-9, worth buying. From jacek.generowicz at cern.ch Thu Jul 25 09:18:15 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 Jul 2002 15:18:15 +0200 Subject: Completion in emacs mode Message-ID: Hi, I'm looking for the ability to do command completion in Emacs' python mode. I haven't managed to get Google to show me anything really pertinent to this quest. Any ideas ? Thanks, From emile at fenx.com Fri Jul 12 07:54:30 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Jul 2002 11:54:30 GMT Subject: Most pythonic way to format a number with commas? References: Message-ID: Alex Martelli > Emile van Sebille wrote: > > > > It's buried in locale... > > "buried" is a loaded word...:-) Yes... sorry ;-) That's just what it felt like the first time I needed it. And reflects in part a more recent run-in with locale. [clarifying and expounding remarks snipped] The other reason for my use of "buried" is my recent discovery of the source of a problem I experienced after writing a simple repeatable obfustication function to scramble text like customer names and addresses, and that initially depended on string.letters. ActivePython 2.1, build 210 ActiveState) based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'English_United States.1252' >>> string.letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz \x83\x8a\x8c\x8e\x9a\x9c\x9e\x9f\xc0\xc1\xc2\xc3\xc4 \xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1 \xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf \xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec \xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb \xfc\xfd\xfe\xff' >>> As this ran within zope, it was first imported as part of a product before setlocale happened elsewhere within zope. Only once zope was up and running the problem surfaced. The cvs version of zope shows that the errant module has been reworked and no longer uses locale. Then again, this may be common knowlege I'm only now finding out. But at least I'm forewarned for the next time I need to know my abc's _and_ put comma's in numbers. ;-) -- Emile van Sebille emile at fenx.com --------- From emile at fenx.com Fri Jul 5 20:40:38 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 06 Jul 2002 00:40:38 GMT Subject: IMAP Email Question References: Message-ID: Donn Cave > Quoth "Emile van Sebille" : > | Charel Yueng > | 'fname=charles\r\nfname=yueng\r\naddress=someaddress\r\n\r\n\r\n' > | >>> [x.split("=") for x in s.split()] > | [['fname', 'charles'], ['fname', 'yueng'], ['address', 'someaddress']] > > I suspect you're taking his example too literally. If the message > always looked just like that, then he could save himself the trouble > and just assume the result. Actually, I assumed from his statement: I then copy the message to another mailbox end then expunge it from the INBOX (that all works great) that the body wasn't the issue. OTOH, I also assume that a specific answer to a question will be projected onto the problem appropriately. OTOH, I also tend to take things literally... ;-) -- Emile van Sebille emile at fenx.com --------- From egbert at bork.demon.nl Tue Jul 30 15:50:02 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Tue, 30 Jul 2002 21:50:02 +0200 Subject: Cookbook: Associating multiple values with each key in a dictionary In-Reply-To: <20020730131414.C7503@eecs.tufts.edu>; from mgilfix@eecs.tufts.edu on Tue, Jul 30, 2002 at 01:14:14PM -0400 References: <20020730171536.A992@bork.demon.nl> <20020730131414.C7503@eecs.tufts.edu> Message-ID: <20020730215002.A2145@bork.demon.nl> On Tue, Jul 30, 2002 at 01:14:14PM -0400, Michael Gilfix wrote: > > I'm not really sure why you prefer the list method. Is there something > that you can't accomplish with the nested dictionaries? When I need { 'boys': ['mike', 'egbert'], 'girls': ['laura','lisa'] } it hurts me when I have to build: { 'boys': {'mike' : 1, 'egbert' : 1}, 'girls': {'laura' : 1,'lisa' : 1} } That adds an extra layer of complexity when i construct it, I have to remember or document that the values can be thrown away, and I have now sets of keys, while I need sets of values. I try to be a good pythonista, so I and simplicity come first, and efficiency and implementation come second. Of course that all changes when I really need the values, ie when they don't have some dummy value anymore. But in that case we simply have a nested dictionary, which is not our subject now. As an afterthought: is it necessary that lists are slower than dictionaries ? Cannot they be subjected to some hash machine as well ? At least in some cases, ie when you search in lists ? egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From anthony at interlink.com.au Tue Jul 2 02:22:24 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 02 Jul 2002 16:22:24 +1000 Subject: How to find out DNS ? In-Reply-To: Message-ID: <200207020622.g626MOM24622@localhost.localdomain> >>> "Steve Holden" wrote > In actual fact you could usually get the same answer by going to *any* DNS > server and asking "what is the DNS server from domain xxx.yyy.zzz" using a > query for NS resource records. Nitpick - this is only for servers that have recursion enabled, which is probably most servers "near" an enduser. If you were to go ask 'a.root-servers.net' for the NS records for 'interlink.com.au.', it'd point you at the servers for 'au.', and you'd be expected to do the next step yourself. big-nameservers-don't-have-to-play-nicely-yrs, Anthony -- Anthony Baxter It's never too late to have a happy childhood. From tim at remove_if_not_spam.digitig.cix.co.uk Fri Jul 12 12:37:08 2002 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Fri, 12 Jul 2002 16:37:08 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> <3D2E9052.2A8B60A6@alcyone.com> Message-ID: <3d2f058a.13107545@usenet.plus.net> >awful tool (often indicated by "X sucks" and "X is evil" without further >explication) and berate anyone who uses it. And to think I thought they were complaining about X-Windows :-) From roy at panix.com Mon Jul 15 08:12:55 2002 From: roy at panix.com (Roy Smith) Date: Mon, 15 Jul 2002 08:12:55 -0400 Subject: SNMP module in python References: <3d329ac0.330042218@news.skynet.be> Message-ID: pixie888 at hotmail.com wrote: > I am looking for a module written in Python to perform SNMP > communication. Can anyone tell me where I can find one? I've been using PySNMP, http://sourceforge.net/projects/pysnmp, which is written entirely in Python. Because it's 100% Python (all the way down to the messy BER stuff), it's very portable. On the other hand, I suspect performance is poor. I havn't pushed the corners of the envelope much, but so far it seems to work for basic stuff. The other alternative is yapsnmp, http://yapsnmp.sourceforge.net, which is a SWIG wrapper around the net-snmp (nee ucd-snmp) package. In theory, I like yapsnmp's approach better, but as a practical matter, getting it to compile and run has been problematical; I don't have exactly the same version of net-snmp installed as the author and ran into compile problems with mis-matched headers. From phr-n2002b at NOSPAMnightsong.com Fri Jul 12 02:58:56 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 11 Jul 2002 23:58:56 -0700 Subject: Python for data driven website? References: Message-ID: <7x7kk1o2j3.fsf@ruckus.brouhaha.com> You should read Philip Greenspun's book "Philip and Alex's Guide to Web Publishing", http://philip.greenspun.com/panda Also available in dead tree form. From tom.verbeure at verizon.no.sp.am.net Sun Jul 28 13:23:57 2002 From: tom.verbeure at verizon.no.sp.am.net (Tom Verbeure) Date: Sun, 28 Jul 2002 17:23:57 GMT Subject: How to detect the last element in a for loop References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: Roy Smith wrote: > Tom Verbeure wrote: >> say, 10 lines of code. Too much to duplicate it outside the loop, not >> enough for a separate function... > > Why is 10 lines of code not enough for a separate function? I use > functions to group code into conceptual blocks that can be thought about > and understood as a unit. Sometimes that block is 100 lines of code, > sometimes it's 3 or 4 lines. I've even written one-line functions. > Whatever makes sense to factor out as an atomic unit. Line count has > little to do with it. Ha! Now we are talking style! :-) Yes, that's, of course, an option also, but we are moving away from the original question and I feel guilty already wasting this forums' reader time with my trival question... My main reason not to use function in this case, is that it may result in moving meaning full code too far away from where the action is. However, after reading some things on the web, I can solve this by added nested functions: def BigFunction: < lots of code > def DefaultForLoopCode(): pass for a in myList[:-1]: DefaultForLoopCode() DoExtra() DefaultForLoopCode() I think this will solve my problem, while still keeping everything relatively clean. Thanks, Tom From mcfletch at rogers.com Tue Jul 2 05:36:22 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 02 Jul 2002 05:36:22 -0400 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: <3D217416.6080006@rogers.com> Well, that answers that question, I suppose. No clue what a surrogate is for, but I suppose there's no point including them in a character-classes set if they're designed specifically as unicode internal chars. Thanks Martin, Mike Martin v. Loewis wrote: > "Mike C. Fletcher" writes: ... >>I was under the impression that utf-8 was supposed to be able to >>support any Unicode character with full back/forth translation. > > > That impression is incorrect: Surrogates (as reserved in Unicode, for > use with UTF-16) are special. > > Regards, > Martin ... From opus at value.net Sat Jul 13 07:37:29 2002 From: opus at value.net (Opus) Date: Sat, 13 Jul 2002 04:37:29 -0700 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <3D300244.3089F1C4@cascade-sys.com> Message-ID: <3D2FAE89.21082.361CABA@localhost> I like the idea of tabular format of code, and it brings back thoughts of my days of programming in RPG. For anyone that has had to use it, you know what I mean. For those that don't, writing code in it meant that you have a form that you wrote the code on, then you typed it in. And, then you counted spaces if you had a bad editor, or you let the editor count them for you if you had a good one. RPG needs everything to be in the correct column. As for the nicest formated languages for reading, coding and debugging, I would have to say that my experience with 4Test (the language developed by Segue for QA Partner and Silk) was the best I have had. It required that you use the IDE (you could use a text editor if you really wanted, but why?) to enter code. The IDE and the language supported collapsible blocks. When you were coding, it automaticly indented for you, and showed a [-] next to the line to show that you could collapse it. A [+] showed that you could expand it. The IDE also had options to expand and collapse the current block, all sub blocks, and the entire file. Because it was saved as a text file that was then checked into a repository, it was a company standard to collapse all blocks before checking it in. The great advantage here was that in reading the code, you could get an overview of lots of lines of code, and then drill into smaller chunks for more specific details. For entering the code, it enforced a standard indentation, and like Python, you unindented to end a block. >From the point of view of someone that has sat down to write a program with out a detailed spec (and from someone that knows that this happens IRL), the ability of a language to allow the developer to quickly see emerging patterns that can be broken into function calls (or macros, or what ever) will speed the development, debugging, and maintenance phases of code. As to style, that is something that is best agreed upon with all that are going to touch any bit of code. To choose a global style standard is a good idea IMHO. To realize and modify that standard within the group of developers is also a good idea. I believe that at one point some one did not like: } else { Well, this might be a good place to warp the standard to your taste, and those around you, or live with it if they don't want to. Reading code out side of one's normal style can be difficult. To comprehend the code can also be difficult. I have found that I like a certain level of comments, and I try to comment my code as much as possible. But, I have seen where the comments were like Kudzu, you could not see the code that actually did the work. Well written and understandable code is much like a well written book, a pleasure to read, where as badly written code is a pain. These are just my rambling $0.02 worth. Thought I would share them with ya. On 13 Jul 2002 at 3:34, James J. Besemer wrote: > > Donn Cave wrote: > > > We can say "follow the standard", or we can say "follow the standard > > unless you have some other idea." > > In merely advocating flexibility on minor points in the standard. I am in no way > advocating total anarchy as you suggest in this rhetorical statement. I think > rather you are the one advocating the extreme view. If you hadn't said "to the > letter" and furthermore objected to Mr. Corns perfectly reasonable suggestion in > your previous post, I probably would not have taken exception. > > Furthermore, we're talking about a sub-heading marked "pet peeves", which I read > as one of the more advisory parts of the standard, something you follow more or > less closely depending on how much you want to emulate a particular individual. > It's not a vital part of the standard. > > Browsing through the 2.2 Library, about half the modules I checked exhibited > deviations from the standard re horizontal whitespace. So not too many key > contributors appear to share your zealous view on this particular point. > > > If you have a good way for people > > to tell the difference between their own personal idiosyncrasies and > > a really good idea that really deserves to be an exception, that > > would be interesting. > > Well, you're asking for an algorithm which anyone would be hard pressed to > provide. I guess that makes the question rhetorical. Howver, I am prepared to > defend tabular organization of code. > > Tabular data is such a common paradigm in computers and in printed reports > precisely because it is a tremendous aid to comprehension. In programming, first > off, you are clued in that the corresponding section of code is highly > repetitious. Second, you are shown that each repeated part may be logically > divided into parallel pieces with similar roles. Most importantly, a tabular > format tells you at a glance those code fragments that are common among all the > various cases, those that are common only among a subset and those that are unique > in each case. Finally, it just looks neater. I don't see how you can argue that > to jumble the stuff all together (thereby eliminating these choice visual cues) > makes tables or highly parallel code EASIER to read. > > In my experience, code comprehension takes place at two levels. At the higher > level, humans perceive pages or "paragraphs" at a time. This is why proper > indentation is to vitally important. The left whitespace and the leading keywords > give you a lot of information about the overall structure of the program without > having to read each line. It helps you navigate the code and provides a context > for local changes. Tables are another aid to comprehension at the higher level. > > At a lower level, you zoom into individual statements, comprehend and edit them. > > > Once a coding style has > > really become standard, deviations from it will tend to be less readable > > for most of the people who are used to that standard, and it makes no > > difference if the deviations are in principle superior. > > In this PEP 8 itself seems to contradict you by saying one explicit reason for > breaking the rules is: > > (1) When applying the rule would make the code less readable, even > for someone who is used to reading code that follows the rules. > > Even if you still disagree about tabular formatting specifically, the express > directive here seems to be to NOT compromise the principle of readability in favor > of standards as you suggest. > > PEP8 covers vitally important major issues (like indentation) and it covers lesser > issues down to the level of horizontal whitespace (beyond tab stops), which > frankly I've NEVER seen in a coding standard. Nevertheless, I even agree with a > lot of THOSE details, e.g., spaces around assignments and after commas. > > I think your point is perfectly valid about the big issues, particularly those > that affect comprehension at the higher level. But it breaks down when it comes > to some of the nitty details, which I bet most users can't exactly recall. I > leave that trivia to the Hobgoblins. > > > By the way, speaking of style - you may not have noticed that you > > formatted your post to 84 columns. 75 or less would be nice. I > > reformatted for you. > > According to my Preferences settings, Netscape is supposed to wrap outgoing > messages to 66 columns. Like a lot of free software it doesn't always do the > right thing. Dunno where the 84 came from, probably the listmanager. > > On the plus side, Netscape wraps lines on incoming messages to my window width, > which is great. So I don't ever find myself in the position of complaining to > others about what amounts to a limitation of my own tools. > > Regards > > --jb > > -- > James J. Besemer 503-280-0838 voice > http://cascade-sys.com 503-280-0375 fax > mailto:jb at cascade-sys.com > > > > > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- You can't tell me what sucks! - Beavis, a true Objectivist. -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From phr-n2002b at NOSPAMnightsong.com Tue Jul 9 02:22:40 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 08 Jul 2002 23:22:40 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <7x8z4lwhcf.fsf@ruckus.brouhaha.com> curt at journyx.com (curt finch) writes: > Python is often used as pseudocode to conduct rapid development. Its > major users are web sites that do not reuse code and often conduct > “throw away” development to meet internet development time > tables. It is a very new language and has very little support compared > to the Java development community. It is also not J2EE compliant. Above is FUD though not being J2EE complaint is true (and a virtue) > Platform Drawbacks > As a new relatively untested development platform in the licensed > software community, Python has certain deficiencies with which all > users and developers should be aware. As if J2EE has been around since forever? FUD. > Issues and concerns > > ? No integrated GUI (Graphic user interface) support. Somewhat true > ? No compiler to the native code. Definitely true and a deficiency that should be corrected sooner or later. > ? No automatic garbage collection. False for most practical purposes > ? Does not have vast number of libraries as that of Java, > Perl, C++; etc. True > ? Since Python is an interpreted language, it requires > frequent run-time checks and thus does not provide the speed, > performance and efficiency of compiled languages like Java, Perl and > C++, which is a major issue. Non-sequitur. Python needs runtime checks because of its dynamic typing. However it should still be possible to compile Python. > ? Python does not provide multiple ways to perform tasks as do > most other languages. False and a bizarre claim. > ? It takes a lot of time for Python to adjust to the > indentation style of the structuring code. False. It is a little disconcerting at first but most people get used to it pretty fast. > ? Since Python is relatively a new language, there are only a > few resources available for information on its latest developments. Semi-true, but in practice the resources are good enough. > ? Limited documentation- only two English language books exist > which provide tutorials or a library reference for Python. Not true any longer. > ? The language is restricted to fewer code modules. Incomprehensible. > ? Lacks native threading capabilities. True. There's a threading module that's similar to java threads, but there's no built-in language support like java's synchronized classes. > ? Lacks basic tools such as integrated source level debuggers. There are some proprietary ones that I haven't tried. There's a free one (IDLE) that's not very impressive. OTOH, Java's debugging support isn't so great either. > ? No packaging methods for software distribution. False. > ? Lacks tools to solve typographical and type mismatch classes > of errors. Not too big a problem in practice. > ? Python cannot write docstrings in C++. Huh? J2EE can't either. Why is this a problem for either? > ? Python is difficult to read. FUD. Java is worse. > ? Dynamic loading is not available on all systems, requiring > that a developer use static loading. Huh? Same is true for Java. Python can always load Python modules (similar to Java class loader). Loading native modules (like Java JNI) dynamically isn't always possible, just like with Java. From logiplexsoftware at earthlink.net Wed Jul 10 13:07:36 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 10 Jul 2002 10:07:36 -0700 Subject: openprojects python room is ruled by dangerous people In-Reply-To: References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: <20020710100736.6f86159d.logiplexsoftware@earthlink.net> On Tue, 09 Jul 2002 23:04:03 GMT Fredrik Lundh wrote: > Martijn wrote: > > > They do kick you out a bit readily, I agree. I got somewhat annoyed > > when I got kicked out while apologizing for spamming with a misfired > > copy & paste buffer. > > the first time I visited, I was kicked out (and banned, iirc) > within a couple of seconds... > > Yes, but in that two seconds you repeated "Google is your friend" 12 times. ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From jknapka at earthlink.net Wed Jul 3 01:04:27 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Wed, 03 Jul 2002 05:04:27 GMT Subject: what can i expect... References: Message-ID: <3D228567.5C332836@earthlink.net> "Delaney, Timothy" wrote: > > > From: Shagshag13 [mailto:shagshag13 at yahoo.fr] > > > > what can i expect if i change my python application to java ? > > (or when do you think it's time to change parts of python > > code to java ? for what purposes ?) > > Apart from the other (very well reasoned answers) ... > > The only time you would generally want to change python code to java is so > you can run on a JVM or interface with java code. > > In which case you do *not* want to convert your code to java. Instead, you > want to run your Python code on a JVM. > > http://www.jython.org/ How about, "If you want your multi-threaded code to run faster on a multi-CPU system"? That's really the only advantage of Java over Python that I see: its threading implementation is clearly better. But I still wonder if Jython threads acquire the Global Interpreter Lock (or if the GIL exists in Jython at all)? -- Joe From opengeometry at NOSPAM.yahoo.ca Mon Jul 22 12:35:35 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 22 Jul 2002 16:35:35 GMT Subject: Need some help please References: <2j2hju8c1btu76tu896cuc9qg6oeep9uoi@4ax.com> Message-ID: Arneau Starl wrote: > I have a stripped down (minimal software on it) ftp server that does > have python 2.2 on it.. Here is what I need to do: > > There is no gui on this redhat machine so I need to have a simple > commandline process to add ftp user accounts I could do this by hand > but then I would have to make them all , I need be be able to make it > easy so another less unix savvy person can create accounts > > I need to be able to execute a python script (mkacnt) with 2 > arguments username and email address. The script does 4 things > ("mkacnt name email") 1: create ftp user account with "adduser" 2: > create random password 3: execute "passwd username " and then update > the password with the one just generated. 4: Email the username and > password to the email address supplied above. > I have 1 ,2 & 4 working I cannot figure out a way to do the password > without Expect (which I cannot install on that machine). Is there a > way around this? - insert the password into /etc/passwd and /etc/shadow directly. - pipe your commands into Telnet session (or Python equivalent thereof) ( echo login-password; sleep 5 echo su; sleep 5 echo root-password; sleep 5 echo passwd username; sleep 5 echo login-password; sleep 5 echo new-password; sleep 5 echo new-password ) | telnet -l user localhost - there may be other simple solution using I/O redirection on the console directly. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From mikew at wakerly.com Fri Jul 12 20:46:56 2002 From: mikew at wakerly.com (Mike Wakerly) Date: Fri, 12 Jul 2002 17:46:56 -0700 (PST) Subject: Bitshifted exit status from Popen3 Message-ID: <200207130046.UAA10442@arkroyal.cnchost.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From peter at engcorp.com Tue Jul 23 22:11:58 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Jul 2002 22:11:58 -0400 Subject: Mastering Regular Expressions 2nd Ed. References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> <7xn0si9o2o.fsf@ruckus.brouhaha.com> Message-ID: <3D3E0CEE.E3B3B4A0@engcorp.com> Neil Schemenauer wrote: > > Paul Rubin wrote: > > Argggh! That sounds like regular expressions aren't really the best > > way to match RFC822 addresses. > > Regular expressions work much better if you use them for lexical > analysis rather than for parsing. Would you please expand on that for those of us who are not computer scientists and/or who do not understand the implications of your statement? Thanks, -Peter From nde at comp.leeds.ac.uk Fri Jul 19 10:28:34 2002 From: nde at comp.leeds.ac.uk (N D Efford) Date: Fri, 19 Jul 2002 14:28:34 GMT Subject: Percent sign in format string? References: Message-ID: Ron Levine wrote: > How can I put a "%" sign in a format string? %% N. From fredrik at pythonware.com Tue Jul 9 19:04:26 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 09 Jul 2002 23:04:26 GMT Subject: How to grab a part of web page? References: Message-ID: <_ZJW8.46998$n4.11321007@newsc.telia.net> "A" wrote: > Is it possible to download only a part of web page? > Say I need to find out an information about a customer that starts > at 1500 byte position and ends at 2000 byte position. If the whole > page has about 100 kb it seems to me waste of time to load all the > page. import urllib file = urllib.urlopen(DATA) data = file.read(2000) file.close() print data[1500:2000] From mis6 at pitt.edu Fri Jul 5 12:52:49 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 5 Jul 2002 09:52:49 -0700 Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <3D2487CB.9000102@gmx.de> <3D24FAC5.3050406@something.invalid> Message-ID: <2259b0e2.0207050852.3b603a9a@posting.google.com> Greg Ewing wrote in message news:<3D24FAC5.3050406 at something.invalid>... > > On the other hand, a situation that *is* very common is > a loop-and-a-half, with the exit condition in the middle. > So far, I've never seen *any* really good loop-and-a-half > structure in any language, and I think Python has a chance > to be truly innovative here. > > The syntax I favour at the moment for Python looks like > > while: > line = f.readline() > gives line <> "": > do_something() > > Some day I'll get around to PEPping this... Python2.2 has already for line in f: do_something() where f is a file object. -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From jayantkawadkar at hotmail.com Tue Jul 23 08:43:16 2002 From: jayantkawadkar at hotmail.com (jayant kawadkar) Date: Tue, 23 Jul 2002 18:13:16 +0530 Subject: Help On file IO Message-ID: Hello , I want a help on File IO ,as I 'm new to Python langauge. As I want to use the API : char* PyModule_GetFilename(PyObject *module) in my python programm What should I import for that I can use this . Now it is giving the error that: PyModule_GetFilename is not defined. Plz help .... jayant _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From peter at engcorp.com Sun Jul 21 01:19:40 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Jul 2002 01:19:40 -0400 Subject: getting date into rfc822 format References: Message-ID: <3D3A446C.27473838@engcorp.com> "Jon J. Morin" wrote: > > date = time.ctime(time.time()) > > Which gives me a date like this: > Sat Jul 20 00:02:03 2002 > > When what I want is something like this: > Fri, 01 Mar 2002 00:18:17 -0500 (EST) > > Incidentally, I have read the rfc822 and I can't figure out what the -0500 > is in the date/time. Can anyone explain this to me? See http://www.python.org/doc/current/lib/module-time.html and search for "RFC 2822" or look at the strftime() formatting codes. The -0500 is a representation of the time difference between your local time and UTC. In this case it means your time is 5 hours behind UTC. For email you should be able to put the time in UTC, so use time.gmtime() as shown in the example in the docs. -Peter From jacek.generowicz at cern.ch Thu Jul 11 03:33:44 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jul 2002 09:33:44 +0200 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: "Steve Menard" writes: > "Jacek Generowicz" wrote in message > news:tyf7kk4jauz.fsf at pcitapi22.cern.ch... > > > > I'll second that. I was about to have a look, and then saw the doc > > extension. I take doc extensions to mean "This document is intended > > for Microsoft customers only". I am not a Microsoft customer. > > See, this is something I really don't understand. I will agree that PDF or > html would have been a better choice, but not everyone can generate PDF ya > know. I would say that Generating PDF is, in general, not significantly more difficult than decoding .doc ... if you can be bothered. (I have to have a high degree of confidence that the content of the .doc will be important to me, before I can be bothered to decode it.) > With this kind of attitude, we'll forever be regarded as the > extremists who won't listen to anything .... There is a lot of information out there which vies for my attention. Extensions such as .doc, .ppt etc. offer a handy first order filter in my process of selecting what I should bother to dowload and read. I freely offer this information to people who might want me to read something they send me or to which they provide URLs. They are just as free to ignore the information I provide, as I am to ignore the information they provide. If this seems extreme, well, so be it. From opengeometry at NOSPAM.yahoo.ca Fri Jul 19 18:57:03 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 19 Jul 2002 22:57:03 GMT Subject: Recursion References: Message-ID: >> def showbits(x): >> if x != 1: >> showbits(x >> 1) >> if x & 01: >> print 1, >> else: >> print 0, Final answer: def showbits(x): if x <= 1: return `x` else: return f(x>>1) + `x&1` -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From roy at panix.com Sat Jul 13 13:34:13 2002 From: roy at panix.com (Roy Smith) Date: Sat, 13 Jul 2002 13:34:13 -0400 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3D2FAE89.21082.361CABA@localhost> Message-ID: Ian Bicking wrote: > One thing I wonder... would it be possible to use Emacs outline mode > with the python mode, so that every syntactic : is a level in the > outline? (well... I'm sure it's possible, but has anyone already done > it?) I wonder if, in the long run, that would be a good thing or a bad thing? I like to have a given function small enough to see the whole thing on one screen (which typically means about 60 lines of code maximum). It's not a hard and fast rule, but I find that if I can't see it all at one time, it's harder for me to understand what it's doing. Once something gets so complex that I can't fit it on one screen, I start looking for ways to (buzzword alert) refactor the code. That typically means finding some hunk of code which can/should logically be broken out as its own function. That function, in turn, can get its own explanitory comments and unit tests. My fear is that if I could just collapse the body of a compound statement with a single click, it would be too tempting to write huge monolihic functions that go on for hundreds of lines. From jon+usenet at unequivocal.co.uk Wed Jul 3 12:37:35 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 03 Jul 2002 16:37:35 -0000 Subject: Comments in pickles? References: Message-ID: In article , Tim Peters wrote: > In short, an embedded $Id never did me any good, but has wasted my time and > tempted people to write code with severe bugs. If you just leave the $Id as > a passive piece of a comment, I suppose the real damage is limited to making > merges artificially painful. I would like to encourage everyone *please* do include CVS ID comments in your code. They are incredibly useful. They have helped me out no end of times when dealing with other peoples' software. When you download programs as tar.gz files, unless you have included the CVS ID as comments in the files, you have no idea what versions you have, and therefore have great trouble trying to compare it with the CVS repository for the project. I agree on the other hand that using the ID as anything other than just a comment is unwise, but I can't imagine why anyone would do such a thing anyway. From andreas at kostyrka.priv.at Wed Jul 24 10:41:28 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 24 Jul 2002 16:41:28 +0200 Subject: __del__ in classes derived from Tkinter classes In-Reply-To: References: Message-ID: <1027491921.4164.69.camel@vaio2> Am Fre, 2002-07-19 um 13.12 schrieb Petr Klyushkin: > Fredrik> (and using __del__ is usually bad style even outside > Fredrik> Tkinter, but that's another story). > > Why? Well, actually because at best it's implementation dependant, at worst it doesn't work at all. (And that's not really a bug, it's just how liberal the Language Reference defines these things.) -) You do not have control of the destruction time. gc might destroy an object at any time after it becomes inaccessible. The reference even allows implementations not to destroy it at all. -) Because you do not know when it is run, you cannot know what other objects and services are still available. Basically the destruction order is not defined. -) So your options what you can do inside __del__ are quite limited. * It must be able to run at any time. * And the program must work without the __del__ handlers being called. example: class T: def __init__(self,v): self.v=v def __del__(self): print "DEL",self.v def f(): t1=T(1) t2=T(2) f() Results: andreas at vaio2:~> python t2.py DEL 2 DEL 1 andreas at vaio2:~> jython t2.py andreas at vaio2:~> Andreas From joost_jacob at hotmail.com Thu Jul 25 09:03:19 2002 From: joost_jacob at hotmail.com (J.Jacob) Date: 25 Jul 2002 06:03:19 -0700 Subject: programming with XML-RPC in Python References: <13285ea2.0207241454.583c743f@posting.google.com> Message-ID: <13285ea2.0207250503.b974470@posting.google.com> I put a new improved version at: http://www.liacs.nl/~jjacob/swc/swc.zip About this project: Goal: ----- Provide functions to turn a Python class into a server offering selected methods from the class for remote usage via internet. The server can also have a quit method and methods for adding and managing clients and for sending events to the clients in an asynchronous way (without waiting for a return value). This way processes written in any computer language and running on any OS platform could work together. Design goals: ------------- * Only use modules in the default Python distributions and supply everything else. If possible stay backwards compatible with Python version 1.5.2 until a higher Python version becomes the default at most places. * No modification of existing code necessary if you want to turn a class into a server. There is still a lot to do and to investigate: ---------------------------------------------- * Stopping a server remotely is done with a global module variable, this is looking ugly. * The asynchronous event sending is not really asynchronous: it also uses XML-RPC and does a synchronous method call in a thread. Ideally it should use UDP instead of TCP? For this the server could be equipped with a method that returns the location of an event handler that accepts UDP events. * The interface definition for servers is done with a simple list of strings for the method names. Maybe a class-interface mechanism would be a better design here. * XML-RPC is used for remote method calls, I have no idea if XML-RPC is the best choice for this but it certainly was the easiest to implement (other choices were CORBA [what a hairy #$?%!] and SOAP [fluctuating standard problems]). * A function or class method to log in to another computer with your username and password (encrypted!) and moving a running server over there and letting all clients know the new location (host,port). * Better documentation. From a-steinhoff at web.de Fri Jul 19 05:41:30 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 19 Jul 2002 02:41:30 -0700 Subject: Tkinter vs. wxPython References: Message-ID: "Gabe Newcomb" wrote in message news:... > Ack! > I've been trying to get into wxPython, but I'm finding the lack > of documentation difficult. There's some, and I'm very grateful for > everybody who's contributed it, but I'm somebody who really likes having > a decent reference and more examples. IMHO ... more examples means only more confusion. What is needed is a good formal documentation ... like the Qt docs. > My question is this: is there any compelling reason I shouldn't just go > with Tkinter instead? I work (for now) exclusively on Win32 boxes, by > the way. I have recently switched from wxPython to PyQt because of the very weak docs of wxPython. PyQt is a stable and good documentated alternative ... the current version works very well. Armin From max at alcyone.com Fri Jul 12 04:10:56 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Jul 2002 01:10:56 -0700 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> Message-ID: <3D2E8F10.B9B4EFD2@alcyone.com> Peter Hansen wrote: > Since you post without smileys, I can only assume you are serious? Yes, that's right. Any post that doesn't contain a smiley is always absolutely dead serious. > To which my response is: you can't be serious. :-) :-) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From fperez528 at yahoo.com Tue Jul 2 17:51:23 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 02 Jul 2002 15:51:23 -0600 Subject: Splitting Text files References: <%XnU8.4057$aJ4.853781@news20.bellglobal.com> Message-ID: Ken Seergobin wrote: > Thanks. Csplit makes the task much easier! The [snip] This is an excellent example where a 'main' python script encapsulating the trickier logic, judiciously driving at various point some of the many low-level unix tools can be the best option. Many of the unix text tools are fabulous, fast and efficient, and there's no point in recoding all that with python (as long as you don't need portability to windows). So using them at a few key spots can be a huge time saver. Think of the unix toolkit as an extension to the python standard library, if you will :) cheers, f. ps. and thanks to the op for csplit! after years of grep/sed/awk/paste/col/split/join, I'd never heard of it :) From 102030405 at gmx.net Sat Jul 13 08:54:27 2002 From: 102030405 at gmx.net (Ralf Claus) Date: Sat, 13 Jul 2002 14:54:27 +0200 Subject: login with python (2) References: Message-ID: "Fredrik Lundh" schrieb im Newsbeitrag news:LWUX8.15865> something like this could work (untested): > > import urllib > > LOGIN = "http://192.168.2.1:/login.htm" > > SITE = "go" > PASSWORD = "..." > > data = urllib.urlencode({"site": SITE, "password": PASSWORD}) > file = urllib.urlopen(LOGIN, data) > > print file.headers > print file.read() > > study the headers and the page contents carefully to see what > you need to do next (the site may be forwarding you somewhere, > possibly using javascript; it may use cookies, etc) Hello, next to do is to type in the password :( print file.read() is the content of the login page...... thx for your ideas From darnold02 at sprynet.com Sun Jul 28 11:45:06 2002 From: darnold02 at sprynet.com (Don Arnold) Date: Sun, 28 Jul 2002 15:45:06 GMT Subject: pickling problems with Pmw/Tkinter Message-ID: I'm trying to develop a Tkinter app that pickles the values of a couple of Pmw counters. Then on its next run, it unpickles these values and loads them back into the counters. That's the plan, anyway. Here's what I have: import pickle, Pmw from Tkinter import * class OptionData(object): def __init__(self): self.minlenval = 0 self.maxlenval = 0 class app(Frame): def __init__(self): self.picklefilename = '/python22/mystuff2/test.dat' self.options = OptionData() self.loadoptions() Frame.__init__(self) p2 = Pmw.Group(tag_text = 'Dictionary') self._minwordlen = Pmw.Counter(p2.interior(), labelpos = 'w', label_text = 'Minimum word length:', entry_width = 2, entryfield_value = self.options._minlenval, entryfield_validate = {'validator' : 'integer', 'min' : 1, 'max' : 20}) self._maxwordlen = Pmw.Counter(p2.interior(), labelpos = 'w', label_text = 'Maximum word length:', entry_width = 2, entryfield_value = self.options._maxlenval, entryfield_validate = {'validator' : 'integer', 'min' : 1, 'max' : 20}) fields = [self._minwordlen, self._maxwordlen] Pmw.alignlabels(fields) for field in fields: field.pack(side = TOP, padx = 5, pady = 5) p2.pack(fill = 'both', expand = 1, side = TOP) self.bind('',self.shutdown) def loadoptions(self): print 'loading options...' try: picklefile = file(self.picklefilename,'r') self.options = pickle.load(picklefile) print 'options loaded' except IOError: print 'using defaults' self.options._minlenval = 3 self.options._maxlenval = 6 def saveoptions(self): print 'saving options' self.options._minlenval = int(self._minwordlen.get()) print 'min =', self.options._minlenval self.options._maxlenval = int(self._maxwordlen.get()) print 'max =', self.options._maxlenval picklefile = file(self.picklefilename,'w') pickle.dump(self.options,picklefile) print 'options saved' def shutdown(self,e): print 'app shutting down' self.saveoptions() root = Tk() Pmw.initialise(root) app().mainloop() Here's what shows in my console window when I run it: D:\Python22\mystuff2>test.py loading options... using defaults app shutting down saving options D:\Python22\mystuff2>test.py loading options... using defaults app shutting down saving options Not only aren't the options being saved, I'm not seeing any of the 'print' lines in saveoptions() after the first. No exceptions are being raised, but it's not working. Any ideas on what's happening here? Thanks, Don From max at malva.com.uaREMOVE.IT Thu Jul 11 01:09:06 2002 From: max at malva.com.uaREMOVE.IT (Max Ischenko) Date: Thu, 11 Jul 2002 08:09:06 +0300 Subject: Python in the enterprise: Pros and cons References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: builder wrote: > Python has many fans in the open source community, but is it ready for > the enterprise? Here are the advantages and disadvantages of using > Python in the corporate environment. > http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm After reading their ah...well...stupid article about XP, I won't even bother to look at this. -- You have to think in a language to write programs in it, and it's hard to want something you can't describe. -- Paul Graham. From edream at tds.net Wed Jul 10 11:35:16 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 10 Jul 2002 15:35:16 GMT Subject: Fwd: Re: newbie: binding args in callbacks References: Message-ID: <3D2C5432.79B4EDEF@tds.net> Martin Franklin wrote: > Create a callback class that uses the built in __call__ method [snip] Interesting approach. Thanks for suggesting it. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From mal at lemburg.com Fri Jul 26 12:03:59 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Fri, 26 Jul 2002 18:03:59 +0200 Subject: mxODBC Zope Database Adapter References: <3D2D4008.2010705@lemburg.com> <3D417260.4070802@lemburg.com> Message-ID: <3D4172EF.3030502@lemburg.com> As you might have read, eGenix is currently developing a new mxODBC Zope DA and we are making good progress at it. If anyone here is willing to join the alpha testing team, please drop me a line. The mxODBC Zope DA will provide enterprise level stability and performance on both Windows and Unix platforms. It already implements connection pooling, parallel execution of Z SQL Methods, connection fail-over and thread-safe transactions. Thanks, -- Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From a-steinhoff at web.de Wed Jul 31 14:53:21 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 31 Jul 2002 11:53:21 -0700 Subject: global interpreter lock not working as it should References: <7xptx4z7to.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xptx4z7to.fsf at ruckus.brouhaha.com>... > anton wilson writes: > > > Quick tangential question: if there's no blocking of any kind, why are you > > > using threads, anyway? Off the cuff thinking says this seems like a misuse > > > of them. > > > > For a real-time system. ;) It will work. It would just be nice if they > > switched exactly every 10 byte codes becuase that means they only use about > > 10 to 20 milliseconds each. > > Maybe you want to switch to Stackless Python and use microthreads. > See www.stackless.org. When we talking about real 'real-time' ... then you should use QNX6.2 plus Stackless Python :) Python 2.2.1 for QNX6 is available at http://www.sf.net/projects/pyqnx There is also a 'configure script' .. Cheers Armin From tanzer at swing.co.at Sat Jul 13 05:48:22 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Sat, 13 Jul 2002 11:48:22 +0200 Subject: switch recipe? In-Reply-To: Your message of "Sat, 13 Jul 2002 01:20:47 CDT." Message-ID: "Mark McEahern" wrote: > > So where I've ended up is a place I'm sure there's some fancy > > name for--but I don't know it. > > The thread on zip suggests the term "lockstep iteration." I can't use > map or zip though because I have an unbounded iterator. Not so. As long as one of the iterators is finite, zip will work: >>> from __future__ import generators >>> def repeat(*args): ... """Return a repeating alternator for args.""" ... while args: ... for a in args: ... yield a ... >>> for i, j in zip(range(5), repeat("a","b","c")): ... print i, j ... 0 a 1 b 2 c 3 a 4 b -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From pyth at devel.trillke.net Wed Jul 24 08:00:22 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 24 Jul 2002 14:00:22 +0200 Subject: cmd, readline, and /path/filename completion In-Reply-To: ; from mwh@python.net on Wed, Jul 24, 2002 at 11:16:28AM +0000 References: Message-ID: <20020724140022.G10625@prim.han.de> Michael Hudson wrote: > Dave Cinege writes: > > I'm trying to tweak the readline functionality, and am a bit lost. > > > > In Bash > > cd /etc/ > > Will display a list of files in /etc/ to complete against. > > > > In my shell, I will always see the files in the current directory. > > > > What must be done to mimic the bash functionaly? Is it an option that > > must be turned on in readline? Do I have to snag the line, and if it is a > > valid path, cd to that path? (then back to PWD) > > I'm guessing that you need to fiddle what characters readline thinks > are word boundaries. readline.set_completer_delims looks hopeful. More exactly, the OP needs to erase the '/' character from the delims list. e.g. readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>?') should work the way you want it. Are you implementing your own completion handler? holger From bokr at oz.net Thu Jul 25 17:02:51 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 21:02:51 GMT Subject: if(debug), optimized away? References: <3d4045be$0$94920$e4fe514c@dreader3.news.xs4all.nl> Message-ID: On Thu, 25 Jul 2002 20:39:32 +0200, Yigal Duppen wrote: >> if(debug): >> if(items > 9): >> print "fatal error..." >> do_some_check_foo(42) >> ... >> >> If I set debug=0, is this code optimized away as in most >> C/C++?? compilers? > >I doubt it. >However, if you use the (predefined) __debug__, it does get optimized away >(at least, I think so). > >if __debug__: > # do stuff > >Note that you cannot set __debug__; it is always true, except when running >python with the -O flag. > You are right: [14:09] C:\pywk\junk>python -O Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> __debug__ 0 >>> __debug__=1 File "", line 1 SyntaxError: can not assign to __debug__ >>> from miscutil import disex >>> disex("""\ ... if __debug__: ... a='debug' ... else: ... a='no debug' ... """) 0 LOAD_CONST 0 ('no debug') 3 STORE_NAME 0 (a) 6 LOAD_CONST 1 (None) 9 RETURN_VALUE (disex is just a convenience thing of mine using compile and dis) >Furthermore, for checks such as these it is better to use the 'assert' >keyword. This too is removed when python -O is used. > >assert items > 9, "Fatal error, too many items" > Regards, Bengt Richter From marcoxa at cs.nyu.edu Fri Jul 12 11:35:32 2002 From: marcoxa at cs.nyu.edu (Marco Antoniotti) Date: 12 Jul 2002 11:35:32 -0400 Subject: Calling Python from Allegro Lisp References: <3D2EC4B5.1070605@thomas-guettler.de> Message-ID: Thomas Guettler writes: > Hi! > > I have an old application which needs to call python. > The old app is written in allegro lisp. > > I tried the following: > (defparameter hlib "c:\\winnt\\system32\\python22.dll") It's be better to say (defparameter *hlib* (parse-namestring "c:\\winnt\\system32\\python22.dll")) > (probe-file hlib) This will just return the above pathname or NIL. > (ct:defun-dll Py_Initialize() > :return-type :void > :library-name hlib > :entry-name "Py_Initialize") > (ct:defun-dll PyRun_SimpleString((s :char *)) > :return-type :long > :library-name hlib > :entry-name "PyRun_SimpleString") > > (Py_Initialize) > (setq foo "print 'foo'") > (PyRun_SimpleString (cref (ct:char *) foo 0)) > > But get: > """ > The first element (CREF (CHAR *) foo 0) of a function > application is not a function name > """ After your setting up of your Python Library you have ended up with a function called PyRun_SimpleString (Note that ct:defun-dll may not be the best way to achieve this) You are calling the above function of the value that the macro CREF. However, note that CREF is in the CT package and that you may or may not have that symbol available in your code snippet. Try putting the fully qualified name in your code: CT:CREF. > What could be wrong. (with-sarcasm () (print "Wanting to use Python?")) > I am new to lisp Then stick with it. Rewrite the Python stuff in a better language and live happier everafter. Cheers -- Marco Antoniotti ======================================================== NYU Courant Bioinformatics Group tel. +1 - 212 - 998 3488 719 Broadway 12th Floor fax +1 - 212 - 995 4122 New York, NY 10003, USA http://bioinformatics.cat.nyu.edu "Hello New York! We'll do what we can!" Bill Murray in `Ghostbusters'. From m.laranjeira at datacraft.com.br Wed Jul 3 15:26:00 2002 From: m.laranjeira at datacraft.com.br (Marcus Vinicius Laranjeira) Date: Wed, 03 Jul 2002 16:26:00 -0300 Subject: Tuples --> How to use them ? Message-ID: <5.1.1.6.0.20020703162513.00a007c0@imap.datacraft.com.br> All, Supose I have an arbitrary tuple of values that came from a sql query. I need to run this algorithm: t1 <-- new tuple t1 <-- results from an arbitrary query l <-- new list for each value in the tuple do: a <-- new tuple add this value to the tuple a add the tuple a to a the list l i.e. I need to create a list of tuples and these tuples will have one, and only one, number that came from the original tuple. Does anyone know how do I do that !? thanks in advance, Marcus From andreyw at canoemail.com Tue Jul 16 04:21:41 2002 From: andreyw at canoemail.com (andreyw) Date: 16 Jul 2002 01:21:41 -0700 Subject: implementing large trees References: Message-ID: <65d4d518.0207160021.231f9783@posting.google.com> Try solution out off Python. There are free versions of MUMPS for example. MUMPS is a tree database. Andrey From kosh at aesaeion.com Sat Jul 13 16:55:16 2002 From: kosh at aesaeion.com (kosh at aesaeion.com) Date: Sat, 13 Jul 2002 14:55:16 -0600 (MDT) Subject: isA function? In-Reply-To: Message-ID: On Sat, 13 Jul 2002, Roy Smith wrote: > Is there a standard isA() function in Python? It should take two > arguments, an instance and a class, and return true if the object is a > member of the class or one of the class's ancestors. > > I know I can roll this myself with __class__.__bases__, but it seems > like a common enough thing that there would be a built-in way to do it. > I looked at the inspect module, and was surprised to not find it there. > > We're writing some unit tests, and one of the tests is "foo() returns > something which isA (bar)". Look at isinstance it does what you want and takes those arguments. isinstance(object, class) Returns true if object is and instance of class or if class is anywhre in object's inheritance structure. From emile at fenx.com Sun Jul 14 12:14:08 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 14 Jul 2002 16:14:08 GMT Subject: function parameter: question about scope References: Message-ID: Uwe Mayer > def getElements(self, types, memo={}): [snip] > The problem is, that 'memo' seems to live beyond method invocation - and > I don't know why: When you use: def getElements(self, types, memo={}): memo will only be created once when the module is initially imported. All subsequent access to getElements() that don't specifically override memo share the same originally created copy of memo. You probably want to do: def getElements(self, types, memo=None): if memo == None: memo = {} Then each invocation of getElements not passing in memo will get a newly created memo. HTH, -- Emile van Sebille emile at fenx.com --------- From mis6 at pitt.edu Wed Jul 24 08:14:15 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Jul 2002 05:14:15 -0700 Subject: re.finditer References: Message-ID: <2259b0e2.0207240414.6ce6e255@posting.google.com> I have submitted a bug report to sourceforge.net M. From boud at valdyas.org Tue Jul 9 05:56:09 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Tue, 9 Jul 2002 11:56:09 +0200 (CEST) Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <200207091153.15904.b.maryniuk@forbis.lt> Message-ID: On Tue, 9 Jul 2002, Bo M. Maryniuck wrote: > On Tuesday 09 July 2002 11:39, Boudewijn Rempt wrote: > > Er, yes. Somebody could: there's qtjava. > May I ask You for link? I'm just curious: Java + QT + crossplatforming. Hmm... > It's part of the kdebindings module: http://developer.kde.org/language-bindings/java/index.html > From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 14:18:51 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 13:18:51 -0500 Subject: Newbie: How to touch "global" variables In-Reply-To: <3D46CF98.5D66A7E5@lmco.com> (Jeff Layton's message of "Tue, 30 Jul 2002 13:40:40 -0400") References: <3D4568D5.3254F968@lmco.com> <3D46836B.2506F469@lmco.com> <3D46CF98.5D66A7E5@lmco.com> Message-ID: >>>>> "Jeff" == Jeff Layton writes: Jeff> modules. Unfortunately, I don't know the variable names Jeff> ahead of time, so I think having the ability to "add" them Jeff> to an instance is where I'm header Jeff> (e.g. MyShare.variable=value). Then I can "quizz" the Jeff> instance looking for specific variables (using dir() ). I Jeff> don't think at this point I need to change any of the values Jeff> in the instance, but I may want to do that at some point (at Jeff> least for the sake of learning out to do it). Thanks again Jeff> for your help and explanation. If you want to work with attributes where you don't know the names, you'll want to familiarize yourself with the built-in functions hasattr, setattr, and getattr class X: def __init__(self): self.a = 1 x = X() if hasattr(x, 'a'): a = getattr(x, 'a') #b = getattr(x, 'b') # raises AttributeError exception setattr(x, 'b', 12) # same as x.b = 12 b = getattr(x, 'b') # now ok b = x.b # also ok # Classes store all of their data attributes in a dictionary called # __dict__. So you can also manipulate attributes with all the # dictionary methods (has_key, get, setdefault, ...) # get returns the value of c or 123 if c is not a key c = x.__dict__.get('c', 123) #c is 123 x.c = 100 c = x.__dict__.get('c', 123) #c is 100 That's why the Borg pattern works, because at class initialization, the instance dictionary is set to be equal to self.__shared_state, which is a class attribute. All of attr methods call special class methods by the same name with the leading and trailing __. So you can control what happens with setattr for example, restricting it to a certain set of keys, or enfocing a certain naming convention on keys (like lower case only or whatever) Here is an example that raises an exception if the user tries to use a short key. No reason for it, just an example... class X: a = 1 def __setattr__(self, key, val): if len(key)<4: raise ValueError, 'No short keys!' self.__dict__[key] = val x = X() x.first = 'John' x.last = 'Hunter' x.age = 33 #raises an exception here You can do a lot with the special methods of python, and there are a lot of them See http://python.org/doc/current/ref/specialnames.html http://diveintopython.org/fileinfo_specialmethods.html http://diveintopython.org/fileinfo_morespecial.html John Hunter From pixie888 at hotmail.com Wed Jul 10 02:04:40 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Wed, 10 Jul 2002 06:04:40 GMT Subject: Python tutorial References: <3d2a9b39.94944531@news.skynet.be> <3JIW8.450828$352.70678@sccrnsc02> Message-ID: <3d2bce0d.173491234@news.skynet.be> On Tue, 09 Jul 2002 21:38:07 GMT, "Emile van Sebille" wrote: >Henk >> Is there any Python tutorial out there which happens to be written in >> Dutch? >> > >Good question! It's well known that all good pythoneers speak dutch, >but apparently not all write in it. > >I'm not sure how far this will get you, but I only found this one link: > >http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-vertaling.html > >Perhaps there's more? I found that link too, but it's not enough, thanks anyway. > >-- > >Emile van Sebille >emile at fenx.com > >--------- > From trentm at ActiveState.com Tue Jul 16 16:39:05 2002 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 16 Jul 2002 13:39:05 -0700 Subject: Getting SOAP working w/ Activestate Python? In-Reply-To: <3D346DB4.5070401@onsitetech.com>; from rs@onsitetech.com on Tue, Jul 16, 2002 at 07:03:48PM +0000 References: <3D346DB4.5070401@onsitetech.com> Message-ID: <20020716133905.B13273@ActiveState.com> [Robb Shecter wrote] > Hi, > > I've got Activestate Python installed (Python 2.2.1), and used the > Python Package Manager to install the two packages: > > ZSI 1.1 > PyXML 0.7 > > However, I haven't gotten any demos to work yet. What demos were you trying? > > These two packages are the two available from Activestate. Are they > compatible? ZSI should state whether is requires PyXML or not. (The base Python XML support vs. PyXML is a little bit of a mess.) I found this: "The ZSI module, which is part of the Python Web Services project at Sourceforge, requires Python 2.0 or later and PyXML 0.6 or later." here: http://www.xmlhack.com/read.php?item=1572 Check out this link for more info: http://pywebsvcs.sourceforge.net/ > Why should I have to install PyXML explicitly? Isn't XML > support built in to the latest version of Python? Python *does* ship with some XML support. You get "more" support via the PyXML package. I am no XML in Python expert but my understanding is that if you do any serious XML work in Python then you generally want the PyXML package installed. PyXML is distributed separately from Python probably a little bit for historical reasons (some XML stuff wasn't ready when Python X.X was ready to ship) and more so because development on Python's XML support was (and perhaps still is) moving faster than development of Python itself. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From whisper at oz.net Fri Jul 19 15:41:07 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 19 Jul 2002 12:41:07 -0700 Subject: Windows, Python and Strings In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Engel, Gregory > Sent: Friday, July 19, 2002 12:11 > To: Python List (E-mail) > Subject: Windows, Python and Strings > > > >>> win32service.ChangeServiceConfig(svc, svccfg[0], svccfg[1], > svccfg[2], svccfg[3], svccfg[4], svccfg[5], 'MSSQLServer', > 'LocalSystem', '', "Green Bar Queue Manager") > > This also executes without error. When I look at the Registry, > the value shows as "M S S Q L S e r v e r" rather than > "MSSQLServer" so the dependency fails. If I use the MS tool, sc.exe: > > sc config TestQueueMgrSvc depend= "MSSQLServer" > > the Registry value correctly shows as "MSSQLServer". I've tried > a number of approaches to resolving this with no luck. It > doesn't appear to be a encoding issue. It's almost certainly an encoding issue: "t e x t l i k e t h i s" is how Unicode displays in ascii. The "blanks" are the upper 8 bits of a (16 bit) unicode character seen as a separate (ascii?) character. > The method requires a string parameter. The Registry stores the > value as binary data. What am I missing? Is there something I > don't understand about how to use this method? AFAIK, the registry stores both string and typed binary data... > Many Thanks. > > C'ya, > > Gregory Engel > Senior Software Engineer > Professional Services > CSG Systems, Inc. > 9555 Maroon Circle > Englewood, CO 80112 > Voice: 303-200-3426 Dave LeBlanc Seattle, WA USA From google at thegoldensun.com Wed Jul 31 00:37:29 2002 From: google at thegoldensun.com (HW) Date: 30 Jul 2002 21:37:29 -0700 Subject: MySQLdb DictCursor scrambles field order Message-ID: <62e69c0c.0207302037.15c62bf7@posting.google.com> Hello, I am viewing some MySQL tables via Python CGI; I use the MySQLdb.DictCursor in order to return the field names as well as the data, so I can output a table with the field names as column headings. Unfortunately, the DictCursor seems to scramble the order of fields, eg: "SELECT field1, field2, field3 FROM table" which returns the fields in order when using a standard cursor, seems to rearrange the order (randomly?) with a DictCursor. I am using MySQLdb 0.9.1, Python 2.1, 3.23.51-nt under Win XP; I have had the same trouble in a similarly numbered Linux version. Thanks for any help! HW From marklists at mceahern.com Tue Jul 9 14:18:17 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 9 Jul 2002 13:18:17 -0500 Subject: Why self? In-Reply-To: <090720021359063518%pecora@anvil.nrl.navy.mil> Message-ID: > Tell you what. You're a smart guy (not sarcastic, I mean it). Why not > apply your considerable knowledge to finding a solution to the issue of > requiring "self." prefixes? It's apparent that lots of people would > like to lose that requirement. I'm sure you can demolish my > off-the-cuff suggestion at some point. I'm a bush-league amateur. But > when you do that you will turn around to see that the issue itself is > still there. What would you do? You say that lots of people would like to lose the requirement. My guess is that's not true. It may appear true, since this topic does come up every so often and the people who think it's a problem are often quite insistent about it. What you don't see, of course, is all the people who are silent because they're quite happy with self. prefixes and consider this a pointless discussion usually kept alive by people who refuse to learn the idioms of Python to their best advantage. Cheers, // mark - From jb at cascade-sys.com Fri Jul 12 01:43:58 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 11 Jul 2002 22:43:58 -0700 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: <3D2E6C9E.FDD37D8E@cascade-sys.com> Alex Martelli wrote: > No such official pronouncement for now on whether linebreak must always > come right after a colon (though I suspect I know where the BDFL's > sympathies lie on this, he hasn't gotten around to writing them down, > AFAIK, and surely not in PEP 8 so far -- good, gives us heretics-to-be > more time to prepare _our_ underground network...). Examples without the intervening line break appear in PEP 8. > Interestingly enough, I find I can live with everything that is > mandated in PEP 8 -- some recommendations are not my favorite ones, > but there's nothing really major in it that irks me. It's hard to complain about a style guide that acknowledges up front that "A Foolish Consistency is the Hobgoblin of Little Minds" and that furthermore common sense may at times dictate breaking the rules. --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From aleax at aleax.it Thu Jul 11 07:25:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 11:25:03 GMT Subject: sorting many arrays from one... References: Message-ID: Tim Peters wrote: ... >> (lists that are close to being ordered > > Unfortunately, it's only some lists that are close to being ordered, > although I believe it catches the most frequent real-life cases of that. Right. The only extra case I've often wished it handled (defining "often" as "more than once":-) is when the FIRST element is out of order and all the rest are OK. That happens in mergesorting huge streams, in the core merge loop: while streams: yield streams[0][0] try: streams[0][0] = streams[0][2]() except StopIteration: del streams[0] else: streams.sort() # this is the first-maybe-OOO sort The "streams" auxiliary list is originally built from the sequence X of already-sorted streams as: streams = [ [X[i].next(), i, X[i].next] for i in range(len(X)) ] Normally N==len(streams) isn't all that big, and I COULD make each leg of the "while streams:" loop O(N) anyway by using knowledge about _which_ special cases method sort is so good at -- changing the else clause into: else: streams.append(streams.pop(0)) streams.sort() # the maybe-OOO item is now *LAST*... but that's not all that pleasant -- I'd do it only in emergencies... Alex From peter at engcorp.com Thu Jul 11 08:24:28 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Jul 2002 08:24:28 -0400 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) References: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: <3D2D78FC.2C339012@engcorp.com> Miki Tebeka wrote: > > Hello All, > > Although it's in the Humor section I take the Python Zen > (http://www.python.org/doc/Humor.html#zen) quite seriously. > However I can understand what does “Sparse is better than > dense” means. It (means don't write): your-code=like+this; because(no,one) will,be,able=to-read(what,you,are,writing+without-effort) Instead, use lots of white space. Put empty lines between blocks of unrelated code within functions, put spaces around operators much of the time (except for the "=" in default/named arguments like the above). Put two lines between method or function definitions. Let the air into the code so it can breathe. Code that is too dense starves for air and withers and dies. At least, that's my interpretation. :) -Peter From tjd at sfu.ca Thu Jul 18 03:02:25 2002 From: tjd at sfu.ca (Toby Donaldson) Date: 18 Jul 2002 00:02:25 -0700 Subject: slicing and parallel assignment: inconsistent behaviour?? Message-ID: Hi, I was hoping someone might be able to help me with a problem I've run into with slices and parallel assignment. I want to swap to segments of a list. For instance: >>> B = range(10) >>> B[1:5], B[5:10] = B[5:10], B[1:5] >>> B [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] This works as I expect. But if I leave out the 10s in the slice indices, I get this: >>> A = range(10) >>> A[1:5], A[5:] = A[5:], A[1:5] >>> A [0, 5, 6, 7, 8, 1, 2, 3, 4] Where has the 9 gone? If I include the 10 on the left side of the assignment, it works as I expect: >>> C = range(10) >>> C[1:5], C[5:10] = C[5:], C[1:5] >>> C [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] Yet leaving adding the 10 on the right side of the assignment and leaving it out on the left has the same behaviour as the A example: >>> D = range(10) >>> D[1:5], D[5:] = D[5:10], D[1:5] >>> D [0, 5, 6, 7, 8, 1, 2, 3, 4] Any idea what's going on? Toby From marklists at mceahern.com Fri Jul 12 10:49:05 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 09:49:05 -0500 Subject: automating command line program In-Reply-To: <002401c229b1$e45aa090$e503010a@int.meetingmaker.com> Message-ID: I'm fairly new to python and I've been trying to automate the usage of a command line prompt program and I'm able to successfully run the application from command line but once the program has launched, I'm unable to enter anymore commands into the program. I've basically just tried using os.system, os.popen, and print statements. Is there other python commands that will allow me to do this? I've looked around the web and I've found a module, Expect, that may be able to help me but I'm unable to find a windows version of this module for python. Any help is appreciated, thank you. Victor Could you please be more specific? What is it you're trying to do? What specifically have you tried? What specifically isn't working? // m - From bokr at oz.net Wed Jul 17 05:04:55 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2002 09:04:55 GMT Subject: map del efficiency python2.2 and 2.1 References: <449Z8.89567$vm5.3207139@news2.tin.it> Message-ID: On Wed, 17 Jul 2002 07:32:16 GMT, Alex Martelli wrote: >Bengt Richter wrote: > >> On Tue, 16 Jul 2002 15:53:43 GMT, Alex Martelli wrote: >> >>>John Hunter wrote: >>> ... >>>> def pairs(l): >>>> return [(l[i], l[i+1]) for i in range(0, len(l), 2)] >> ^^^^^ > ... >>>def pairs(L): >>> for i in xrange(0, len(L), 2): >> ^^^^^^ >> ^ >>> yield L[i], L[i+1] >>> >>>but that's a minor issue, I guess. >>> >>>Another likely performance boost in 2.2 would be: >>> >>>m = dict(pairs(seq)) >>> >>>with pairs coded as here shown. >> >> In case John didn't notice, that little 'x' your finger likely >> typed automatically probably made some difference too ;-) > >Yep, but John had used xrange in other spots of his code, >so I didn't think I needed to explain better. Still, that >may have been an error on my part. So, the better explanation: >range and list comprehensions build lists and thus may have >to allocate lots of memory. xrange and generators don't build >any list but rather return one item at a time as needed. > >But the importance of using xrange vs range is minor -- yes >it does make SOME difference, but it's small. See: > >from __future__ import generators >import time, gc > >L = range(300 * 1000) > >def timit(f): > start = time.clock() > m = dict(f(L)) > stend = time.clock() > print f.__name__, stend-start > >def pairs_lc_ra(L): > return [ (L[i],L[i+1]) for i in range(0, len(L), 2) ] > >def pairs_lc_xr(L): > return [ (L[i],L[i+1]) for i in xrange(0, len(L), 2) ] > >def pairs_ge_ra(L): > for i in range(0, len(L), 2): > yield L[i], L[i+1] > >def pairs_ge_xr(L): > for i in range(0, len(L), 2): ^-- needs x, but doesn't make much difference > yield L[i], L[i+1] > >gc.disable() > >for i in range(3): > for f in pairs_lc_ra, pairs_lc_xr, pairs_ge_ra, pairs_ge_xr: > timit(f) > > >[alex at lancelot MyDocuments]$ python pa.py >pairs_lc_ra 0.53 >pairs_lc_xr 0.52 >pairs_ge_ra 0.29 >pairs_ge_xr 0.28 >pairs_lc_ra 0.52 >pairs_lc_xr 0.52 >pairs_ge_ra 0.28 >pairs_ge_xr 0.28 >pairs_lc_ra 0.52 >pairs_lc_xr 0.52 >pairs_ge_ra 0.28 >pairs_ge_xr 0.28 > >This is with 2.2.1. 2.3 built from CVS lowers generator's advantage: > >[alex at lancelot src]$ ./python pa.py >pairs_lc_ra 0.44 >pairs_lc_xr 0.4 >pairs_ge_ra 0.29 >pairs_ge_xr 0.28 >pairs_lc_ra 0.43 >pairs_lc_xr 0.4 >pairs_ge_ra 0.29 >pairs_ge_xr 0.29 >pairs_lc_ra 0.43 >pairs_lc_xr 0.39 >pairs_ge_ra 0.29 >pairs_ge_xr 0.29 > >but even here, using generators rather than list comprehensions >seems still much more important than using xrange rather than range. > Yes. Looks like about ~5% advantage for 'x' and ~100% for 'ge' on my old machine (P2-300mhz/320MB with Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32): pairs_lc_ra 2.12676607592 pairs_lc_xr 2.02671428164 pairs_ge_ra 1.00829043683 pairs_ge_xr 0.942929913458 pairs_lc_ra 2.11218992576 pairs_lc_xr 2.07914132127 pairs_ge_ra 1.00314620904 pairs_ge_xr 0.959043968146 pairs_lc_ra 2.0945639475 pairs_lc_xr 2.22773139387 pairs_ge_ra 1.03221134747 pairs_ge_xr 0.952561302467 Thanks for the demo. Regards, Bengt Richter From loewis at informatik.hu-berlin.de Tue Jul 30 04:55:41 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2002 10:55:41 +0200 Subject: global interpreter lock not working as it should References: <200207292348.TAA31011@test-area.com> Message-ID: Just writes: > I can see it on MacOSX, three different Linux boxes and a FreeBSD box. > Various Python versions. The output is always sequential. As Aahz explains, that can indeed happen (and, depending on the thread implementation of your operating system, might be even likely to happen). It is in no way "wrong". Please replace the for statement with a while 1: loop - even on systems where my script produces sequential output, I find that the operating system will eventually switch threads. Regards, Martin From jon_bills at hotmail.com Wed Jul 3 09:37:58 2002 From: jon_bills at hotmail.com (Jon Bills) Date: Wed, 3 Jul 2002 14:37:58 +0100 Subject: determining instance attributes References: Message-ID: "Ralf Juengling" wrote in message news:xduu1nhxdvz.fsf at kantine.informatik.uni-freiburg.de... > Hi, > > how can an instance easily find out all its non-method > instance attributes? This information is held in the __dict__ member of the instance. > Cheers, > Ralf Cheers, Jon. From iphi at imagis.ch Sat Jul 27 09:00:05 2002 From: iphi at imagis.ch (Iphigenie) Date: 27 Jul 2002 13:00:05 GMT Subject: calendar lameness! References: Message-ID: I started thinking something odd was going on in comp.lang.python when one foggy november evening "James J. Besemer" came into my office and told me: > > Tim Peters wrote: > >> [James J. Besemer] >> > ... >> > And don't get me started on when Easter is. >> >> That's easy! Sunday. > > Yeah, but which Sunday? > > Hint: the Catholic church went to great lengths attempting to > define Easter in such a manner that (among other things) it > could never occur on the same day as Passover. Isnt passover on a saturday night anyway? -- Iphigenie http://www.iphi.net From huaiyu at gauss.almadan.ibm.com Tue Jul 9 18:01:24 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 9 Jul 2002 22:01:24 +0000 (UTC) Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: Simon Foster wrote: >On Tue, 9 Jul 2002 15:23:49 +0200, "Bo M. Maryniuck" > wrote: > >>On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote: >>> eval! >> >>Overkill. Unsafe. Ugly. Lame. >> > >What do you mean by unsafe? Something like the following could happen (don't try it!) # eval('system("rm -rf /")') Huaiyu From mertz at gnosis.cx Mon Jul 15 10:49:40 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Mon, 15 Jul 2002 10:49:40 -0400 Subject: Python to XML to Python conversion In-Reply-To: References: Message-ID: |of Python dictionary and be able to convert it to XML and back. My xml_pickle library is clearly the most direct answer to this question. Mind you, I agree with some of the caveats in the thread you generated about "buzzword compliance" and overuse of XML, etc. But assuming you do have good reasons to do what you describe, get: http://gnosis.cx/download/Gnosis_Utils-current.tar.gz It will do what you want, very simply (and will do lots more if you want to be non-simple). There's lots of documentation in there also. Yours, David... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From peter at engcorp.com Thu Jul 4 08:13:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Jul 2002 08:13:50 -0400 Subject: Efficient python programming... References: <3d238f6b.579164824@news.dsl.pipex.com> <3D23D092.4E3AD523@engcorp.com> Message-ID: <3D243BFE.C5105B22@engcorp.com> "Bo M. Maryniuck" wrote: > > On Thursday 04 July 2002 06:35, Peter Hansen wrote: > > > I prefer this one: > > > > > > "You can have it right" > > > "You can have it cheap" > > > "You can have it now" > > > > > > Pick any two. > > > > Interestingly, XP provides a way to have all three... > > If You mean XP-programming, than I'm not agree: You can't have it NOW. You're right, of course, but then James Kew's list above was not quite correct. It's normally "good, cheap, or fast" and although a substitution of "right" for "good" is okay I don't think "now" is the same as "fast". From emile at fenx.com Tue Jul 9 17:20:35 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Jul 2002 21:20:35 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: Simon Foster > >> eval! > What do you mean by unsafe? eval is generally to be avoided when other methods suffice: >>> int(string, 16) 305419896 -- Emile van Sebille emile at fenx.com --------- From oren-py-l at hishome.net Wed Jul 3 11:26:34 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 3 Jul 2002 18:26:34 +0300 Subject: Thread safetyness in Python In-Reply-To: <20020703143408.GA32161@unpythonic.net>; from jepler@unpythonic.net on Wed, Jul 03, 2002 at 09:34:14AM -0500 References: <20020703135851.GA73351@hishome.net> <20020703143408.GA32161@unpythonic.net> Message-ID: <20020703182634.A15524@hishome.net> On Wed, Jul 03, 2002 at 09:34:14AM -0500, Jeff Epler wrote: > On Wed, Jul 03, 2002 at 09:58:51AM -0400, Oren Tirosh wrote: > > The resolution is one bytecode operation so a+=1 is atomic but not a=a+1. > > The list operations above are atomic. > > a+=1 is multiple bytecodes. 6 LOAD_FAST 0 (a) 9 LOAD_CONST 1 (1) 12 INPLACE_ADD 13 STORE_FAST 0 (a) You're right. I forgot that the inplace operations also need to store the new object afterwards since immutable objects such as ints cannot really be modified "in place". So a+=1 isn't atomic, but l+=[1] is. Interesting. Oren From rpm at wag.caltech.edu Tue Jul 2 15:18:03 2002 From: rpm at wag.caltech.edu (Richard P. Muller) Date: Tue, 02 Jul 2002 12:18:03 -0700 Subject: Add parent directory to path? References: <3D21F62D.9050801@wag.caltech.edu> Message-ID: <3D21FC6B.2040706@wag.caltech.edu> Chris Liechti wrote: > Rick Muller wrote in > news:3D21F62D.9050801 at wag.caltech.edu: > > >>I often use the little hack >> >>import sys >>sys.path.append('..') > > > i would use sys.path.append(os.path.abspath('..')) > as you might change the current dir of the app later. > > >>to add the parent directory to the python path. It's nice, e.g., if I >>want to keep a directory below the program directory that contains test >>scripts, but still let them easily import the parent directory's modules. >> >>This hack worked on Unix and Windows/Cygwin, which up until recently >>were my only build targets. Now I just got a Apple OS X box, and I find >>that, despite the BSD heritage, this little hack no longer works. Is >>there a good platform-independent way of doing this? I figure that >>something like this should live in os.path, but I didn't find anything >>appropriate. > > > doo you have printed os.curdir() and os.path.abspath(os.curdir) > do thay return somthing useful? don't have OSX, but i would expect it to > act like a unix too.... > > Chris, os.path.abspath(os.curdir) works. Thanks. Rick -- Richard P. Muller, Ph.D. rpm at wag.caltech.edu http://www.wag.caltech.edu/home/rpm From merman at snafu.de Sat Jul 6 14:05:18 2002 From: merman at snafu.de (merman) Date: Sat, 6 Jul 2002 20:05:18 +0200 Subject: Understanding properties References: Message-ID: > >> class MyObject(object): > > > > Why it needs the inheritance from object - I don't understand. > > Backwards compatibility. To be precise, a class using properties > needs to be new-style -- subclassing object is the simplest way > to achieve this (there are quite a few others) -- because by > default a class is a "classic" one, implementing exactly the > same semantics as in Python 2.1 and older, ensuring no major code > breakage in porting from 2.1 to 2.2 but constraining the applicability > of the new features to classic classes. Thanks Alex. The last part of your description is a little bit unclear for me - I'm a newbie. Perhaps I will understand it in one year ;-). Regards Thomas From phoebe_1 at att.net Wed Jul 31 14:37:53 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 31 Jul 2002 11:37:53 -0700 Subject: __slots__ variables and initialization Message-ID: Greetings, I don't recall exactly where I read it, but I had read that ALL the variables in __slots__ were initialized to None and are automatically part of the instance attributes whether they are explicitly created in the __init__ method or not. In 2.2.1 this is not what is happening. e.g: class X(object): __slots__ = ['_x'] def get_x(self): return self._x >>> x = X() >>> x.get_x() I get an attribute error. Obviously, defining and '__init__' method and explicitly creating it works. Is this the way it is supposed to be? Also, when is the '__' bug in the '__slots__' variable list going to be fixed? I am currently embarking on a large project and would like to nail down the convention of '__' for private variables in a class, quickly. If the bug fix is going to be further down (2.2.2?) then I would like to change our convention to something else. Thanks From shagshag13 at yahoo.fr Wed Jul 17 12:32:25 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 17 Jul 2002 18:32:25 +0200 Subject: how to ask google, altavista or another search engine... References: Message-ID: well, not that time... need python scripts... but thanks for the advice. s13. "John Hunter" a ?crit dans le message de news: m2y9cagwdj.fsf at mother.paradise.lost... > >>>>> "Shagshag13" == Shagshag13 writes: > > Shagshag13> but i'm also looking for others search engines > Shagshag13> wrappers like altavista or metacrawler, etc. > > If you are willing to go to the dark side, you may find the WWW:Search > perl mods useful. > > John Hunter > From pyth at devel.trillke.net Sun Jul 21 04:56:14 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 21 Jul 2002 10:56:14 +0200 Subject: can i make a p2p application in python? In-Reply-To: ; from eugene1977@hotmail.com on Sat, Jul 20, 2002 at 05:31:40PM -0500 References: Message-ID: <20020721105614.C10625@prim.han.de> eugene kim wrote: > like kazaa or napster.. > > is it possible? yes. For a start, there are a lot of modules for networking like ftplib, httplib etc. Next, implementing the logic for bootstrapping and dynamically managing a P2P-network is certainly possible with python. But concept/algorithm-wise it's not exactly trivial. HTH, holger From aleax at aleax.it Wed Jul 10 03:42:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 07:42:51 GMT Subject: Why self? References: <3D2B540B.4030205@onsitetech.com> <3D2B5C2E.6050001@onsitetech.com> Message-ID: <%zRW8.62682$vm5.2294043@news2.tin.it> Robb Shecter wrote: > Alex Martelli wrote: > >>>Well, I'd say that an object understanding the message I send to it, or >>>being the type of object I think it is - success or failure - surely is >>>a big difference! Sort of the name of the whole game... >> >> An object can "understand" (well...) the message (out of metaphor: be >> able to supply the attribute or method you're asking of it) WITHOUT >> "being the type you think it is". This is called POLYMORPHISM, and >> IS the whole game. > > Damn! The all-caps are out. And to beat that, I've been blindsided by > a red herring! > > 1. So you're uhh... agreeing but not? I'm not agreeing that "being the type you think it is" matters. > 2. I'm down w/ polymorphism, man! I'm all over over it. There's a big > difference between type and class, for starters, and 'type' as in Not in Python 2.2: >>> class X(object): pass ... >>> x = X() >>> type(x) >>> See? The type of x IS class X -- in Python 2.2. > 'implements an interface' is what I'm talking about. Pleased to meet you, Mr Humpty-Dumpty -- take care about sitting on walls, pray. You can certainly find areas of human endeavour where 'type' and 'class' have been defined in the ways you prefer. But, we're talking about Python -- if you're using terms in wildly different ways from the way Python uses it, you have to define the fact, of course. They don't mean "just what you want them to mean, no more, no less". It's not particularly sensible in Python to think of a concept of "interface" as "type". Whenever you bind on x a new attribute you're then changing its type...? That doesn't make much sense -- it's not a fruitful concept, either practically or conceptually. It may be useful for other, more rigid languages, but not here. Basically when you try to call x.foo() the distinctions that matter are: 1. any object either has an attribute foo, or not. If x is in the set of objects not having attribute foo, this raises AttributeError 2. objects that have an attribute foo can have it callable, or not. If x is in the set of objects whose attribute foo is not callable, this raises TypeError with suitable contents. 3. objects with a callable foo attribute may let you call it without arguments, or not. If not, TypeError again, with different contents (about what numbers of argument you should supply). Any of these points can be changed by any operation on x. If x's type (class) supplies a foo, x can "un-supply" it only via __getattribute__ (which must be class-supplied and flexible enough to support that...), so (1) is sometimes hard to get away from -- but 2 / 3 are trivial (the type/class would not only have to supply foo but do it via a property that stops rebinding -- a tall order, not impossible but practically never encountered). It's therefore quite irrelevant for you to state x's type or class. What you DO want to assert is: x has an attribute named foo, callable without arguments. How you assert this is with statement x.foo() There are no other general ways to assert this, although you may break some part of this down carefully: hasattr(x, 'foo') and callable(getattr(x,'foo')) (the 'callable without arguments' part is harder...). Surprise! That's EXACTLY the statement you need to use here. Can't get any more explicit than this...:-). > No, you don't know me, but I know OO. :-) If you really do know OO in the context of a reasonably dynamic language (Python's quite dynamic, but some other OO languages such as Ruby are even more so), then your statement about Python's "implicitness" here is inexcusable. I'd rather explain it as an understandable confusion due do unfamiliarity with the context, but, if you insist... Alex From edream at tds.net Wed Jul 10 11:27:09 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 10 Jul 2002 15:27:09 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> <3D2C4CE1.C4E85A07@tds.net> Message-ID: <3D2C524B.72A8E407@tds.net> Alex Martelli wrote: > Sure. You need to "snapshot" the value of val at the moment you're > interested in it -- passing it as an argument is one way to do that. > > In the for loop that you show, the use of val in: > callback=lambda: self.myCallback(val) > indicates the variable thus named in outer scope (or global scope), > and the relevant value is the one that said variable has _when > the lambda is later called_ -- by what time the loop has proceeded > to the end and val has stayed bound to the last value. Thanks very much for this clarification. > BTW, the for loop using: > > callback = lambda val=val: self.myCallback(val) > > should work just fine -- now you're "snapshotting" again (passing > val as an argument, so the value that matters is here the one at > *function-definition* time, as in the "extra level of indirection" > case that I suggest, NOT the value at *function-call* time in the > outer or global scope). Yes. This does work. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From tim.one at comcast.net Sat Jul 27 01:27:46 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 27 Jul 2002 01:27:46 -0400 Subject: calendar lameness! In-Reply-To: <3D4200EA.32C7497C@cascade-sys.com> Message-ID: [James J. Besemer] >>> And don't get me started on when Easter is. [Tim] >> That's easy! Sunday. [James] > Yeah, but which Sunday? The seventh Sunday after Shrove Sunday, of course. > Hint: the Catholic church went to great lengths attempting to > define Easter in such a manner that (among other things) it could > never occur on the same day as Passover. Don't try to oversimplify it . From jepler at unpythonic.net Tue Jul 23 22:56:19 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 23 Jul 2002 21:56:19 -0500 Subject: Tkinter Grid manager question In-Reply-To: <0C7CA8D8DF75494EB09AB6016990107FF0F894@NOXMAIL.noetixad.com> References: <0C7CA8D8DF75494EB09AB6016990107FF0F894@NOXMAIL.noetixad.com> Message-ID: <20020723215612.A1467@unpythonic.net> By default, a frame ignores the width= and height= it is given, and instead calculates the amount of space needed by the widgets it manages via grid or pack. You can tell the grid manager that it should not behave in this way, and should instead take the width= and height= you select for the frame and parcel that space out to the managed widgets: f1.grid_propagate(0) now, f1 will be 900x100 Similarly, if you "grid" things into f1_1 you need to run f1_1.grid_propagate(0) if you "pack" things into f1_1, you need to run f1_1.pack_propagate(0) If you want to make sure the rows are the same width, you need to set the weight (again on the master): for row in range(4): f1.grid_rowconfigure(row, weight=1) now, f1_1, f1_2, f1_3, and f1_4 will be configured to get equal shares of the height of f1. If you still don't get a layout exactly 225 pixels wide, this is probably because of the borderwidth. For instance, if you configure a frame width a thick border and then make another frame inside, the inner frame is smaller (shifting to tcl since that's easier to do): %frame .f -bd 25 -relief raised -width 100 -height 100 frame .f.f pack prop .f 0 pack .f pack .f.f -expand 1 -fill both wm geo . winfo geo .f winfo geo .f.f . and .f have geometries of 100x100, while .f.f is only 50x50, due to the border of .f. Geometry management in Tk is a somewhat complex issue, and you have to expect to play with the options before you get what you want. Usually you will want to have as few intervening levels of frames as possible. Jeff From aleax at aleax.it Sat Jul 13 09:54:29 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 13:54:29 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: Emile van Sebille wrote: ... >>>> l1 = [1,4,7,10,32,45] >>>> l2 = [4,32] >>>> >>>> def f(lst): return 1 > ... >>>> [ l1.append(x) for x in l2 if f(x) ] > [None, None] >>>> l1.sort() >>>> l1 > [1, 4, 4, 7, 10, 32, 32, 45] >>>> > > There, only took a minute. Is that fast enough? ;-) We can do a bit better by not abusing list comprehensions: l1.extend([ x for x in l2 if f(x) ]) l1.sort() and to make this a move, as requested, rather than a copy, a third statement: l2[:] = [ x for x in l2 if not f(x) ] Using list comprehensions for loops not meant to build lists is not quite kosher. It may work, but it IS allocating a list of results without real purpose. You may be able to use a list comprehension with extend, like here; or, code a bona fide loop -- that's still a possibility, remember:-). List's sort method is *incredibly* fast if the list is already sorted except for a few items out of place at the end. This approach may be able to exploit this superb speed if only a few items are being appended to l1. If many items are being appended, then O(N log N) is the best we can do anyway. Thus, this approach is near-optimal. Alex From raims at dot.com Fri Jul 12 11:30:25 2002 From: raims at dot.com (Rhymes) Date: Fri, 12 Jul 2002 17:30:25 +0200 Subject: What went wrong in Python1.6 ? References: Message-ID: <6fttiuc7ligvbobpgcs41k7ek25vju8n59@4ax.com> On 12 Jul 2002 14:03:25 +0200, Piet van Oostrum wrote: >The license was wrong. There were problems with GPL compatibility? -- Rhymes rhymes at myself.com " ride or die " From fakeaddress at nowhere.org Fri Jul 5 02:19:58 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 05 Jul 2002 06:19:58 GMT Subject: sending a file through sockets References: Message-ID: <3D253AA6.1090806@nowhere.org> Sorry if this gets double-posted... brueckd at tbye.com wrote: > Guyon Mor?e wrote: >>so the trick is to convert a file to a string representation right? > Um... you *could* do that, but it wouldn't actually help at all. The > contents of the file already are in a string representation because Python > strings can contain anything, including binary characters. The easiest way > to send a file is to simply read the data from the file and send it out > the socket, Right. > but to send the length of the file first so the receiving end > knows if and when it got the whole thing. That's not really needed. Just call shutdown(1) when finished writing. The receiver can detect the end when recv() returns zero bytes without error, which only happens on clean shutdown. The socket will also select() as readable just before the zero-byte recv(). The only snag is if a local error causes the sender to close the socket before sending all the data. Note that in the code, you don't actually check that you've received as much data as expected. The code uses the size to know when to stop reading, and the "if not data: break" will do that anyway. > If you need too much more > functionality than this it might be easier to just use one of the standard > file transfer protocols, e.g. FTP. Good advice. For most applications, I'd recommend the HTTP family. > Anyway, here's some sample code, but if > you're not already familiar with sockets then you should spend a little > time experimenting with them. Did you test this? The Python library uses the empty string for INADDR_ANY, which is fine for bind(), but I don't think it's legal for connect(). I understand it's a basic demo, but I'll note that any real application requires some time-out discipline to avoid very long hangs. Also on most Unix systems we'd need to watch out for signals that force system calls to return. --Bryan > The sending side listens for incoming connections and sends out the file. > The receiving side connects to the "server" and writes the file to disk. > > Common code: > import struct > PORT = 5555 > FILENAME = 'foo.bin' > HDR = '!I' > HDR_SZ = struct.calcsize(HDR) > > Sending side: > import os > from socket import * > s = socket(AF_INET,SOCK_STREAM) > s.bind(('',PORT)) > s.listen(1) > while 1: > q,v = s.accept() > q.sendall(struct.pack(HDR, os.path.getsize(FILENAME))) > f = open(FILENAME,'rb') > while 1: > data = f.read(4096) > if not data: break > q.sendall(data) > q.close() > > Receiving side: > from socket import * > f = open(FILENAME, 'wb') > s = socket(AF_INET, SOCK_STREAM) > s.connect(('', PORT)) > size = s.recv(HDR_SZ) > size = struct.unpack(HDR, size) > while size > 0: > data = s.recv(4096) > if not data: break > size -= len(data) > f.write(data) > s.close() From peter at engcorp.com Thu Jul 4 08:21:20 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Jul 2002 08:21:20 -0400 Subject: XP: on or off-topic? (was Re: Efficient python programming...) References: <3D00A456.4315EDA3@engcorp.com> <3d238f6b.579164824@news.dsl.pipex.com> <3D23D092.4E3AD523@engcorp.com> Message-ID: <3D243DC0.C82E6B45@engcorp.com> James Ashley wrote: > > In article <3D23D092.4E3AD523 at engcorp.com>, Peter Hansen wrote: > > Simon Foster wrote: > >> > >> On Fri, 7 Jun 2002 21:03:08 +0100, "James Kew" > >> wrote: > >> "You can have it right" > >> "You can have it cheap" > >> "You can have it now" > >> > >> Pick any two. > > > > Interestingly, XP provides a way to have all three... [...] > But does that discussion belong here? Seems to me that there are plenty > of python-specific theads going on. There seem to be many other places > to examine this forum. If you have been reading all those threads, you'll have noticed a number of questions that come up from time to time about developing large applications with Python, using software patterns with Python, unit testing with Python, optimizing Python, and so on. Just because such a thread wanders a little away from Python itself for a while doesn't make it unsuitable for this newsgroup/mailing list. Python programmers are by definition not the kind to follow the rest of the crowd, and they also tend to be interested in practical advice about how to improve their results and the way they get them. And you can always stop reading the thread, too. Vote with your feet. But if you aren't so quick to dismiss it, you may find the thread comes back to Python in interesting ways, and you might even learn something. -Peter From tbryan at python.net Thu Jul 25 22:44:35 2002 From: tbryan at python.net (Tom Bryan) Date: Fri, 26 Jul 2002 02:44:35 GMT Subject: New Zope/Python User Group in NC, USA (Research Triangle area) Message-ID: Geoff Davis and I are looking into the possibility of setting up a Zope/Python User Group in the Research Triangle area of North Carolina. At the moment, we'd like to keep things very informal. Just a bunch of Pythonistas meeting once a month to share knowledge and listen to someone give a presentation on some aspect of using/hacking/learning Python, Jython, or Zope. If you're interested in getting attending, go to http://dev.zope.org/Members/tbryan/TriZPUG/FrontPage In a couple of weeks, we'll be contacting everyone who adds his or her name to the list to organize a first meeting, which will probably include a presentation from Geoff on using CMF with Zope. Thanks, ---Tom From fperez528 at yahoo.com Thu Jul 18 23:03:14 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 18 Jul 2002 21:03:14 -0600 Subject: Nested scopes question Message-ID: In the following code: def foo(): def bar(): print 'x from foo',x x+=1 x=0 for i in range(5): bar() foo() the call to foo() raises a NameError b/c x is incremented, and python (2.2) then assumes it is a local variable. Is there a way to make python honor the nesting of the scopes (global doesn't work). The only solution I found was the rather unsightly one of putting my value for x inside a list: def foo(): def bar(): print 'x from foo',x[0] x[0]+=1 x=[0] # put value in a list so nested scopes work like I want for i in range(5): bar() foo() Is there a better option? Thanks, f. From cy at no-spam-artic.net Fri Jul 5 02:41:48 2002 From: cy at no-spam-artic.net (Charel Yueng) Date: Thu, 04 Jul 2002 23:41:48 -0700 Subject: IMAP Email Question Message-ID: I am trying to use the imaplib module to read messages in a remote mailbox and enter the data retrieved from the BODY[TEXT] into a mysql database for later processing. I have formatted the email to be: fname=charles fname=yueng address=someaddress when I get the mail thru Imap it comes in with: ('OK', [('2 (BODY[TEXT] {378}', 'fname=charles\r\nfname=yueng\r\naddress=someaddress\r\n\r\n\r\n), ')', '2 (FLAGS (\\Seen))']) I cannot process any string data because it's a tuple. I can't seem to be able to parse any data. What should be my approach to this problem? what I need to extract is separated by the '=' sign ie. charles,yueng,someaddress I then copy the message to another mailbox end then expunge it from the INBOX (that all works great) Any help would be appreciated Charles From heikowu at ceosg.de Tue Jul 30 12:40:43 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 30 Jul 2002 18:40:43 +0200 Subject: Nested stream line iteration In-Reply-To: References: Message-ID: <1028047243.2942.5743.camel@d168.stw.stud.uni-saarland.de> Hi Lars! On Tue, 2002-07-30 at 14:11, Lars Lundgren wrote: > #!/usr/bin/env python > > import sys, os, time, fileinput, string > > def build( module, tag ): > os.system( "cvs co " + tag + " " + module) > > filename = module + "/cvsDependencies" > > for line in fileinput.input(filename): > [m,t] = string.split( line ) > build( m,t ) > > os.chdir(module) > os.system( 'make -DVERSION="' + tag + '"') > > build( "my_module", "-r v1_0" ) Why not write the following? import os def build(module,tag): os.system("cvs co %s %s" % (tag,module)) cvs_dep = open("%s/cvsDependencies" % (module,),"r") for line in cvs_dep.xreadlines(): (m,t) = line.split("") build(m,t) os.chdir(module) os.system("make -DVERSION=\"%s\"" % (tag,)) build("my_module","-r v1.0") That should do what you want, I guess... Yours, Heiko W. From fakeaddress at nowhere.org Tue Jul 2 19:54:00 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Jul 2002 23:54:00 GMT Subject: A problem with urllib References: <3D1FD7A1.F265FC8E@engcorp.com> <3D2163E3.3050605@nowhere.org> Message-ID: <3D223D2A.4070607@nowhere.org> Aki Niimura wrote: > I run your demo script > in my environment, however, I got "HTTP/1.1 401 Authorization > Required" in both cases. Well, that's yet more puzzling. > Bryan, if you have tested your script with Linksys DSL > router, could you provide me the type of router (mine is BEFSR41) and > the firmware version (mine is 1.42.7)? The model, as shown on the front of the unit is BEFSR41. The firmware version, as reported on the "Status" page is "1.37, Jan 03 2001". So I have the same model with earlier firmware. > I tried the script both from Solaris and from Windows, but I got the > same result. > > Any further suggestions are also appreciated. You might re-check that "http://:admin at 192.168.1.1/" still works from a browser. Possibly the password got changed. Then, I'd suggest you examine (or post here) the output that my sample code returned. Possibly they moved away from "basic" authentication in the later firmware. --Bryan From daniel.dittmar at sap.com Tue Jul 23 11:48:40 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 23 Jul 2002 17:48:40 +0200 Subject: Make me beautiful (code needs help) References: Message-ID: Daniel Dittmar wrote: > Mark wrote: >> for i in range(len(data["A"])): >> try: >> data["new"].append(data["A"][i] - data["A"][i-1]) >> except OutOfBounds: >> data["new"].append("?") >> > > from __future__ import generators > > def difference (collection): > iterator = iter (collection) > yield None > last = iterator.next () > for current in iterator: > yield current - last > last = current > And a version which handles undefined entries, so you can now find the differences of the differences: def difference (collection): last = None for current in collection: try: yield current - last except TypeError: yield None last = current a = [1,2,4,10,50] >>>print list (difference (a)) [None, 1, 2, 6, 40] >>>print list (difference (difference (a))) [None, None, 1, 4, 34] Daniel From richie at entrian.com Tue Jul 9 06:32:20 2002 From: richie at entrian.com (Richie Hindle) Date: Tue, 09 Jul 2002 11:32:20 +0100 Subject: Flush References: Message-ID: > Anyone know if python has a flush() function like PHP, > to buffer dump in CGI ? As others have said, sys.stdout.flush() will do this. An alternative is to change the #! line of your CGI script to run "python -u". This has two effects: o it makes both output channels unbuffered, which means you don't need to remember to flush them o it puts the output channels into binary mode, which means that your script is portable between platforms with different line ending sequences (Windows, Unix, Mac) if you explicitly end your HTTP headers with '\r\n'. -- Richie Hindle richie at entrian.com From spam at melkor.dnp.fmph.uniba.sk Mon Jul 8 06:35:26 2002 From: spam at melkor.dnp.fmph.uniba.sk (Radovan Garabik) Date: Mon, 8 Jul 2002 12:35:26 +0200 Subject: procmail replacement in Python References: <3u8pea.617.ln@127.0.0.1> Message-ID: Sheila King wrote: : The tarball URL for the pycmail packages is not working for me. there were just some power outages, it should work now : Did anyone grab a copy that they can share? I would like to look : at this package. We are often get potential clients at asking about : our web hosting services, who would like to use procmail. However, : procmail doesn't run well on our system due to the Qmail mail permissions : and such. It would be interesting to see if this python procmail : replacement might do the job? it depends pycmail just expects the incoming mail at stdin, and copies it to various destinations, so under standard scheme it is invoked with UID of the user expecting mail, and if it has proper rights to write it into destination mailboxes, all should work. (what kind of problems are you having with procmail?) -- ----------------------------------------------------------- | Radovan Garabik http://melkor.dnp.fmph.uniba.sk/~garabik | | __..--^^^--..__ garabik @ fmph . uniba . sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From chris.gonnerman at newcenturycomputers.net Fri Jul 19 08:57:32 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 19 Jul 2002 07:57:32 -0500 Subject: file ops on the fly ? References: <21TZ8.101254$vm5.3505549@news2.tin.it> Message-ID: <006d01c22f23$dd28e1c0$0101010a@local> ----- Original Message ----- From: "Shagshag13" Newsgroups: comp.lang.python > > thanks, i'm going to look at fileinput... > > ans yes i'm working on big file (>1go). From a sequential reading (line by line) i need to do line insertion and/or line deletion in > my file. And i don't wish to create a new (wasting place) file. It can't be done. Line deletion can be done using a dual-file-pointer algorithm, but if you can't load the dataset into RAM you can't do insertions without copying to another file. Ur. Maybe it can. If you buffer a few lines ahead, rewriting them as you go... I'm not even going to try to write the code for that. It's giving me a headache. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From aleax at aleax.it Sat Jul 13 10:17:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 14:17:19 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: JB wrote: ... > remains sorted, that is, the entries from > should be inserted to the right positions in . When > is defined by > n := max(len(list1),len(list2)), > then should work in O(n) time. > > Any hints of how to do this (as fast as possible)? Hmmm, I hadn't seen the O(N) constraint. The approach previously posted by Emile and commented on by me does not guarantee meeting that constraint: it CAN happen to become O(N log N) when most of list2 ends up appended to list1. For an O(N) guarantee, I think you must use a merge-like linear scan on the lists -- also requiring O(N) temporary auxiliary storage, of course. Here's a fancifully-expressed solution...: au = [None] * 2 it = iter(list1) au[0] = [ it.next(), 0, it, [] ] it = iter(list2) au[1] = [ it.next(), 1, it, [] ] while True: m = min(au) i = m[1] if i and f(m[0]): i = 0 au[i][3].append(m[0]) try: m[0] = m[2].next() except StopIteration: break # now, either list is exhausted # if any tail is left in the first list, copy it au[0][3].extend(au[0][2]) # if any tail is left in the second list, distribute it for x in au[1][2]: au[not f(x)][3].append(x) # finally, copy the results back list1[:] = au[0][3] list2[:] = au[1][3] OK, OK, NOT the most lucid code I ever posted, I agree. But I get it by reasoning back from the GENERAL case of mergesort (for any number of streams) and specializing for 2 streams AND adding the subtle asymmetry beteween the first list (whose items must all go to the first auxiliary list) and the second one (whose item must go to the first auxiliary list iff they satisfy predicate f, otherwise to the second auxiliary list). I bet you can do better by exploiting the specifics of this case!-) Still -- this IS O(N) in time and space! Alex From lellinghaus at yahoo.com Tue Jul 16 02:06:15 2002 From: lellinghaus at yahoo.com (Lance Ellinghaus) Date: Mon, 15 Jul 2002 23:06:15 -0700 (PDT) Subject: NetBackup Managemen Protocol Support Message-ID: <20020716060615.86128.qmail@web20901.mail.yahoo.com> Has anyone created a library to connect to the different subsystems (Media and Device Manager, Storage Unit Manager, etc..) under Veritas NetBackup? I know I can parse the raw files if I am on the local machine, but I would like to be able to connect to the server from a remote machine, similar to how I can use jnbSA from a remote machine. Thank you, Lance Ellinghaus ===== -- Lance Ellinghaus __________________________________________________ Do You Yahoo!? Yahoo! Autos - Get free new car price quotes http://autos.yahoo.com From uwe.schmitt at procoders.net Sat Jul 27 10:41:59 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 27 Jul 2002 14:41:59 GMT Subject: xrange questioin Message-ID: Hi, as xrange() comsumes less memory than range() I ask why I should use range() at all.... is there any benifit from using range() ??? Greetings, Uwe, -- Dr. rer. nat. Uwe Schmitt python, php, c++, codes, tips, tutorials at uwe.schmitt at procoders.net http://www.procoders.net From fakeaddress at nowhere.org Tue Jul 9 16:09:31 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 09 Jul 2002 20:09:31 GMT Subject: sending a file through sockets References: <3D277DDC.1040705@nowhere.org> <1026007094.566332@yasure> <3D280B4B.8020008@nowhere.org> <3D29FBA5.7080707@nowhere.org> Message-ID: <3D2B4301.40609@nowhere.org> Donn Cave wrote: > Quoth Bryan Olson: > | Donn Cave wrote: > ... > |> Part of my job is to decide > |> how robust an application needs to be, and while it may be good to > |> err on the side of safety, that doesn't excuse me from making the call. > | > | For an internet application, it turns out to be more than most people > | think. It's a rough network out there. > > I'm going to try one last time to clarify my point here: it _depends_ > _on_ _the_ _application_. Are you willing to consider other points? It also depends upon _the_ _environment_. Very frequently, programs that worked fine within an enterprise fail on the internet. If I were giving hints on writing "my first Internet application", one would be *not* to do it at the sockets level. > Some applications need to be as bomb-proof > as possible, but many others don't. That isn't because they're not > "professional", or not "real", it's because the risk is a tolerable > trade-off for the complexity of a bomb-proof solution. Many times we've seen news-worthy failures of internet applications. Report often include the fact that flaw was already well-known. People wonder how the creators could be so irresponsible as to deploy programs with known, fixable, defects. > | I welcome you to send a byte count. I didn't even say it was bad > | advice; just that it's not really needed, and since the protocol > | didn't check it, we might as well take it out. To me, this one looked > | like a job for HTTP/0.9. > > If you ever get your hands an actual application that sends a byte > count but doesn't look at it on the other end - leave it alone. Well of course I've gotten my hands on such things. Most web browsers don't use the "content-length" in a text/html response over HTTP/1.0. That's recommended practice by RFC 1945, because a number of buggy servers computed the length before adding server-side includes. --Bryan From b_mcerlean at yahoo.com Tue Jul 9 15:59:48 2002 From: b_mcerlean at yahoo.com (Brian McErlean) Date: 9 Jul 2002 12:59:48 -0700 Subject: Splitting a string every 'n' References: Message-ID: Simon.Foster at smiths-aerospace.com wrote in message news:... > What is the idiomatic way to split a string into a list > containing 'n' character substrings? I normally do > something like: > > while strng: > substring = strng[:n] > strng = strng[n:] > > > But the performance of this is hopeless for very long strings! > Presumable because there's too much list reallocation? Can't Python > just optimise this by shuffling the start of the list forward? > > Any better ideas, short of manually indexing through? Is there > something like: > > for substring in strng.nsplit(): > I have a handy class I use for things like this: class Group: def __init__(self, l, size): self.size=size self.l = l def __getitem__(self, group): idx = group * self.size if idx > len(self.l): raise IndexError("Out of range") return self.l[idx:idx+self.size] I use it mainly for grouping things like: for x,y in Group([1,2,3,4,5,6,7,8,...],2): process_coords(x,y) but its also applicable to your problem, and works neatly with strings. try: for substring in Group(string, n): Don't you just love python's polymorphism! You don't state what you want to do if the string isn't a multiple of N characters. This version includes the shorter string at the end. Brian. From shagshag13 at yahoo.fr Tue Jul 23 12:26:09 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 23 Jul 2002 18:26:09 +0200 Subject: how to count lines in a file ? Message-ID: hello, i need to count lines in a file (that i *can't* keep in memory, so can't use readlines()) by now i use this : --- import os BUFFER_SIZE = 10000 def lineCount(filename, bufferSize = BUFFER_SIZE): do = 'wc ' + filename p = os.popen(do, 'r') line = p.read() p.close() if line: return long(line.strip().split()[0]) else: lineCount = 0 fhi = file(filename) while 1: lines = fhi.readlines(bufferSize) if not lines: break lineCount += len(lines) return lineCount --- is it the correct ? do you think i can tweak it ? thanks in advance, s13. From woodsplitter at rocketmail.com Sat Jul 27 16:49:04 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: Sat, 27 Jul 2002 16:49:04 -0400 Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> Message-ID: "Jeffrey Keil" wrote: > I'd like to have a Python script open a text file, process the data in > the text file and then write a report to an Excel file. It sounds to me as though what you intend to do might be more complex than a CSV-based solution could comfortably solve (in that you want to "process" the data with Python, then create a "report" with Excel). However, if CSV-import *is* sufficient, it's much simpler than using COM to automate Excel from Python. If you do need to use COM automation, there was a recent thread on the topic: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&frame=right&th=e 6e69b35daac4772&seekm=7876a8ea.0207221138.66a3a5b%40posting.google.com#link1 From mwh at python.net Tue Jul 30 04:55:04 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 08:55:04 GMT Subject: Python design failures (was Re: Let's Talk About Lambda Functions!) References: <3d455445_9@news.newsgroups.com> <3d457011_1@news.newsgroups.com> Message-ID: "Donn Cave" writes: > What he said - "... nearly indistinguishable from single quotes." > Density at the expense of legibility is why I'd say it doesn't really > fit with my ideal of Python programming style. On one of Guido's slides he also mentions problems with typesetters changing both `a` and 'a' to `a'.... > On the other hand, list comprehensions certainly would fall in that > category too, and there's no question that I'm out of touch with the > prevailing sentiment on comp.lang.python about things like this. Hey, I like <>. > And the distribution library appears to use `` rather liberally - > probably more than repr(). Maybe they're older? Not sure on this one -- both are certainly pretty old. > Obviously this doesn't make it any better (is Perl more wonderful > for all the people who use it, or Visual Basic, C++, etc?) But we > can't pretend there's a consensus. Good sigmonster :) Cheers, M. -- Roll on a game of competetive offence-taking. -- Dan Sheppard, ucam.chat From marklists at mceahern.com Wed Jul 17 21:03:18 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 17 Jul 2002 20:03:18 -0500 Subject: newby: How do I execute external progs? In-Reply-To: Message-ID: Regarding the subject: Try os.system and/or os.popen() and friends. // mark - From shagshag13 at yahoo.fr Mon Jul 8 05:17:48 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 8 Jul 2002 11:17:48 +0200 Subject: Memory ? References: Message-ID: Great thanks for the reply ! It helps a lot to understand ! > I'm not sure what you mean by "boxed" in this context. That i can' t guess the size of my arrays (range from 0 to ???) > But if you don't need such alterations and > insertions, a mapping from the compact set [0..N) to any multiset of > N values is indeed faster and less memory-hungry as a sequence, typically > a list, than as a dictionary Sorry to ask but what do you call a "mapping" ? Thanks in advance, s13. From Simon.Foster at smiths-aerospace.com Tue Jul 9 09:10:28 2002 From: Simon.Foster at smiths-aerospace.com (Simon.Foster at smiths-aerospace.com) Date: Tue, 9 Jul 2002 14:10:28 +0100 Subject: 8 Queens Problem Message-ID: <00172807.C22236@smiths-aerospace.com> Just For Fun! I've been working on a solution to the eigth queens puzzle. Here is my attempt. There's a solution in Scheme in SICP which takes only 13 lines. Can anyone come up with a shorter solution in Python, without any of the obvious silliness? Having to do the list copies: r = rows[:] s = solution[:] seems like a bit of a waste, does anyone see a solution that doesn't involve lots of copying? Seems to me that functional languages have the edge for this sort of problem. Anyone have anny comments. SICP = "Structure and Interpretation of Computer Programs" by Abelson, Sussman and Sussman PS. For the functional gurus out there: Would this solution qualify as tail-recursive? PPS. What's a closure? A continuation? ---- import sys def queens( order, rows, solution ): if order: for x in rows: y = order - 1 for i, j in solution: if x - y == i - j: break if x + y == i + j: break else: r = rows[:] s = solution[:] r.remove( x ) s.append(( x, y )) queens( y, r, s ) else: print solution queens( 8, range(8), [] ) From anders at gamebox.net Wed Jul 10 12:24:13 2002 From: anders at gamebox.net (A Nilsson) Date: Wed, 10 Jul 2002 18:24:13 +0200 Subject: JPython and Jython References: <20020710180603.50a4e417.spam@oblomov.org> Message-ID: Jython changed name from JPython a while ago - that?s all. /Ando "oblomov" skrev i meddelandet news:20020710180603.50a4e417.spam at oblomov.org... > > Could someone tell me a bit about the diffrences between JPython > and Jython? I want to implement Python as a scriptlanguage in my > Java environment. What would be the best solution? > > > kalle From Norman_Shelley-RRDN60 at email.sps.mot.com Fri Jul 26 17:28:59 2002 From: Norman_Shelley-RRDN60 at email.sps.mot.com (Norman Shelley) Date: Fri, 26 Jul 2002 14:28:59 -0700 Subject: ?Module re documentation bug, error, or misunderstanding? References: <3D41B265.AD56FF90@email.sps.mot.com> <15681.47874.446657.686812@12-248-11-90.client.attbi.com> Message-ID: <3D41BF1B.905CA623@email.sps.mot.com> Thanks Skip. This solution leads to another question, probably a documentation issue. I do not need "r" or double backslashes when I use \d, \s, \S, ... all the special sequences that \number is included with in the documentation. What indication is there in the documentation that \number must be handled differently than say, \d ? >>> re.match("(.+) \1", '55 55') >>> re.match("(.+) \\1", '55 55') >>> re.match("(.+) (\d\d)", '55 55').groups() <<<< \d works with only one backslash ('55', '55') Skip Montanaro wrote: > Norman> So, what am I missing below as both searches "should" succeed? > > "r". > > >>> import re > >>> re.search("(.+) \1", '55 55') > >>> re.search(r"(.+) \1", '55 55') > <_sre.SRE_Match object at 0x402665a0> > > > > -- > Skip Montanaro > skip at pobox.com > consulting: http://manatee.mojam.com/~skip/resume.html From markus.kaukonen at iki.fi Tue Jul 30 10:47:24 2002 From: markus.kaukonen at iki.fi (Markus O Kaukonen) Date: Tue, 30 Jul 2002 17:47:24 +0300 Subject: How to execute an external binary reading from standard in Message-ID: <3D46A6FC.AA068BC8@iki.fi> Dear all, How to execute a exeternal (binary) program reading from standard input in a python code ? For example : /home/mok/my_prog.bin < my_input.txt My system is Linux and the binary is written originally in fortran 90 (if that should matter). I tried os.popen('/home/mok/my_prog.bin < my_input.txt ') with no success Best Wishes, Markus Kaukonen, Finnland From newfroups at jerf.org Thu Jul 11 23:01:51 2002 From: newfroups at jerf.org (Jeremy Bowers) Date: Fri, 12 Jul 2002 03:01:51 GMT Subject: Python to XML to Python conversion References: Message-ID: <3D2E1793.8030600@jerf.org> thehaas at binary.net wrote: > I'd do the Python -> XML like this: > > outfile = file("out.xml") > > outfile.write("") > for key in dict.keys(): > outfile.write("<%s>%s\n" %(key, dict[key], key) ) > > outfile.write("") > outfile.close() > > How's that?? Well-formed XML, without any DOM-overhead. This is common and incorrect; the XML is not going to be well formed for any number of reasons. The keys of the dict are not required to be valid XML tag names (consider a key "1 2", wrong for starting with a number AND having a space in it). The keys of the dict may not be strings. The values of the dict may not be strings either. The values of the dict may contain any of several XML chars which much be encoded, such as &. Goodness help your XML parser if the text happens to include XML or XML fragments. For each key in the dict, the odds become increasingly stacked against you. If you __know__ you have string keys and string vals, you can do something like from xml.sax.saxutils import quoteattr ... outfile.write('' % (quoteattr(key), quoteattr(dict[key])) ... (untested) but it is still better to go with the XML marshaler or standard Pickle module if at all possible. Also, part of being a good programmer is learning how to elicit good requirements. Do you understand why you need XML? XML is a good transfer language between programs and language boundaries. If you just need to save some data for the same program to retrieve later, you actively *don't* want XML. Use pickle. (Or 'shelve', which I like for quick projects.) If you *are* going to transfer this data to another program, then what do those other programs take naturally? If they have a native format and you can match it, you can save yourself that much trouble. Understand the motivation. If XML is being used as a bullet point, you may consider politely suggesting better, cheaper, faster, faster-to-*develop* alternatives (cPickle). Failing that and if you never intend to transfer the data anywhere, then use the XML marshaler for the buzzword compliance and ease-of-use pickling. (Thought: XML should never be your *first* choice of file format. It is the choice of *last* resort, when you absolutely *need* easy parsing in multiple languages or environments and can't get it any other way. It is then a much better choice then other formats, but only under those limited, albiet extremely popular, conditions.) From ttene at virata.com Tue Jul 9 06:52:44 2002 From: ttene at virata.com (tal) Date: 9 Jul 2002 03:52:44 -0700 Subject: Converting a hex string to a number Message-ID: <4b628986.0207090252.5338178d@posting.google.com> Hello, I am trying to convert a hex string (for example: "0x12345678") to a number (0x12345678 or just 12345678). Can you help me please? Thanks, Tal. From eugene1977 at hotmail.com Sun Jul 21 22:35:49 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sun, 21 Jul 2002 21:35:49 -0500 Subject: can i make a p2p application in python? References: Message-ID: i don't even know what bootstrapping is.. can u recommend a good book to read? i found these books.. JXTA: Java P2P Programming Peer to Peer Application Development(also in java) From cbbrowne at acm.org Mon Jul 15 16:35:04 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 15 Jul 2002 20:35:04 GMT Subject: Python's Lisp heritage Message-ID: Centuries ago, Nostradamus foresaw when Tim Peters would write: > [James J. Besemer] >> ... >> The original semantics (as formally defined in Lisp itself >> [McCarthy]) called for dynamic binding. > > It seems this would have been a surprise to McCarthy : > > http://www-formal.stanford.edu/jmc/history/lisp/node4.html > > See paragraph "d. Free variables". When a user bumped into a function where > the difference between dynamic and lexical scoping mattered, and lexical > scoping was what they needed, "I must confess that I regarded this > difficulty as just a bug". The understanding of these issues was much > muddier at the time. > >> ... >> I find it highly ironic that Perl originally did it the wrong way >> ("local"), although later they introduced a now-recommended static >> binding ("my"). > > More recently, REBOL went down the same path. Dynamic scoping is attractive > for implementation reasons; everyone who succumbs eventually regrets it > (except for RMS in elisp ...). X-Mailer: mh-e 6.1; nmh 1.0.4+dev; Emacs 21.4 Dynamic scope buys you the ability to not need to specify _all_ the values that you might be customizing. If a new Emacs mode requires adding in a bunch of additional parameters, dynamic scope lets them be visible throughout the scope during which they are "live" as opposed to just within the environment in which they were defined. >From a paper on Emacs: "Some language designers believe that dynamic binding should be avoided, and explicit argument passing should be used instead. Imagine that function A binds the variable FOO, and calls the function B, which calls the function C, and C uses the value of FOO. Supposedly A should pass the value as an argument to B, which should pass it as an argument to C. This cannot be done in an extensible system, however, because the author of the system cannot know what all the parameters will be. Imagine that the functions A and C are part of a user extension, while B is part of the standard system. The variable FOO does not exist in the standard system; it is part of the extension. To use explicit argument passing would require adding a new argument to B, which means rewriting B and everything that calls B. In the most common case, B is the editor command dispatcher loop, which is called from an awful number of places. What's worse, C must also be passed an additional argument. B doesn't refer to C by name (C did not exist when B was written). It probably finds a pointer to C in the command dispatch table. This means that the same call which sometimes calls C might equally well call any editor command definition. So all the editing commands must be rewritten to accept and ignore the additional argument. By now, none of the original system is left!" If all you have is lexical scoping, parameters have to get explicitly passed down the chain in order to get from function A to function C. That means introducing additional parameters to function B, which didn't actually care about those extra values. Most of the time, lexical scope is likely to be more useful. But there are places where dynamic scope is to be preferred. -- (concatenate 'string "cbbrowne" "@cbbrowne.com") http://www.cbbrowne.com/info/spreadsheets.html How does the guy who drives the snowplow get to work in the mornings? From martin at v.loewis.de Mon Jul 15 15:03:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 15 Jul 2002 21:03:58 +0200 Subject: Write \x1a to binary file References: Message-ID: "Harald Schneider" writes: > I've got a problem with writing "\x1A" to a binary file on Win32 platform. > I think due tue an issue wiht popen() this terminates the output stream. Is > there any solution for this ? I think there is some win32 module that allows you to set the default open mode for files to "binary". Regards, Martin From charles_mantha at hotmail.com Sat Jul 6 23:36:24 2002 From: charles_mantha at hotmail.com (Charles Mantha) Date: Sat, 6 Jul 2002 23:36:24 -0400 Subject: Why is it crashing? (newbie) Message-ID: Yup, a newbie question again :/ . I am trying to run a small toy program which I modified from a tutorial. It's a questionnaire that uses lists which contains the questions and answers. Every time I try to run this prog it freezes my Python Shell interpreter (IDLE). This is the code : ## This program runs a test of knowledge true = 1 false = 0 def menu(): print "'1' Take the test." print "'2' View the questions and answers." print "'3' Quit." print # First get the test questions def get_questions(): # notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and everything?","42"],\ ["What is a three letter word for mouse trap?","cat"],\ ["What noise does a truly advanced machine make?","ping"]] # This will test a single question # it takes a single question in # it returns true if the user typed the correct answer, otherwise false def check_question(question_and_answer): #extract the question and the answer from the list question = question_and_answer[0] answer = question_and_answer[1] # give the question to the user given_answer = raw_input(question) # compare the user's answer to the testers answer if answer == given_answer: print "Correct" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) == 0: print "No questions were given." # the return exits the function return index = 0 right = 0 while index < len(questions): #Check the question if check_question(questions[index]): right = right + 1 #go to the next question index = index + 1 #notice the order of the computation, first multiply, then divide print "You got ",right*100/len(questions),"% right out of",len(questions) menu() menu_choice = int(raw_input("Choose one of the options: ")), while menu_choice != 3: if menu_choice == 1: run_test(get_questions()) Note : The "calling" part of the code is not finished for the options 2 and 3. But It should at least run the test when you type in 1, no ? From peter at engcorp.com Mon Jul 15 09:18:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Jul 2002 09:18:57 -0400 Subject: isA function? References: Message-ID: <3D32CBC1.C58543C1@engcorp.com> "Delaney, Timothy" wrote: > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > For example, a unit test for a factory function might be checking > > that instances of several different classes were being returned > > depending on the parameters passed in. > > > > If the code were broken so that only a single class was represented > > in the returned objects, Timothy's test would continue to pass > > (bad!) while yours would fail - just as you'd want - alerting you > > to the bug. > > Why would this be bad? Presumably you are testing that the returned objects > have specified semantics. What does it matter if the returned objects are > all of the same type or not - what is important is what happens when you use > them. > > Assuming that the code was *broken*, this would show up in other tests. I guess you can write unit tests your way, and I'll write them my way. I want my unit tests to test the *unit*, the thing I'm trying to test, so I can localize the failure immediately. I don't want the test to ignore certain possible failure modes so that I have to waste time debugging when some other test fails on a routine way across the application, even though it's the factory method which failed. > Artificially restricting the types that you can deal with is generally a bad > idea. If it passes all the unit tests, either it is acceptable, or your unit > tests are broken. If it passes all your unit tests except for an arbitrary > type check, then I contend that your unit test is broken. I contend that this advice is good for real code, but when writing unit tests it's okay to break it. At least, this is what I have found to be a practical way to work when doing test-driven development, where each unit test is written before the code that will make it work. If I want to extend my factory method to return another type of object, I must write a unit test which will fail if it does not do so. Limiting myself to a single test which checks that all returned objects have the right signature is inadequate in this circumstance, though it may be acceptable for you when doing traditional unit testing, writing tests after the fact. -Peter From bdesth at nospam.free.fr Wed Jul 3 21:17:47 2002 From: bdesth at nospam.free.fr (laotseu) Date: Wed, 03 Jul 2002 21:17:47 -0400 Subject: newbie question on Fredrik Lundh's simple script References: <3D231402.81C0E715@gol.ge> Message-ID: <3D23A23B.5070400@nospam.free.fr> Giorgi Lekishvili wrote: > > Fredrik Lundh wrote: > > >>John Boik wrote: >> >> >>>Here is the problem. The frame pops up OK, but when I press the Quit button >>>nothing happens. When I press it twice, Python shuts down. >> >>I assume "Python" means "the IDLE environment" ? >> >>IDLE executes Python code inside it's own interpreter, and >>is also using Tkinter. If you run a program inside IDLE that >>shuts Tkinter down, you'll also shut IDLE down. >> >>That's really IDLE's fault, not Tkinter's... >> >>I recommend running the samples in a stand-alone Python >>interpreter, from the command line. >> >>(or use an IDE that knows how to run Python programs in >>a separate process...) >> > > > Would you like to tell me which are such IDEs, and among them, which are freeware? > > Thank you. > Giorgi > > > > >> > > Well, I'm not sure it's worth having a look, but I've been told about a brand new cross-platform, cross-language, fully scriptable and configurable IDE. It's named Emacs... laotseu From roy at panix.com Sun Jul 7 16:53:23 2002 From: roy at panix.com (Roy Smith) Date: Sun, 07 Jul 2002 16:53:23 -0400 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> Message-ID: Peter Hansen wrote: > We put all of ours in a subdirectory called "unit" [...] we similarly > use "_user" or "_accept" at the end That makes sense. > As for getting out of sync -- this is not a problem if you always > write the test code before the application code I know that's the way it's supposed to happen, but somehow we never seem to quite reach that particular state of bliss :-) > We modify PYTHONPATH to include ".." first and run from the folder > containing the tests. Then the "import module" is all we need. Seems reasonable. > By the way, you might encounter problems with "module-test.py" as > a file name at some point... you couldn't import it, for example. > Use underscores instead of hyphens... Good point; I hadn't thought of that. We've been using the "filename-test" convention with our TCL stuff, and I brought it over from that. Thanks for the input. From aleax at aleax.it Fri Jul 12 04:37:59 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 08:37:59 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: Jonathan Hogg wrote: ... > I'm not sure it is possible to "overuse" XML. It is -- easily. My pet peeve is the idea of using XML files for tasks that obviously need a real database, preferably a relational one. I think some people never really GOT relational databases, no matter that they've been around for decades and are so widespread, and they're now turning to *overusing* XML to cover up for that:-). > If you need to read and > write structured data, why bother coming up with your own format? (see: > the entire contents of /etc) Or why use something that is proprietary to a > particular language or system? (see: Pickle) Speed, size, and convenience are possible reasons. If the structure is highly repetitious, and the amount of data is very large, then repeating the tags identically a zillion times can impose substantial overhead of space and time. Pickling and unpickling can be (say) twice as fast and consume half as much space as going to an XML format. That doesn't really matter unless the amounts of data are huge, of course. But the point is, sometimes they ARE. I/O-bound programs are hardly a thing of the past: CPU's get faster much faster than networks and disks get faster. The need to search "random-access" wise, or "keyed"-wise, is often an excellent reason to avoid a format that requires reading though all of a file to get at a particular piece of data. dbm variants, shelve, and relational databases, can be huge wins here (compared to XML, pickle, or any other choice requiring whole-file reloading). While XML is reasonably human-editable, there may well be formats that are more convenient than it for this purpose, avoiding the need of special-purpose XML-oriented editors and allowing the use of any good old text editor with maximal ease. This is a good reason to keep a human-editable configuration file in non-XML form, in my opinion. Let's try to avoid pro-XML hype in an attempt to counter the anti-XML hype that's suddenly burst on this group...:-) Alex From james.kew at btinternet.com Wed Jul 24 07:20:25 2002 From: james.kew at btinternet.com (James Kew) Date: Wed, 24 Jul 2002 12:20:25 +0100 Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: "Bo M. Maryniuck" wrote in message news:mailman.1027501596.4354.python-list at python.org... > On Tuesday 23 July 2002 19:02, Bjorn Pettersen wrote: > > Now, why on earth would you use that monstrosity instead of: > > > > for line in open(filename): > > count += 1 > > Or even: > > print len(open('/etc/passwd').readlines()) *cough* Reread the OP's problem specification: "Shagshag13" wrote in message news:ahk020$tl4ue$1 at ID-146704.news.dfncis.de... > i need to count lines in a file (that i *can't* keep in memory, so can't use readlines()) The "for line in file" solution addresses this constraint: "len(file.readlines())" doesn't. James From tundra at tundraware.com Wed Jul 10 13:30:02 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 10 Jul 2002 17:30:02 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: Matthias Huening wrote: > Tim Daneliuk wrote in > news:qmqgga.g31.ln at eskimo.tundraware.com: > > >>Does some kind soul out there happen to have a pointer to a >>tutorial/examples on fiddling with the Win32 registry from PythonWin? >> > > > There is a module called pyRegistry. Can't find the url right now, but > you can get it from ActivState: > http://aspn.activestate.com/ASPN/Modules/Python/dist_html?dist_id=11218 > > Matthias Is there some advantage to this module over the standard _winreg module? -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From m.faassen at vet.uu.nl Thu Jul 11 12:54:54 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 11 Jul 2002 16:54:54 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> Message-ID: Alex Martelli wrote: [snip long discourse on holy war topic] > I suspect we'll have (at best) to agree to disagree on the > specifics of this. Yes, this is probably Python's version of the "where do I put the { and } holy war", as you haven't managed to convince me at all; I prefer linebreaks after ':' and indentation for blocks, no matter how small they may be. My eyes do trip over the other variety and leave me with a feeling of frustration. The other Python holy war topic is tabs versus spaces. More than one way to do it can lead to holy wars, apparently. :) Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From hst at empolis.co.uk Wed Jul 3 11:53:09 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Wed, 3 Jul 2002 16:53:09 +0100 Subject: Regular expressions in python Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C56@hendrix.empolisuk.com> Graeme Longman [mailto:glongman at ilangua.com] wrote > Hi, > > I'm using the python module re to search through strings of html text > but I have found that it is taking too long using the seach method. > > I am looping though a list of regular expressions and I find that it > takes much longer when no match is found for the expression > than it does > when a match is found. Is this normal ? > > I have fixed the problem for now by using string.find() > before searching > the text but was wondering if anyone had any ideas on a better > technique. > > Is there something else I should be using ? I am using '.*' and > re.DOTALL in my expressions but that doesn't seem to be the problem. > > Thanks for any help in advance. > > Graeme > I've found it is MUCH faster if you convert your list of regular expressions into a set of bracketed expressions separated by | (use re.VERBOSE as well!) and then use re.findall. That way you get a giant list of tuples, with the non-matching expressions returning the empty string. HTH Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From smouttebolleke at hotmail.com Sun Jul 7 11:45:55 2002 From: smouttebolleke at hotmail.com (MontrezVosSeins) Date: 7 Jul 2002 08:45:55 -0700 Subject: Why is it crashing? (newbie) References: Message-ID: "Charles Mantha" wrote in message news: > > menu() > menu_choice = int(raw_input("Choose one of the options: ")), > while menu_choice != 3: > if menu_choice == 1: > run_test(get_questions()) Maybe this should do it, menu() menu_choice = input("Choose one of the options: ") if menu_choice == 1: run_test(get_questions()) elif menu_choice == 2: .... elif menu_choice == 3: print "Bye" else: print "Whoops, you have made a mistake! Try again." menu() From max at alcyone.com Fri Jul 5 22:27:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 05 Jul 2002 19:27:05 -0700 Subject: Why self? References: Message-ID: <3D265579.D1AE137@alcyone.com> Courageous wrote: > In other environments, you're stuck doing things like: > > m_i = i; > > or... > > i = i_arg; > > ... a clear sign of a struggle to resolve mishandled ambiguity. Or better yet, this->i = i [this.i in Java]; -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From stefan.heimann at web.de Sun Jul 28 06:19:36 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 28 Jul 2002 10:19:36 GMT Subject: TAB completion Message-ID: Hi! I have a application with a builtin interactive shell. I use the readline module for command completion and history browsing. The following code enables filename completion: try: import readline except ImportError: self.printErr("Could not import readline.\nHistory browsing " \ "and tab completion will not be available.") else: readline.parse_and_bind("tab: complete") readline.set_completer_delims('\t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>?') I also want to have command completion, but I don't want to write a complete function for the filename completion (because it's already there). I thought something like def complete(text, state): if text seems like a command: myCmdCompletion(text, state) else: pythonsBuiltinCompletion(text, state) could do the job. My problem is: How can I call the default completion function that comes with the python distribution? thanks for helping Stefan From gregory.p.green at boeing.com Fri Jul 12 19:30:29 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Fri, 12 Jul 2002 23:30:29 GMT Subject: Specifying linker and compiler in distutils Message-ID: We are trying to build a c++ extension using distutils on SGI irix. C++ source needs to be linked using the 'CC' command on sgi instead of 'ld' so that template instantiation can be done correctly. I scanned through the documentation and source of distutils, and didn't see an obvious way of specifying this. Can anybody point me in the right direction? -- Greg Green From jdhunter at ace.bsd.uchicago.edu Mon Jul 29 12:16:34 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 29 Jul 2002 11:16:34 -0500 Subject: What is a glue language? In-Reply-To: (Jens Kubieziel's message of "Mon, 29 Jul 2002 16:33:32 +0200") References: Message-ID: >>>>> "Jens" == Jens Kubieziel writes: Jens> Hi all, the word 'glue language' is mentioned in the FAQ. I Jens> have no clue :-) what this could mean. Could someone explain Jens> this (also a german translation is appreciated)? A glue language is used to hold many parts together. People who have worked with computers for a while usually have lots of little pieces of software running on multiple platforms to do their work for them, and it is hard to integrate all these pieces together. python is good at interoperating with all these pieces -- it can run command line utilities, talk to every major database, automate web interaction, integrate compiled libraries from c/c++/fortran and so on. But because python is a full, object oriented programming language with excellent built in libraries, it can do much more. As Paul Rubin noted: IMO a bunch of the frustration I sometimes feel with Python comes from its originally being intended as a "glue" language. It's too good for that, and finds itself used as a work horse or even a race horse. Neither type of horse belongs in the glue factory ;-). As for the translation, Es tut mir leit, mein Deutcsh ist nicht so gut. Ein 'glue' sprache versucht alle die teile zusammen halten..... Tcshuss, John Hunter From rs at onsitetech.com Tue Jul 9 15:19:40 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 19:19:40 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: <3D2B36FD.7080002@onsitetech.com> Charles Hixson wrote: > If you are subclassing a class that someone else has written, you don't > want to accidentally redefine an internal name. Sorry. I can accept > that you should be able to explicitly access it, but to be able to > change it by accident is (would be?) a misfeature. > > I didn't believe that this happened in Python. It does, and it seems a > significant flaw.... Yeah - this is getting to what I'm talking about. From the Python Tutorial, section 9.6: "Name mangling is intended to give classes an easy way to define ``private'' instance variables and methods, without having to worry about instance variables defined by derived classes [...]. Note that the mangling rules are designed mostly to avoid accidents..." This is where I got the idea that variables should be marked with __ in order to function in the way you expect. Like, if I understand this correctly, a programmer could be forced to comb recursively through the code of all superclasses looking for possible collisions. Robb From tim.one at comcast.net Fri Jul 26 16:55:41 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 26 Jul 2002 16:55:41 -0400 Subject: performance problem in python 2.2 In-Reply-To: Message-ID: [Jeff Davis] > I wrote a small python program to help me solve a math problem. When I > tried to run it with large values, What does "large values" mean? Please be specific. > it ate all my RAM and I eventually had to kill it. I tried writing the > same thing in C and it used almost no RAM (and had an upper limit) and > finished much faster. When you wrote it in C, how did you declare p? In your Perl code $p is a double-precision float, and in your Python code p is an unbounded integer (a data type Perl doesn't have natively). It's impossible to know what you intended (although easy to guess ). > Then I was talking to someone who suggested that I try perl. I have the > exact same algorithm in perl, and it doesn't eat my RAM, and executes > much more quickly (same order of magnitude as the c program). It seems > almost as if there's a memory leak in one of python's simple math > operations, because it is so much worse than the other ones I tried. > > I have listed the two programs below. Does someone think I found a > bug/memory leak? I don't, no. > Does someone know about something else that might be going on? You do, yes -- but you haven't told us what yet . > ... > ===================python======================== > #!/usr/bin/python2.2 > > import sys > > n = 1.0 > p = 2L**64 If you intend this to be a float, say p = 2.0**64 instead. > c = long(sys.argv[1],10) > > for i in range(1,c): This may or may not be troublesome, depending on what you meant by "large values". You could try using xrange instead. Python code also runs significantly faster if loops are in functions (local variable access is significantly quicker than global variable access in Python). > n = (n * (p-i)) / p > print 1-n > ====================perl========================== > #!/usr/bin/perl > > $p = 2**64; Here $p is a float, although it "looks like" an integer. You should be aware that, because it's a float, your later $p-$i computes exactly $p until $i gets large enough to affect $p's least-significant bit. > $c = $ARGV[0]; > > $n = 1; > foreach $i (1..$c) { > $n = ($n * ($p-$i)) / $p > } > print 1-$n, "\n"; From kdart at kdart.com Wed Jul 31 07:01:49 2002 From: kdart at kdart.com (Keith Dart) Date: Wed, 31 Jul 2002 11:01:49 GMT Subject: How do you import a module with "." in its filename? References: Message-ID: In article , "Duncan Booth" penned these words: > "Andrew P. Lentvorski" wrote in > news:mailman.1028080249.16165.python-list at python.org: > >> So, how do I import a module with "." in its filename? >> >> > fname = 'c:/test/a.test.py' > f = file(fname, 'r') > a_test = imp.load_module('a_test', f, fname, ('.py', 'r', > imp.PY_SOURCE)) f.close() > > See the module imp documentation for further details. > But.... why bother? Why not just rename the original modules to a_test.py, etc.? That's what I do. -- -- ^ \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart ---------------------------------------------------------------------------- Public key ID: B08B9D2C Public key: ============================================================================ From mwh at python.net Thu Jul 25 13:12:19 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 25 Jul 2002 17:12:19 GMT Subject: Speed up Python by up to 5% ? References: Message-ID: "Edward K. Ream" writes: > It may be possible to speed up the Python interpreter 3% to 5% with a > trivial modification. Maybe. [snip] > In short, this is a very tight loop. But can't it be improved? The byte > code is littered with SET_LINENO opcodes. Has anyone considered moving the > test: > > if (things_to_do || --tstate->ticker < 0) > { /* handle periodic things */ } // not usually executed. > > out of the main loop an into the case for SET_LINENO? I don't think so, because a more seriously consdiered modification has been removing SET_LINENO entirely (it's *only* used for tracing, these days). There's a patch on sf about this. > The only problem I can think of is that there would be some loop that does > not involve any SET_LINENO opcode at all. Can anyone come up with such an > example? Anything run under "python -O"... > Is there any other reason for moving the "periodic things" test > out of the main loop? Even if there were places where a loop contains no > SET_LINENO opcode, it might be worthwhile to have the compiler insert an > DO_PERIODIC_THINGS opcode in the bytecode for the loop. This might be a reasonable strategy anyway. Would require complicating the compiler to ensure one got into every loop, etc, but that should be easier when Jeremy's ast-branch lands. > How much time might we expect to save? Oh no, you're not going to sucker anyone with that one . Except maybe yourself . > Let us look at the most favorable case first. As it happens, the > SET_LINENO case of the main loop takes about the _least_ amount of > time to execute (on average) so the speedup relative to this case > will be the _greatest_. Here is the code that typically gets > executed: > > case SET_LINENO: > f->f_lineno = oparg; > if (tstate->c_tracefunc == NULL || tstate->tracing) > continue; // typically _is_ executed. > // typically _not_ executed. > > As a rough estimate, let us just count C instructions in the loop through > this case: > > if (things_to_do || --tstate->ticker < 0) > { /* typically not executed. */ } > opcode = *next_instr++ > if (opcode >= HAVE_ARGUMENT) { > next_instr += 2; > oparg = ((next_instr[-1] << 8) + next_instr[-2]) > } > switch (opcode) > { > case SET_LINENO: > f->f_lineno = oparg; > if (tstate->c_tracefunc == NULL || tstate->tracing) > continue; // typically _is_ executed. > // typically not executed. > } > > Depending on how you count, there are 8-10 instruction here, I make it rather a lot more than that, esp on RISC architectures... > so saving the > line: > > if (things_to_do || --tstate->ticker < 0) > > might save up to 10% to 15% of the time through this loop. This is a very > rough estimate, and the actual value may be less. Notice that code marked > "typically not executed" has little effect on "amortized" time. > > Are typical opcodes much more expensive than the simplest SET_LINENO case? > I wrote a simple program based on dis to count the static occurrences of > bytecodes. You should look at Jeremy's work counting instructions for individual bytecodes: http://www.zope.org/Members/jeremy/CurrentAndFutureProjects/PerformanceMeasurements Also, there's the DX_PAIRS & so on macros you can build Python with. For one thing, static frequency of bytecodes != (in general) dynamic frequency. [...] > Dynamic execution frequencies will not match these static frequencies > exactly, but I see no reason to suppose they will be wildly different. If > anyone has real dynamic data, I would like to see it :-) Ah. As Tim once said, this editor doesn't go backwards :) You can make real data yourself. grep for DYNAMIC_EXECUTION_PROFILE. > Typical "fast" opcodes are LOAD_FAST and LOAD_CONST. The code for them is > as follows: > > case LOAD_FAST: > x = GETLOCAL(oparg); // x = fastlocals[oparg] > if (x == NULL) { // if (x == NULL) ... > /* Typically not executed. */ > } > Py_INCREF(x); // x->ob_refcnt++ > PUSH(x); // *stack_pointer++ = x > if (x != NULL) continue; > break; // Typically not executed. > > case LOAD_CONST: > x = GETCONST(oparg); // x = f->f_code->co_consts->ob_item[oparg] > Py_INCREF(x); // x->ob_refcnt++ > PUSH(x); // *stack_pointer++ = x > continue; > > Again we can see that eliminating: > > if (things_to_do || --tstate->ticker < 0) > > from the main loop might save up to 10% of the time taken to execute these > instructions. > > Some opcodes _will_ take much longer than others to execute. I have marked > the "heavy hitters" above with **. Suppose we say that the heavy hitters > will take at least 10 times longer than the other opcodes to execute, so we > shall add 10 times their total count to the total count of 95454 shown > above. The new total then becomes roughly 300,000 rather than 100,000, so > perhaps by this very rough estimate we might save 3-5% rather than 10-15%. > > Still, this might be a real savings. What do you think? I think you should get some real data. > P.S. The code needed to execute the "periodic" tasks in the SET_LINENO case > might be simpler than the code in the main loop, because we would execute > the periodic tasks _every time_ the SET_LINENO is seen. Uhh, what about sys.setcheckinterval? [snip] > Again, dynamic data would be helpful. No kidding! Don't want to discourage you, but finding performance enhancements for Python is not all that easy any more -- most low hanging fruit aren't that tasty :-/ Cheers, M. -- Academic politics is the most vicious and bitter form of politics, because the stakes are so low. -- Wallace Sayre From fredrik at pythonware.com Tue Jul 9 19:04:03 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 09 Jul 2002 23:04:03 GMT Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: Martijn wrote: > They do kick you out a bit readily, I agree. I got somewhat annoyed > when I got kicked out while apologizing for spamming with a misfired > copy & paste buffer. the first time I visited, I was kicked out (and banned, iirc) within a couple of seconds... From whisper at oz.net Wed Jul 3 18:53:19 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 3 Jul 2002 15:53:19 -0700 Subject: PythonWin + other GUIs = CRASH! In-Reply-To: <3D232FEE.3010606@gmx.de> Message-ID: Only reason I can see for needing something like this (unless you're a masochist or a masochist's friend) is in a GUI-independent IDE. There is only one solution: create a remote control module and then spawn your target in a new process/python interpreter (that autoloads the remote controller before the target is loaded). This is the only way to ensure that the event processing loop for the GUI isn't disturbed by an event processing loop from another GUI library. Of course, it also keeps the target app relatively isolated from the host IDE code. I know that the Wing IDE and HAP debuggers both have a remote control protocol; have a look. Alternatively, looking through Python's "batteries", the RPC module might be a place to start on such a scheme. Regards, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Ingo Linkweiler > Sent: Wednesday, July 03, 2002 10:10 > To: python-list at python.org > Subject: PythonWin + other GUIs = CRASH! > > > Hi, > > when using the PythonWin IDE with other GUI-Toolkits (Qt, > wxPython, Pygame), the application crashes or freezes when > running them with "file->run". > > Is it possible to avoid this? > > Do you know other IDEs, which can be used with [Qt, wxPython, Pygame]? > > Ingo > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From jacek.generowicz at cern.ch Thu Jul 25 11:04:51 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 Jul 2002 17:04:51 +0200 Subject: Completion in emacs mode References: Message-ID: "Mark McEahern" writes: > > I'm looking for the ability to do command completion in Emacs' python > > mode. I haven't managed to get Google to show me anything really > > pertinent to this quest. > > http://www.geocrawler.com/archives/3/338/1993/12/0/1878323/ [link to description of new-dabbrev] Thanks. Abbrev works by searching buffers for candidates (IIRC). I need to complete names of objects and their attributes (and their attributes, and ...); these will either have been defined in C++ extension modules, or constructed at runtime based on information obtained from another process via a pipe. I think that dabbrev and its derivatives will not be able to get at this information, though I would love to hear that I am mistaken about this. From remi at cherrypy.org Sat Jul 20 07:32:04 2002 From: remi at cherrypy.org (Remi Delon) Date: 20 Jul 2002 04:32:04 -0700 Subject: Appication server other than zope References: <20020718194213.22848.28280.Mailman@mail.python.org> Message-ID: <585c0de9.0207200332.293bf78e@posting.google.com> Drew Csillag wrote in message news:... > > Hi. > > I'm searching for application servers other than zope. Would somebody > > tell me where to get such thing? > > I know of at least two (I know there are more), there's SkunkWeb > (http://skunkweb.sourceforge.net) and WebWare (http://webware.sf.net). > There are a bunch listed at > http://www.python.org/cgi-bin/moinmoin/WebProgramming. > > I myself am partial to SkunkWeb, but don't take that as too strong of an > endorsement as I am one of it's authors. > > Drew Csillag There's also CherryPy (http://www.cherrypy.org). For an example of a commercial web site developed with CherryPy, check out http://www.urbishop.com/indexPage (sorry, it's all in French :-)) Remi. From K.Rdt at TU-Berlin.DE Wed Jul 3 15:18:52 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Wed, 03 Jul 2002 21:18:52 +0200 Subject: HT clear some wxPython fram? In-Reply-To: <20020703114714.47419520.logiplexsoftware@earthlink.net> Message-ID: <64SOKICUR2V2X08TPZYOI1ZLF41B6IF.3d234e1c@FRITZweb> Am 03.07.02 20:47:14, schrieb Cliff Wells : >class MyPanel(wxPanel): > def __init__(self, parent, fontsize = 12): > wxPanel.__init__(self, parent, -1) > self.SetBackgroundColour(wxWHITE) > self.text = [] > self.fontsize = fontsize > EVT_PAINT(self, self.OnPaint) > > def draw(self, dc): > dc.Clear() > font = wxFont(self.fontsize, wxMODERN, wxNORMAL, wxNORMAL) > dc.SetFont(font) > y = 0 > for t in self.text: > dc.DrawText(t, 0, y) > y += self.fontsize + 2 > --------------------------------------------------------------------- Hi OK! Well done. A further problem: The frame is 'renewed' after 14 rows, so the netstat-output is in the beginning (more than) doubled. Is some sort of - excuse me - GOTOXY? Or is this another buffer(?)problem? BTW: I've now subscribted to wxpython-group. K at Rdt --------------------------------------------------------------------- From johnroth at ameritech.net Wed Jul 31 09:24:47 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 31 Jul 2002 09:24:47 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> <3d46c6a2$1_1@hpb10302.boi.hp.com> Message-ID: "Huaiyu Zhu" wrote in message news:slrnake5a1.467.huaiyu at gauss.almadan.ibm.com... > Daniel Fackrell wrote: > >"John Roth" wrote in message > >news:ukddqtelmp6eda at news.supernews.com... > >> The reason I say "indenting 2" is that you need two > >> dedents to make it work: one to close the def, which does > >> not have it's own indent, and one to finish off the expression > >> in which the def is imbedded. > > > >Again, the problem is that Python must assume that when it sees code > >indented further than the previous line, a single indent is intended. It > >has no way of knowing how many indents you mean unless something is actually > >indented to each level along the way. > > I don't quite get the idea why it has to indent 2. See examples below. > > >In addition to that, indentation is currently ignored inside (), {}, [], > >strings, and on lines following an escaped newline. Some of that could > >change, perhaps, but it seems to me that it might break existing code. > > > >I do see merit in this discussion, though, because I see class and def > >statements as really being a shorthand for doing two things at once, namely > >creating a function and then binding it to a name. > > > >Admittedly, there are probably cases where the second part does not apply > >all that well. Perhaps a case where you want a list or dict of functions > >would be one such case. Binding to the name simply adds a step along the > >way. Passing a callable object as a parameter to another callable object > >would probably be another such case. > > Here's an example to exand on the idea. > > a = { > 'func1': def (x,y): > lots of things > more things > return x+y > 'func2': def (x,y): > lots of things > more things > return x-y > 'func3': def (x,y): > lots of things > more things > return x-y > } That works nicely, and you're right, you don't need two dedents in this case, so you don't need two (virtual) indents either. > For vertical scoping, it is not necessary to separate items with commas. Is this valid Python in general, or is this another change to the syntax? > >The issue quickly becomes readability, though. Would you want to be able to > >do a complex multi-line def or class statement inside an assignment creating > >a list, for example? And how would you do that without indentation? > > > >funcList = [ Insert idea here ] > > This does not look too bad, although it does take a while to get used to. > For simple functions still lambdas look better. > > curries = [ > def (x): > return def (x,y): > return x+y > > def (x): > f = def (x,y): > return x-y > return f > > lambda x: lambda y: x*y, > > class: > def __init__(self, x): > self.x = x > def __call__(self, y): > return x/y > ] Another nice example. Thanks. Again, the commas are missing, which may be a good thing, or it may not. John Roth From hjwidmaier at web.de Tue Jul 2 07:05:16 2002 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 2 Jul 2002 04:05:16 -0700 Subject: Python needs better error reporting References: Message-ID: <6e990e29.0207020305.76551dcb@posting.google.com> "James J. Besemer" wrote in message news:... > Tim Peters wrote: > > > Well, "xor" isn't legit there, but other tokens that are OK after > > > > if s == ' ' > > > > include > > > > [a ong list] > > The question is NOT be what all may follow the string literal. Rather it should > be what tokens are legal between the string literal and end of line? Very > different questions. > > If I'm not mistaken, only ":" or "\" are legal in that narrow context. Instead of listing all the legitimate tokens that may follow, why not just give something like "Incomplete 'if' statement?" This "invalid syntax" is really kind of a lazy excuse (there's this one operating system that gives errors like "Error: one of the bazillion operations you started by clicking on that button did not work." Helps a lot. Really.) The other day I removed a try/except and forgot to dedent the block. "SyntaxError: invalid syntax" Embarrassing as it is, but it took me a while to figure out what was wrong. "Unexpected indent" or "Unexpected start of block" or something along those lines would have showed me directly what the error was. Whenever I write a parser, I try really hard to tell the user why an error is thrown (and surely fail miserably). Python, being such a beginner-friendly language, ought to do better than "invalid syntax." Guess I just shouldn't make errors any more. ;-) Hans-Joachim From aleax at aleax.it Fri Jul 5 12:31:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 16:31:18 GMT Subject: [OT] What is Open Source? (fwd) References: <7x65zv5254.fsf@ruckus.brouhaha.com> Message-ID: David Mertz, Ph.D. wrote: ... > pretending that you "contract" for "intellectual property", you create > the illusion that IP is something inherently in your possession. I can Maybe not "inherently", in that an idea is not "in my possession" until I've thought of it (on my own or on others' prompting). But then, neither is a bushel of corn "inherently in my possession" until somebody's harvested it (which implies it's been grown first), etc. So I may be missing the distinction. Let's take an example. Say that my family works in the pottery gilding trade. It's a reasonable business, although it takes extreme care and skill to use just the minimal possible amount of gold to give the gilded pot the right appearance, and it's quite specialized-labor intensive. Now, maybe by accident and maybe because I'm inherently motivated to tinker in strange ways, I come up with a huge enhancement on the classic gilding technique I learned at grandpa's knee. By making a pile of rags soaked in appropriate solutions, and putting the pot to be gilded, well-rubbed with graphite powder, and a lamel of gold, in appropriate places, I find out the pot does get gilded, slowly but surely, with an extremely low amount of gold compared to what it would take in order to get it that good manually -- and while it's being gilded I can read the Baghdad Times, or whatever passes for it in the (I believe) 9th century. Yes, it does seem incredible one could actually come up with such a thing as electricity and galvanic effects on one's own in such fashion, but, according to some archaeologists, this MAY have happened in 9th century Baghdad -- at least, it's one way to explain a certain rather mysterious archeological find. If this specific technological piece of luck should be fictitious, no matter -- you can most certainly think of other analogous possibilities. Now, absent any concept of "IP", what shall I do with my find? Most assuredly, unless I have an unusual amount of goodwill towards mankind, I'll endeavour to keep it a secret of my trade. Isn't "trade secret" the oldest form of "IP"? By exploiting my new technique, I can get results similar to, or better than, those of my competitors, with less effort and (crucially) much less gold for a given gilding task. I'll only teach the secret to my oldest son, as soon as he's old enough to be trusted to keep it and familiar with the basics of normal gilding technologies of the time. Similarly, he'll only teach it to his own oldest son, and so on. We can't afford to let the secret escape, or it's bye bye to our competitive advantage -- if other gilders learn of the new trick, they'll start using it, and the price of gilded pots will fall accordingly. Of course, by keeping this a secret, we're making it quite likely that the secret will be lost one day -- maybe not to resurface for the better part of a millenium. Well, tough -- if society grants me no benefit or protection for revealing my discovery, I sure owe society no such revelation if I can possibly avoid it, no? We do know for sure that such secrecy was the norm, much later (in the late Renaissance) for such techniques as solving 3rd and 4th degree polynomial equations. Niccolo` Tartaglia, or whoever it was who first came up with that idea, held it as his own peculiar secret as long as he could -- basking in the glory of being the only one learned and clever enough to accomplish such tasks, and teaching it only for princely sums and avowals of secrecy (one such was broken, which is how the technique then spread). If a non-disclosure contract had been recognized in law at the time, I guess Tartaglia (or whoever) might have managed to keep it a secret quite a bit longer. Working on "just word of honor" proved less reliable. Now, the "contract" idea may be a bit clearer. We, collectively, want to encourage people who have thought up, discovered, etc, nice and clever ideas, to share them. For that purpose, it may be in society's collective advantage to award some prize for such sharing. It's quite hard to come up with equitable ways to determine such awards so they'll indeed encourage the sharing (and indeed the investment in the thinking-up) without also rewarding useless ideas. A temporary monopoly is a clever, market-oriented way to let the appropriate award values be determined mechanically -- revealing the idea is deemed to be worth whatever 15 years' (or other fixed amount of time) of exclusive exploitation of the revealed idea may be. In some cases, of course, this will be too high, and in others too low (when it's far too low, the idea won't be revealed, which is why we still DO have trade secrets these days, of course). But, take some give some, it's still a neat hack overall. By raising the value of discovering things, it also produces more discoveries, of course -- since when you discover something you may still try to gain from your discovery the old way (keep it secret) OR avail yourself of the new mechanisms, the discovery is made more valuable, so you're incentivated to expend more time and energy in the hope of making discoveries. Now, of course, there are inherent weaknesses, and, like for just about any social arrangement, ways and means to work around it, exploit it for rent-seeking, and so on. Many discoveries could not be usefully exploited without revealing them anyway: in this case, rewarding the revelation may turn out not to be in society's overall interest (unless the "encouraging more discoveries" factor should dominate). Some discoveries are "in the air" when the time is "ripe" for them -- then, awarding a temporary monopoly to whoever happens to come up with them first is rather arbitrary. Classifying the various kinds of discoveries and adjusting per-kind the amount of time of the temporary monopoly might help -- but of course the rent-seekers may fight this by lobbying. But for each of these issues one needs to get down to specifics rather than just take some kind of overall philosophical and moral stance. There's no misconception involved as you state...: > actually hold my bushel of corn, and as long as I hold it someone else > can't. By pretending IP has the same nature, one falsely > naturalizes--us Lukacsian's say "reify"--the "thing" that one "has." Consider a field of grass. The fact that my cow is grazing there doesn't, per se, impede other people's cows. But if everybody can graze their cows at will, overgrazing will irretrievably damage the field, and all involved -- the 'tragedy of the commons'. To avoid it, it may be in society's best interest to recognize the concept of 'property' -- empower a single individual or firm to stop others' cows from grazing on each piece of land. A society's choice to acknowledge and protect the property of land is just as "artificial", or "falsely naturalized", as that to acknowledge and protect a temporary monopoly in exploiting some idea. The fact that a field of grass is something you can touch and an idea isn't is quite besides the matter -- one could easily philosophize about the field of grass and find out it has nothing but social "reality" anyway (at the very least, what distinguishes THIS field from THAT field -- except, e.g., fences that our social contract may let us put up? Or just a social covenant that "Jim's cows and his ancestors have been grazing there exclusively since time immemorial"? Etc, etc -- and indeed, what the land's "property" protects is not really the physical object, but the less tangible concept of USING certain sets of physical objects in socially sanctioned ways, &c). Land property is quite as subject to abuse, rent-seeking (indeed, 'rent' was first used specifically for land!-), etc, as any other social arrangement. Look at the vicissitudes of land reform in various countries and eras to see how hard it has generally been to adjust this social contract in ways that would in fact keep it in society's overall benefit. That doesn't condemn the concept of "land property" nor the "reification" of property, any more than your arguments, or the current abuse-ripe state of many aspects of intellectual property, condemn that of "intellectual property". Alex From jussij at zeusedit.com Thu Jul 11 18:32:25 2002 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Fri, 12 Jul 2002 08:32:25 +1000 Subject: Automating MSDEV studio build process References: Message-ID: <3D2E0779.201@zeusedit.com> Bjorn Pettersen wrote: > Does anyone have any experience automating a nightly build process using > Python in combination with MSDevStudio? I remember some discussion here > about it a while ago, but I couldn't find any reference to it through > Google... It is possible for MSVC 6.x and onwards to build the project using the command line. Here is a link to the details (notice that the URL has been wrapped): http://msdn.microsoft.com/library/default.asp?url=/library/en-us /vcug98/html/_asug_building_a_project_from_the_command_line.asp Jussi Jumppanen Author of: Zeus for Windows, Win32 (Brief, Emacs, etc) FTP Text Editor "The C/C++, Java, HTML, FTP, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From tim at lesher.ws Thu Jul 18 13:14:24 2002 From: tim at lesher.ws (Tim Lesher) Date: 18 Jul 2002 10:14:24 -0700 Subject: slicing and parallel assignment: inconsistent behaviour?? References: Message-ID: tjd at sfu.ca (Toby Donaldson) wrote in message news:... > This works as I expect. But if I leave out the 10s in the slice > indices, I get this: > > >>> A = range(10) > >>> A[1:5], A[5:] = A[5:], A[1:5] > >>> A > [0, 5, 6, 7, 8, 1, 2, 3, 4] > > Where has the 9 gone? You're overwriting a[5] twice. Look at it step by step: >>> a = range(10) You next want to do a[1:5] = a[5:]. But those are different-sized slices: >>> a[1:5] [1, 2, 3, 4] >>> a[5:] [5, 6, 7, 8, 9] So a[1:5] gets replaced with [5, 6, 7, 8, 9], and a[5:], _which starts at the 9_, gets replaced with [1, 2, 3, 4]. -- Tim Lesher tim at lesher.ws From robert_kuzelj at yahoo.com Wed Jul 3 15:43:50 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 3 Jul 2002 12:43:50 -0700 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: hi jonathan, > 1. Reverse the test and check to see if something is an instance of 'type' > of 'types.ClassType', i.e., a new-style class or an old-style class. > > if isinstance(source, type) or isinstance(source, types.ClassType) > return source() > else: > return copy.copy( source ) that is exactly what i did. but i dont like this solution cause as i told before it is rather implicit than explicit. > 2. If you know that the instances you are creating will not have '__call__' > methods, then you can differentiate classes and instances by the fact > that classes are callable: > > if callable( source ): > return source() > else: > return copy.copy( source ) > > This works equally well for old- and new-style classes. Conveniently it > also works functions that create objects and callable instances > masquerading as classes or functions that create objects (hoo hah). cant do that since i have absolutly no control of what is being given to me. > Oh, you can tell us. No matter what crimes your contemplating, you can take > comfort in the fact that they can probably be made more horrifying with > metaclasses ;-) ;-) dont despair! i WILL use metaclasses on a later stage of the project. ciao robertj From tim at bladerman.com Sat Jul 27 09:19:43 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sat, 27 Jul 2002 13:19:43 GMT Subject: Guide to the python interp. source? References: Message-ID: "Michael Hudson" skrev i meddelandet > "Tim Gahnstr?m /Bladerman" writes: > > but I would also be happy if I found a small description och what > > code is where, > > Well, the interpreter mainloop is in Python/ceval.c, object type > implementations are in Object/*.c, ... <...> > Reading Include/object.h (and maybe other headers -- objimpl.h?) might > give some clues. That is a start atleast, thanks for that, I will start my explorations there > > or anything like that. A lot of projects have "a small guide for > > wannabe developers" but I havn't found anything like that for this > There's http://www.python.org/dev/, but there's nothing of the sort > you're asking for here, really. I noticed, but thought that I just had missed it. I thought there must be some where for such a large project. But the problem is ofcourse ever present, "nobody likes to do documentation" > > Things I want to change is for example, everything should be "call by > > refferense", > That may be very hard. If you want things like this: > > def f(x): > x += 1 > > i = 2 > f(i) > i --> 3 > > then you have problems. That is exactly what I want to have, that is more intuitive I think and I don't think it must be that hard either. It is not a speed issue so it must not be a true CBR. I will probably figure out some ugly hack to make it seem like CBR. Maybe look into value/copy return as Alex Martelli mentioned. What I want is not really CBR but the, from Ada known "in out parameters" or the Pascall "var parameter". > > redirect output, > Probably easy. Not quite sure what you mean here. Didn't really mean anything briliant there, it was just small things that poped out of my head while I was writing. I meant I want all output (text, graphics, buttons, etc) in a certain window in the IDE I am creating. > > better errormesages, > Examples? Feel free to contribute these back to the project... Ofcourse I will contribut them back if I create something there that is usefull for alot of people. Maybe the error messages I want to have is not so badly needed for experienced programmers but more for beginners. A traceback is for instance really cryptic to a novice programmer I want an errormessage to look loike this. "The program stopped running for some unknown reason. It is likely an error on line 23 in the file "myprog.cod": if (max(3)>variable): The error is probably caused by the call to the function max(). If you mean to call the built in function max it must have two arguments, namely "val1" and "val2" but you only supply it with one argument (constant 3). On the other hand it might also be a misspelled call to your own function maz() in "mylib.cod" " Currently the errormessage looks like this instead: "Traceback (most recent call last): File "", line 1, in ? if max(3)>variable: TypeError: min() or max() arg must be a sequence" It is ofcourse likely that I won't be able to create an errormessage just like I want but atleast that is my future goal. Thanks alot for the time you took to answer. Tim From trentm at ActiveState.com Wed Jul 10 18:10:45 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 10 Jul 2002 15:10:45 -0700 Subject: Python in the enterprise: Pros and cons In-Reply-To: <33e8a47f.0207101302.1bd3d902@posting.google.com>; from sarah.fraser@cnet.com on Wed, Jul 10, 2002 at 02:02:33PM -0700 References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: <20020710151045.D3737@ActiveState.com> [builder wrote] > Python has many fans in the open source community, but is it ready for > the enterprise? Here are the advantages and disadvantages of using > Python in the corporate environment. > http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm > The cons: > ... > - Absence of a commercial support point, even for an Open Source project > (though this situation is changing) > ... Perhaps you missed: http://www.ActiveState.com/Products/PythonDirect/ Cheers, Trent -- Trent Mick TrentM at ActiveState.com From bogus@does.not.exist.com Wed Jul 31 18:21:14 2002 From: bogus@does.not.exist.com (chris) Date: Wed, 31 Jul 2002 18:21:14 -0400 Subject: wxRadioBox : start with none selected? Message-ID: thanks for great advice previously on lists and dicts. Good stuff, and my code is about 1/3 as long now! how do i set a radiobox to default to no choice until the user chooses? i need the "mouse click" for further processing, and if it stays on its default, it seems there is no wxEVT_COMMAND_RADIOBOX_SELECTED event. i realize the selection can be passed even if the user does not actively click on it, but I have no way of knowing if they have agreed to the default, or not gotten that far yet - each selection leads to other choices in real time, so it's not a "submit when finished" setup. this seems like an option that i can't find, since it seems common you might not want to predispose the user to a choice. something along the lines of wxRadioBox.SetSelection(none). chris ps, if thtis was IMPOSSIBLE, i could fall back on using two radio buttons instead of each radio box, since they start unselected, but that might be a huge pain, and would be giving up. From donn at drizzle.com Sat Jul 27 21:14:44 2002 From: donn at drizzle.com (Donn Cave) Date: Sun, 28 Jul 2002 01:14:44 -0000 Subject: how to count lines in a file ? References: <7aU%8.139472$vm5.4528856@news2.tin.it> <1027656130.63094@yasure> Message-ID: <1027818882.982376@yasure> Quoth bokr at oz.net (Bengt Richter): ... | I like this, but I think I would rather see timely finalization | subsumed under a general event-handling mechanism for objects. Thus | ref count going to zero would be a standard event that you could | write a handler for. A rack of event handlers might be specified | much like __slots__, except a list of tuples instead of names, | (could use a dict, but might want to specify piority order to | put likely events first) e.g., (using a fictional container for | standard platform event, perhaps extendable a la sys.modules): | | class Foo: | __events__ = [(sys.events.ON_ZERO_REFCOUNT, myFinalize)} | ... | def myFinalize(self, event, *rest): | self.f.close() This function could also say "no", if you wanted to give the object the option to survive zero refcount. Donn Cave, donn at drizzle.com From jeremy at alum.mit.edu Fri Jul 12 08:59:28 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: Fri, 12 Jul 2002 08:59:28 -0400 Subject: compiler package In-Reply-To: <021401c228f8$9bf5c190$e000a8c0@thomasnotebook> References: <021401c228f8$9bf5c190$e000a8c0@thomasnotebook> Message-ID: <15662.53936.141617.325061@slothrop.zope.com> >> Has anyone used the compiler package to compile Python source >> code to other languages? Is there anything to get started? >> >> Thomas I haven't and the package doesn't provide anything other than some front-end tools. The primary focus of the package is to provide a pure Python bytecode compiler. The AST it uses would certainly be helpful for other projects. It's possible, also, that it's IR would be useful for high-level analysis. (The IR is almost identical to bytecode, which is itself somewhat abstract.) Jeremy From whisper at oz.net Sat Jul 6 02:14:35 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 5 Jul 2002 23:14:35 -0700 Subject: Why self? In-Reply-To: Message-ID: What do you know - another programmer whose first encounter with a computer didn't involve killing 4,000 aliens from the planet "Mongo"! Well said! Now if someone would just stand up and call eXtreme Programming the EXtreme BS that it is! :P BTW, Charles Semeyonie (sp?) who originated "hungarian" notation has repented publically. It started out as a learning aid for newbie MS programmers and grew an evil life of it's own. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Matt Gerrans > Sent: Friday, July 05, 2002 19:24 > To: python-list at python.org > Subject: Re: Why self? > > > > What I mean by the legacy part is that you have to name self in the > > list of arguments to the class methods. > > This part is redundant - but once you are inside a method, it is fine > > that you have to explicitly qualify by self when refering to class > > variables. > > I kind of like this part of the syntax, especially when using > os.path.walk() > with a walker method in a class; it is very clear what is going > on with the > "self" pointer, as opposed to the implicit pointer in C++ which can be > confusing in similar circumstances. > > > As holger points out, a frequent source of errors in C++ is that a > > method takes an argument with the same name as a class variable - > > which then hides the class variable. > > I don't agree with this argument -- a simple compiler warning solves this > problem; no need to throw out the baby with the bath water. I also don't > think it is a frequent source of errors. > > In Python, I think the required "self" reference in methods is a > case where > the solution is worse than the problem it solves. Since > indentation is the > method of scoping in Python, this addition of five characters to each > instance variable is particularly annoying -- a one-line statement that > contains several instance variables can easily become unmanageable. > > It's a bit like that horrible blight on the programming community called > "Hungarian Notation" that needlessly polutes code with incomprehensible > variable prefixes so that you know your string is really a long > pointer to a > zero terminated array of signed 8-bit characters. As if you cared, or > needed to be constantly innundated with such superfluous information. > Fortunately, the Hungarian Notation investation has for the most part been > limited to Microsoft's C and C++ APIs and thier usage, but hasn't infected > others -- and nowadays it even seems to be on the decline in Redmond (C# > examples are generally free of it). > > I never had a much of problem in C++ with distinguishing member variables > from local variables and I never liked those cheesy ("Some cheese, please, > my good man!") conventions of always using "m_" or "this->". If you keep > your methods small and clean, you don't need all this slop. > > However, since Python doesn't have declarations, some method is > required to > distinguish whether an assignment in a class's method is an > assignment to a > instance variable or a local variable. I prefer the solution of simply > making it illegal to have local variable names match class variable names. > Hmm... this doesn't help with the problem of globals, but there > is a keyword > for that. > > > When I prototype new classes, the methods often start out as > > functions, and typically I forget to add self to the argument list > > when they are promoted to methods. > > Me too! > > > -- > http://mail.python.org/mailman/listinfo/python-list From gerhard at bigfoot.de Mon Jul 22 03:53:25 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 22 Jul 2002 07:53:25 GMT Subject: Parnassus gone?? References: Message-ID: Matthias Huening wrote in comp.lang.python: > What happened to The Vaults? I just got this error: > Error 400 - Unable to resolve host name - http://www.vex.net/parnassus/. This site seems to have problems from time to time. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mfranklin1 at gatwick.westerngeco.slb.com Mon Jul 22 03:33:51 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 22 Jul 2002 07:33:51 +0000 Subject: openning links from python? In-Reply-To: References: Message-ID: <200207220637.g6M6bW705697@helios.gatwick.geco-prakla.slb.com> On Monday 22 Jul 2002 6:21 am, akhar wrote: > is it possible to have a url load inside the OSes preferred browser? Not sure what you want, you could try the webbrowser module. From aleax at aleax.it Wed Jul 24 04:16:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:16:10 GMT Subject: Make me beautiful (code needs help) References: Message-ID: Emile van Sebille wrote: > Mark >> Ok, I have the following data: >> >> data["A"] = [1,2,4,10,50] >> >> and I want to get: >> >> data["new"] = [?, 1, 2, 6, 40] > > >>>> A = [1,2,4,10,50] >>>> ['?']+[a-b for b,a in zip(A,A[1:])] > ['?', 1, 2, 6, 40] Fine (and most elegant) for relatively small sequences, where you don't mind zipping the sequence with a shifted copy of itself. Otherwise, the normal way to do it is the less-elegant: ['?'] + [ A[i+1]-A[i] for i in range(len(A)-1) ] Alex From whisper at oz.net Mon Jul 22 15:16:16 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 22 Jul 2002 12:16:16 -0700 Subject: Command history (up arrow) in IDLE on Windows 2000 In-Reply-To: <8d3e714e.0207212143.3b692496@posting.google.com> Message-ID: >From the .8 Idle online help: Alt-p retrieves previous command matching what you have typed Alt-n retrieves next Return while on any previous command retrieves that command Alt-/ (Expand word) is also useful here David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Tony C > Sent: Sunday, July 21, 2002 22:43 > To: python-list at python.org > Subject: Command history (up arrow) in IDLE on Windows 2000 > > > Is it possible to enable command history in IDLE ? > I'm using version .8 on Windows 2000. It's really irritating not to > have command history, like in BASH or Cshell. > > thanks > Tony > > cappy2112 at yahoo.com > -- > http://mail.python.org/mailman/listinfo/python-list From news-and-lists at the-me.de Fri Jul 26 13:32:39 2002 From: news-and-lists at the-me.de (Axel Bock) Date: Fri, 26 Jul 2002 19:32:39 +0200 Subject: python class question References: Message-ID: On Fri, 26 Jul 2002 09:53:09 +0200, Jonathan Hogg wrote: > On 25/7/2002 19:38, in article Xns9256D2197BD87cliechtigmxnet at 62.2.16.82, > "Chris Liechti" wrote: > > Because that won't work. Look again at the code above. It gets an > attribute of self with the *name* stored in 'connection'. I don't know > where 'connection' comes from here. The code that you've shown us Axel > would never have worked, so I'm guessing it is the result of playing with > the original code. > > I'm guessing it should have read something along the lines of: > > dbc = getattr( self, self.connection ) yeah, sorry, this is like it looks. I forgot the "self". >>> Now I tried to modify the last line as follows: >>> self.DB = dbc() >>> and getting a very strange error (Error Type: UnpickleableError Error >>> Value: Cannot pickle objects). >> >> don't know Zope but it look like that it uses pickle to store your >> instaces and the DB object cannot be picked. thats probably because the >> connection to a database cannot be stored, it must be terminated and >> rebuild, but thats doesn't seem to be supported by the db object. But what am I trying to do? I try to assign the reference to a new object to a member variable - so why does this not work?? > No, I'd say (as above) that 'self.connection' is a string, which means > that 'self' has a method (or instance variable that refers to a class?) > called 'MySQL_database_connection'. See what > 'self.MySQL_database_connection' is. This is an instance of "Connection". But why can "dbc()" deliver an instance of "DB" ??? (DB is a class, I checked) > Then perhaps you should just do the same in the member functions, i.e., > call the machinery that creates a database connection. You could always > wrap it in a method that returns a database connection. I can always ... how? ;-)) Thanks a lot, Axel. From Christopher.Cox at honeywell.com Tue Jul 30 14:12:25 2002 From: Christopher.Cox at honeywell.com (Chris) Date: 30 Jul 2002 11:12:25 -0700 Subject: Win32api,sleep() oddity Message-ID: <13bf971.0207301012.3af0d16@posting.google.com> I use Python embedded in a testing utility on Windows NT4. We recently switched PCs to a faster system because of the volume and intensity of the tests we were running. The old system was a PIII-550MHz system and the new is a PIV-1.5GHz system. We've noticed that when calling the following funtction: def wait(Seconds): loop = Seconds * 50 for i in range (0,loop): win32api.Sleep(20) if win32ui.PumpWaitingMessages(0,-1): win32api.PostQuitMessage() raise exceptions.SystemExit on the PIV system, the actual wait is 50% longer than we had requested (a 10 second wait actually waits 15.55 seconds, 100 seconds waits 155.5 seconds). IS there some implementation detail in win32api that might cause this error to arise? Any help would be appreciated. Chris From nospam at dsl.pipex.com Wed Jul 3 19:58:56 2002 From: nospam at dsl.pipex.com (Simon Foster) Date: Wed, 03 Jul 2002 23:58:56 GMT Subject: Efficient python programming... References: <3D00A456.4315EDA3@engcorp.com> Message-ID: <3d238f6b.579164824@news.dsl.pipex.com> On Fri, 7 Jun 2002 21:03:08 +0100, "James Kew" wrote: >"Peter Hansen" wrote in message >news:3D00A456.4315EDA3 at engcorp.com... >> Eddie Corns wrote: >> > >> > A friend is fond of quoting this to me: >> > >> > Rules of Optimization: >> > Rule 1: Don't do it. >> > Rule 2 (for experts only): Don't do it yet. >> > -- M.A. Jackson >> > >> You forgot the even more important first thing for a beginner: >> get it correct! > >I favour Kent Beck's aphorism: "Make it work, make it right, make it fast." > >James > > > I prefer this one: "You can have it right" "You can have it cheap" "You can have it now" Pick any two. From stefan.heimann at web.de Mon Jul 29 10:10:44 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 29 Jul 2002 14:10:44 GMT Subject: TAB completion References: Message-ID: Dave Cinege wrote:: > On Monday 29 July 2002 5:11, Stefan Heimann wrote: >> Dave Cinege wrote:: >> > On Sunday 28 July 2002 6:19, Stefan Heimann wrote: >> >> Hi! >> >> >> >> I have a application with a builtin interactive shell. I use the >> >> readline module for command completion and history browsing. The >> >> following code enables filename completion: >> > >> > Is your work based on the cmd module? >> >> No it is not. I have looked at the cmd module, but its completion >> function does not contain filename completion. > > Not true. Please see > http://mail.python.org/pipermail/python-list/2002-July/thread.html#114824 > http://mail.python.org/pipermail/python-list/2002-July/114824.html Ah, ok thanks! I am developing with python 2.1 and this feature of the cmd class is not available in that version. Is it corrrect, that readline's default filename completion is applied when the function set with set_completer(completionFun) returns `None'? That seems to be the point I did not understand. Thanks for helping! Bye Stefan From stephen.boulet at motorola.com Mon Jul 29 14:28:26 2002 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Mon, 29 Jul 2002 13:28:26 -0500 Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> Message-ID: <3D45894A.2090406@motorola.com> What if you wanted to do things like make a tabbed spreadsheet (tabs on the bottom that break up a notebook int subparts, not '\t'), is this possible with csv format? Chris Liechti wrote: > keilj_33 at yahoo.com (Jeffrey Keil) wrote in > news:67f6bbe5.0207270544.696f6076 at posting.google.com: > > >>Greetings: >> >>I'd like to have a Python script open a text file, process the data in >>the text file and then write a report to an Excel file. I'm not sure >>how I would write to an Excel file from a Python script. Is there any >>books that would give me details on doing this? > > > you could use COM. but i think its simpler to write the output to a text > file again. use tabs to separate columns and name it .csv - excel will > autodetect the format and load it correctly. > > chris From aleax at aleax.it Sun Jul 21 05:10:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Jul 2002 09:10:47 GMT Subject: can i make a p2p application in python? References: Message-ID: eugene kim wrote: > like kazaa or napster.. > > is it possible? Of course it is -- why wouldn't it be? For example, The Circle is written in Python, see http://www.csse.monash.edu.au/~pfh/circle/ , and quite an ambitious peer-to-peer system it is. Alex From kdart at kdart.com Wed Jul 31 07:43:51 2002 From: kdart at kdart.com (Keith Dart) Date: Wed, 31 Jul 2002 11:43:51 GMT Subject: Simple HTML classes References: <47ptjushoni8bfqurttm86sgt8bm6tge84@4ax.com> Message-ID: In article <47ptjushoni8bfqurttm86sgt8bm6tge84 at 4ax.com>, "Dale Strickland-Clark" penned these words: > We need a bunch of light-weight HTML classes to build web pages - > especially forms. These will work with the CGI module so that the forms > related classes are bi-directional. > > Before we start writing them them, I was wondering if anyone had done > anything similar or there was a module I'd overlooked. > > I can't believe this hasn't been tackled before. > > Thanks > -- > Dale Strickland-Clark > Riverhall Systems Ltd The pyNMS package has an HTML package (sub-package) that allows generating HTML from Python objects. Actually, it is XHTML 4.1. This uses my Python Object Model (POM) for XML file creation, parsing, and manipulation that is similar in concept to DOM. Actually, you can construct any XML document with that, and the HTML package is just a subset of that (uses the "compiled" XHTML DTDs). Should you ever need to update to a newer version of XHTML, just run the dtd2py program on the new DTD file. You instantly get all newly defined elements and attributes. http://pynms.sourceforge.net/ download the release, and look at the lib/POM.py and lib/HTML/__init__.py files. You can construct any document using the "generic" constructor methods, or use the more convenient "helper" methods for some elements. More helper methods need to be added, however. Hope this helps, Keith -- -- ^ \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart ---------------------------------------------------------------------------- Public key ID: B08B9D2C Public key: ============================================================================ From pinard at iro.umontreal.ca Mon Jul 29 19:05:56 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 29 Jul 2002 19:05:56 -0400 Subject: PEP 1, PEP Purpose and Guidelines In-Reply-To: <15685.35726.678832.241665@anthem.wooz.org> References: <15685.35726.678832.241665@anthem.wooz.org> Message-ID: [Barry A. Warsaw] > It has been a while since I posted a copy of PEP 1 to the mailing > lists and newsgroups. Thanks for giving me this opportunity. There is a tiny detail that bothers me: > The format of the author entry should be > address at dom.ain (Random J. User) > if the email address is included, and just > Random J. User > if the address is not given. This makes me jump fifteen years behind (or so, I do not remember times), at the time of the great push so the Internet prefers: Random J. User
It is more reasonable to always give the real name, optionally followed by an email, that to consider that the real name is a mere comment for the email address. Oh, I know some hackers who praise themselves as login names or dream having positronic brains :-), but most of us are humans before anything else! Could the PEP be reformulated, at least, for leaving the choice opened? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From robin at jessikat.fsnet.co.uk Thu Jul 4 07:42:08 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 4 Jul 2002 12:42:08 +0100 Subject: replacing instance __setattr__ References: Message-ID: In article , Jonathan Hogg writes >On 4/7/2002 10:24, in article D1NxKLAkRBJ9Ew3i at jessikat.demon.co.uk, "Robin >Becker" wrote: > >> well it seems Python not as dynamic as I believed. The object is >> searched last which seems completely counter-intuitive to me, but there >> you go. > >It makes sense when you think about it. The special __*attr__ methods are >the mechanism by which one searches the instance and class dictionaries. You >can't get to the instance dictionary without going through one of these >methods first. > >When you do: > >>>> foo.bar special methods aside I find in 'Unifying types and classes in Python 2.2' http://www.python.org/2.2/descrintro.html#mro that the object is always searched last for methods which seems a bit daft and obviously different for non-method attributes. Maybe that's not true of the 2.2.1 interpreter. I had always imagined that the object dict was used before anything else in all cases. We seem to have a lot of special cases for the unwary to find punji sticks in. > >it roughly translates in the interpreter to: > >>>> type(foo).__getattr__('bar') > >The default __getattr__ method (the one in 'object') looks something like >(again, using Python pseudo-code - it's actually all C): > > def __getattr__( self, name ): > if name in self.__slots__: > index = self.__slots__.index( name ) > return contents_of_slot( self, index ) > elif has_dict(self) and name in self.__dict__: > return self.__dict__[name] > elif name in self.__class__.__dict__: > return self.__class__.__dict__[name] > else: > raise AttributeError( "... no attribute '%s'" % name ) > >The __*attr__ methods aren't actually found through the class dictionary, >they are stored in special slots in the type object and hit directly. > >The type of an object is about the only thing you can reliably query. Every >object is guaranteed to have a type. So the interpreter always asks the type >any complicated questions about an object, such as: please retrieve the >following attribute. > >[Anyone feel free to jump in and correct my rather loose explanation of the >internals.] > >Jonathan > -- Robin Becker From phr-n2002b at NOSPAMnightsong.com Wed Jul 10 19:51:41 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 10 Jul 2002 16:51:41 -0700 Subject: Python in the enterprise: Pros and cons References: Message-ID: <7xbs9fta42.fsf@ruckus.brouhaha.com> "David LeBlanc" writes: > * Lack of true multiprocessor support > > -- Heh. That's not really true either. Python is no better and no worse then > any other application program wrt to multiprocessor usage. What the author > probably was referring to here is Python's lack of multi-processor > multi-threading - i.e. true parallel computation. Know many non-specialized > languages that can or do exploit multi-processor multi-threading? There are > even OS dependencies: Win32 OS's (NT, 2k, XP) will not spread applications > across processors unless your program causes it to explicitly (this is at > least true on retail 2 processor maximum systems). Linux OTOH, does so. I thought NT could use multi-processor multi-threading. I don't see any issue about having to tell it to. If you could tell Python to use multiple processors, that would count too. > * Software performance (though benchmarks repeatedly demonstrate Python is > comparable to Java in most applications) > > -- "Python is comparable to Java" is probably a con - Python far surpasses > Java in the shortness of time spent going from "hmmm ..." to "run ...". If > you're comparing clock cycles, then you're saying an open source development > project has done what a multi-billion dollar company with 100's of > developers has done (that's a bit unfair - Python probably has more > developers (including "battery" developers) on it then does Java). Python > can and most likely will get faster and even more popular, but I'm not sure > the same can be said for Java. There are almost certainly more people writing Java stuff than Python stuff. Python wins big in development speed and development speed is important, but it's not always the only thing. Sometimes you care how fast your program runs AFTER you've written it. And native-code Java compilers like gcj completely beat the pants off Python in terms of execution speed. There are some projects like psyco which aim to narrow that gap, but they're not yet ready for prime time. > * Lack of prepackaged solutions > > -- Take a look at the Python foundry on SourceForge. Browse the > comp.lang.python.announce archives. Spend an afternoon in the Vaults of > Parnassas, Python's defacto standard repository/catalog for contributed > software. Search for "python applications" on Google or Yahoo. Try "python > " for whatever type of application you're looking for and > see what comes up. Lack of channels for promoting Python applications > doesn't mean they don't exist. Regardless of that, lots of stuff has been written in Java that's never been written in Python. Where's the Python TLS stack with certificate management? Where are the Enterprise Python Beans? Where is the JCE-like Python cryptography library with hardware service providers (answer to that one: I'm writing it but it has a ways to go)? Where's the Python ODBC interface (ans: it exists but you have to pay for it)? The list goes on, and that's just Java. > * Documentation gaps > > -- This was recently discussed on comp.lang.python. There are at least 27 > books dealing with Python or Python in specific applications. The "in the > box" documentation is ackward to use but reasonably comprehesive (tutorial > aside - the best basic introduction is the book "Learning Python" by Mark > Lutz). Yes, those are documentation gaps. You have to actually go out buy chunks of dead tree pulp in order to use this documentation, and then let it encroach heavily into your working/living space if you want to keep it around for future reference. To me, these problems greatly decreases its value of such docs. Java's online docs are far superior to Python's. There are also a lot more books about Java, but I don't care about those for the same reason I don't care about Python books. > There are at least 2 full books for Python online: DiveIntoPython and > "How To Think Like A Computer Scientist" (using Python), and many other > online resources available through Python.org. These are tutorials and neither of them attempts to be complete references. > * Absence of GUI and teamwork tools > > -- There two commercial tools for wysiwyg tkinter development, one of which > is PythonWorks from Pythonware. Do CVS and Subversion count as teamwork > tools? They do solve the source management part. MoinMoin Wiki software will > solve the team interaction part of the equation, and there are chat packages > out there, including a Jabber client for instant messaging on all the > popular IM networks. It's a product opportunity for someone to integrate all > the tools into a cohesive whole, but all the parts seem to be there... I'm not too impressed by any of those but I'm not impressed by Swing or AWT either, so it balances out. > The one thing that has come to mind from writing this as a con for Python is > the lack of channels for widespread dissemination of information about > commercial software applications, support and consulting. Python does need > better publicizing in the marketplace. Python.org provides such a focus for > information about the language, but provides little beyond a jobs board for > the marketplace. It would be nice to see a registry of products and services > that use or support Python. > > My conclusion is that Python is entirely ready for the enterprise - and it's > already there! Python is ready for some applications and getting there for others. It has a lot of virtues and to be clear about it, I like Python better than Java for most purposes. However, Python's advocates often don't acknowledge that there are still areas where Python genuinely does fall behind. We need to stay aware of Python's shortcomings so we can acknowledge them and/or fix them. From tdelaney at avaya.com Wed Jul 24 18:31:16 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 25 Jul 2002 08:31:16 +1000 Subject: how to count lines in a file ? Message-ID: > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt] > > print len(open('/etc/passwd').readlines()) There is currently discussion on python-dev of the file object possibly becoming collectable by GC (and hence not going away immediately the last reference you know about disappears). Whilst is it *extremely* unlikely that this would be allowed (due to the preponderance of broken code such as the above) it does point out that such code is indeed broken. Other people have already addressed the other problem in the above code. Tim Delaney From zopestoller at thomas-guettler.de Thu Jul 25 10:06:05 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Jul 2002 16:06:05 +0200 Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> Message-ID: <3D4005CD.4060404@thomas-guettler.de> Alex Martelli wrote: > Thomas Guettler wrote: > ... > >>>Many Python functions expect to get arguments of specific types >>>(or polymorphic to such types, i.e., supplying all necessary >>>methods and operations with equal signatures). >>> >>>Having them accept arguments of wrong types, with silent coercion, >>>would hurt all careful developers, by hiding bugs. >>> >>I agree, but than the exception should have a better message: >> > > Should it? Maybe I should have written than types supplying all > necessary methods and operations with equal signatures are OK > too. Dont't take this to serious, I just wanted to know what other people think thomas From theoryboy at my-deja.com Sun Jul 21 12:08:50 2002 From: theoryboy at my-deja.com (Peter Saffrey) Date: 21 Jul 2002 09:08:50 -0700 Subject: memory freeing Message-ID: I am writing a graph based application in Python. The application requires each node (a Python object) stores information about routes to get from one node to another. The routes are stored in a hash of lists, of which there are 2 for each node. The can_reach hash has reachable node names (strings) as keys, and lists of lists of transitions (also strings) as values. The reachable_from hash is the same structure but stores routes to the storing node, rather than originating from it. The values are lists of lists, because I need to store several alternative routes between the nodes for efficient searching through the graph. For example, a node s0 may have a can_reach hash that looks like this: {'s1': [['t0','t1'],['t3','t4']], 's2': [['t4','t5','t6']]} indicating that s0 can reach s1 by routes ['t0','t1'] or ['t3','t4']. s0 can reach s2 by route ['t4','t5','t6']. This could equally be a reachable_from hash, indicating that s0 can be reached from s1 by routes ['t0','t1'] or ['t3','t4'] and s0 can be reached from s2 by route ['t4','t5','t6']. I realise the reachable_from hash is repetition, but I need it to generate the can_reach hashes. I have found, perhaps not surprisingly, that in large graphs these hashes grow very large. Since I only need the reachable_from hashes for can_reach generation, I was going to delete all reachable_from hashes once I had the can_reach routes I need. I set up a loop to assign "None" values into all the reachable_from hashes, but the memory displayed by my system monitor (gkrellm) does not seem to indicate that I've gained any memory. Do I need to do anything more specific to order Python to return this memory to me? Obviously many of the routes have shared parts, but I use the concatenate (+) operator when building the lists, and I thought this generated new list copies. Apart from anything else, each hash and the pointers to the lists of lists should be separate objects, and just removing these ought to give me a few megabytes, but I don't seem to be getting any at all. The Python website has some rather advanced advice on homemade reference management, which does not seem to suit my needs. Any ideas? Regards, Peter Saffrey -- PhD student Computing Science Department University of Glasgow From pecora at anvil.nrl.navy.mil Tue Jul 9 15:58:26 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 15:58:26 -0400 Subject: Why self? References: <090720020820257031%pecora@anvil.nrl.navy.mil> <090720021359063518%pecora@anvil.nrl.navy.mil> Message-ID: <090720021558267277%pecora@anvil.nrl.navy.mil> In article , Andrew Koenig wrote: > Louis> def __init__(self): > Louis> name=None > > But that's extra code. I thought the whole point was to get rid of > extra code, not move it around. Getting rid of distracting code was my motive. I always try to initialize object variables. That helps me when I look over an object and I thought that was good practice. Hence, it adds no code for me. > > What about someone who wants to write several classes with methods > that behave exactly the same way? Doesn't it make sense to write that > code once, and then install references to it in each of those classes? I would answer: use inheritance. > What about code that wants to build up objects with particular > properties by installing methods dynamically in those objects > according to the requested specifications? Oh, I see adding functionality on the fly. Interesting idea. Is that really undoable with my suggestion? My mind is hitting a wall trying to see that, sorry. > Because requiring "self" has some advantages, as well as the disadvantages > that you and others have mentioned, it's a matter of opinion as to whether > a solution to the problem would create other problems. For that reason, > I'm not inclined to go looking for a detailed solution--especially as > any solution would have to avoid breaking existing code. ^^^^^^^^^^^^^^^^^^^^^^ Yeah, that's true. Sigh. Looks like I live with self. Now that sounds deeply Jungian or something. Thanks for the feedback. -- Lou Pecora - My views are my own. From fredrik at pythonware.com Sun Jul 28 11:02:16 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 28 Jul 2002 15:02:16 GMT Subject: How to detect the last element in a for loop References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: Tom Verbeure wrote: > > For a simple solution, how about: > > > > for a in myList[:-1]: > > do_stuff(a) > > special_stuff(myList[-1]) > > No, I still want to do 'do_stuff' for the last element also. This may be, > say, 10 lines of code. Too much to duplicate it outside the loop, not > enough for a separate function... so why not just change the for loop? for a in myList: do_stuff(a) special_stuff(myList[-1]) for extra style points, you can use the else statement to make sure the special stuff isn't done if you have to break out of the loop: for a in myList: do_stuff(a) else: special_stuff(a) > That would be the case if I would check for iterator.end(), but I check for > iterator.next().end() ! as the code in my earlier post tried to tell you, iterator.next() returns the next item from the sequence, or raises an exception. to implement your proposal, *all* objects need to implement an end method, which should return true if they are the last object in a container. since objects can be shared (the containers only hold references), and objects don't know or care about what containers they are in today, that's pretty much means that we have to start over from scratch... From mcherm at destiny.com Wed Jul 10 10:47:07 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 10 Jul 2002 10:47:07 -0400 Subject: j2ee vs. python (and what our evil competitors are saying about python) Message-ID: <3D2C48EB.3060301@destiny.com> curt finch writes: > Our rebuttal (based on some of your comments) is here: > > http://www.journyx.com/pdf/PythonAtAGlance.pdf Great job, actually -- that's nicely written. I'd like to echo Terry Reedy's suggestion that you (if willing) release this for general use in Python advocacy. While I'm at it, is there anyone willing to donate web and/or wiki space for Python advocacy? As far as I can tell, "Starship Python" is no longer taking new members, and I have some advocacy materials I am collecting and trying to post. I just need a place to host it (and of course lots more well-written content like curt finch's). -- Michael Chermside -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3230 bytes Desc: S/MIME Cryptographic Signature URL: From glongman at ilangua.com Tue Jul 30 10:53:38 2002 From: glongman at ilangua.com (Graeme Longman) Date: Tue, 30 Jul 2002 15:53:38 +0100 Subject: Searching for email address References: <3D46A4BD.A894DC59@ilangua.com> Message-ID: <3D46A872.55D6C3F@ilangua.com> Source code for the book ? What do you mean ? John Hunter wrote: > >>>>> "Graeme" == Graeme Longman writes: > > Graeme> In the process of translating our client's sites. Just a > Graeme> script to find all the email addresses so that the email > Graeme> addresses aren't included for translation. > > Tim Roberts wrote on this group a few days ago about a 'multi-thousand > byte full expression to match a valid RFC822 e-mail address' from > *Mastering Regular Expressions 2nd Ed.*. So you may want to check the > O'Reilly site and see if you can download the src code for the book. > > John Hunter > > -- > http://mail.python.org/mailman/listinfo/python-list From mgilfix at eecs.tufts.edu Tue Jul 30 13:21:24 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Tue, 30 Jul 2002 13:21:24 -0400 Subject: Python equivalent to 'which'? In-Reply-To: ; from shalehperry@attbi.com on Tue, Jul 30, 2002 at 10:01:23AM -0700 References: <732d35a1.0207300836.3836892e@posting.google.com> Message-ID: <20020730132124.D7503@eecs.tufts.edu> Seems like that might make a good convenience function in the os.path module. I'm sure many people have wanted such a function if they're using python for pure scripting. Perhaps you should try submitting a short patch...? Worst case, at least it'll get stored in the system. -- Mike On Tue, Jul 30 @ 10:01, Sean 'Shaleh' Perry wrote: > >>> def which(exe): > ... for d in string.split(os.getenv('PATH'), ':'): > ... name = os.path.join(d, exe) > ... if os.path.isfile(name): return name > ... return None > ... > >>> which('bash') > '/bin/bash' > >>> which('foo') > that's all 'which' does (-: -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From johann.hoechtl at myrealbox.com Sun Jul 14 14:46:31 2002 From: johann.hoechtl at myrealbox.com (=?ISO-8859-1?Q?Johann_H=F6chtl?=) Date: Sun, 14 Jul 2002 20:46:31 +0200 Subject: Python and Parrot References: <3D316CCA.90605@myrealbox.com> <7FeY8.15997$p56.5173354@newsb.telia.net> Message-ID: <3D31C707.9020706@myrealbox.com> I'm not advocating it, I only stumbled over http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/nondist/sandbox/parrot/ and was wondering why work stopped as the papers of parrot look promising. By mentioning Allos, HarrixOS ... you mean that Perl people make a good job at advertising sthg. which will never take off ? And yes, I guess i was browsing to quickly over the article ! Fredrik Lundh wrote: > Johann H?chtl wrote: > > >>Recent progress has been very fast and according to >> >>http://use.perl.org/articles/02/07/03/2241212.shtml >> >>the progress of parrots implementation is even likely to speed up. > > > didn't that article basically say "we're out of money, and will no > longer work full time" rather than "the progress is likely to speed > up"? > > (and why is it that the Parrot advocacy reminds me of stuff like > Freedows and Allos, not to mention HarrixOS... ;-) > > > > From shagshag13 at yahoo.fr Tue Jul 23 13:27:39 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 23 Jul 2002 19:27:39 +0200 Subject: how to count lines in a file ? References: Message-ID: here is a test in counting [6871785] lines from a file of > 1Go --- the code i post [Eof processing] : 00:01:13 --- the code i post without "wc popen" lines [Eof processing] : 00:01:09 --- lineCount = 0 fhi = file(filename) for line in xreadlines.xreadlines(fhi): lineCount += 1 return lineCount [Eof processing] : 00:01:22 --- lines = 0: for line in file(filename): lines += 1 [Eof processing] : 00:01:22 --- lineCount = 0 fp = open(filename) it = iter(fp) try: while it.next(): lineCount += 1 except StopIteration: pass return lineCount [Eof processing] : 00:01:42 ************ all comments are welcome !!! thanks, s13. From fredrik at pythonware.com Thu Jul 18 11:27:15 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Jul 2002 15:27:15 GMT Subject: smtplib and passwd's References: Message-ID: Rajarshi Guha wrote: > I'm using smtplib to let my script send some mail through my smtp > server. Howveer I need a logon and passwd for my smtp server - how does > smtplib handle such servers? Where can I specify my username and > password? did you look in the fine manual? http://www.python.org/doc/current/lib/SMTP-objects.html login(user, password) Log in on an SMTP server that requires authentication. The arguments are the username and the password to authenticate with. From oliver.smith at removethisbit.baesystems.com Tue Jul 16 04:00:52 2002 From: oliver.smith at removethisbit.baesystems.com (Olly Smith) Date: Tue, 16 Jul 2002 09:00:52 +0100 Subject: HTTP_USER_AGENT Parsing References: Message-ID: <3d33d24d$1@pull.gecm.com> wrote in message news:mailman.1026755722.21116.python-list at python.org... > On Mon, 15 Jul 2002, Olly Smith wrote: > > > I'm a bit of a newbie to Python, and in my quest to generate nice HTML > > content, I need a way to work out what browsers clients are using from their > > HTTP_USER_AGENT strings. > > > > Any pointers? > > - Googling for lists of User Agent strings will give you sample Javascript > to determine client platform and browser based on user agent value - this > is pretty easy to port to Python. > > - The same Google search will turn up lists of known user agent strings, > which will be useful for your test code. > > - User agent strings are not 100% reliable, but few people change them, so > they are fairly accurate (you can generally even detect browsers like > Opera, even when they are reporting themselves as IE). > > - Also check the HTTP spec, as it list the official format of user agent > strings. It's basically a list of names, each followed by an optional > version number and an optional list of additional info. On the end of the > line can be an optional language code too, I think, e.g. "[en]". > > - For most people it's not worth the effort to invest too much time doing > browser-specific HTML. ;-) > Ta, I'll check that out. This bit of code I'm working on has to produce a 'nice' interface, but part of the spec says it must work with NS4 correctly .. and we all know NS4 is a PITA ;) Olly From info at ciquery.com Sat Jul 13 13:44:36 2002 From: info at ciquery.com (www.ciquery.com) Date: Sat, 13 Jul 2002 17:44:36 +0000 (UTC) Subject: python - asp Message-ID: Does anybody know if the download of python 2.2 from www.python.org for Windows includes the ActiveX Scripting Engine . I need to build some ASP pages that run Python on the server side. ________________________________ Enhance your mind at www.ciquery.com From aahz at pythoncraft.com Wed Jul 3 12:48:08 2002 From: aahz at pythoncraft.com (Aahz) Date: 3 Jul 2002 12:48:08 -0400 Subject: Thread safetyness in Python References: Message-ID: In article , John Goerzen wrote: > >I have some questions about what is thread-safe in Python. Can someone tell >me whether each of the following are thread-safe: > >1. a = a + 1 >2. a = a + 2 Depends on what "a" is. If it's a function/method local, it's guaranteed thread-safe (assuming no pathological poking into code objects). Generally speaking, worrying about thread-safety of objects is the wrong tack to take with Python. What you want to do is make sure that only one thread has access to any given object, usually by passing references to the object around with Queue.Queue. >3. If this is not thread-safe and two threads try to do it simultaneously, >it might be the case that each thread adds a new list[5] instead of one >adding list[5] and the other list[6]. This is thread-safe. Anything with only one bytecode is thread-safe. You can use the dis module if you want to check it out. The problem comes when you use list.append(f()).... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jepler at unpythonic.net Thu Jul 18 10:59:07 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 18 Jul 2002 09:59:07 -0500 Subject: property problem In-Reply-To: <3D36C65A.5040300@mplusr.de> References: <3D36C65A.5040300@mplusr.de> Message-ID: <20020718145907.GA6794@unpythonic.net> Properties only work properly when you subclass object. They don't work properly on old-style classes. Jeff From shagshag13 at yahoo.fr Thu Jul 25 10:08:04 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 25 Jul 2002 16:08:04 +0200 Subject: how to get a return value from an exception ? Message-ID: hello, i need to raise an exception which "carry" some data... i think that it's something like : class MyException(Exception): def __init__(self, *args): Exception.__init__(self, args) >>> raise MyException('one', 2, 'three') Traceback (most recent call last): File "", line 1, in ? raise MyException('one', 2, 'three') MyException: ('one', 2, 'three') but them how to access to 'one', 2, and 'three' ? it's ok if i do it like in "dive in python" >>> class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return `self.value` but here what does the `` stand for ? thanks, s13. From weirdron at b0ne.net Wed Jul 10 05:06:05 2002 From: weirdron at b0ne.net (Weirdron) Date: Wed, 10 Jul 2002 09:06:05 GMT Subject: Python, COM and MatLabs Safearray Message-ID: <1OSW8.205616$IR.3395800@news.chello.at> I'd like to use the COM Interface of MatLab and the functions to transfer matrices use the following datatype: Pointer SafeArray Real 8 (Flags = 3) How do I create this datatype with Python? Any help is greatly appreciated. Thanks, Ron From opengeometry at NOSPAM.yahoo.ca Tue Jul 23 15:07:15 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 23 Jul 2002 19:07:15 GMT Subject: how to count lines in a file ? References: Message-ID: Shagshag13 wrote: > hello, > > i need to count lines in a file (that i *can't* keep in memory, so can't use readlines()) > by now i use this : > --- > import os > > BUFFER_SIZE = 10000 > > def lineCount(filename, bufferSize = BUFFER_SIZE): > > do = 'wc ' + filename > p = os.popen(do, 'r') > line = p.read() > p.close() > > if line: > return long(line.strip().split()[0]) > else: > lineCount = 0 > fhi = file(filename) > while 1: > lines = fhi.readlines(bufferSize) > if not lines: > break > > lineCount += len(lines) > return lineCount > --- > is it the correct ? do you think i can tweak it ? > > thanks in advance, > > s13. If you are on Unix, then just use wc -l filename with any of function in 'os' module. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From eddie at holyrood.ed.ac.uk Fri Jul 12 10:40:43 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 12 Jul 2002 14:40:43 +0000 (UTC) Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: Just adding my tuppence worth. Remember that whitespace can be added horizontally too eg. for line in xreadlines.xreadlines(sys.stdin): if line[0] == '#' : continue elif line[:5] == 'DATE:' : yield ('DATE', scan_date (line)) elif line[:5] == 'INTF:' : yield ('INTF', scan_intf (line)) elif line[:4] == 'ETH:' : continue # for now elif line[:4] == ' ' : continue else : yield ('DATA', scan_data (line)) Basically, when you layout code you need to think about how to convey to the reader what's going on. In constructions like the above I believe it's much easier to see that it's only ever looking at the beginning of the line and the table like structure makes it easy to map what it finds to what gets done. (this code was extracted from a quick one-off so I'm not interested in comments about how good it is!). I used align.el, which I discovered recently to do the work, it does blocks of assignments very easily, other things take a little work. I also occasionally collapse single if statements if I feel they are less important to the flow. Eddie From tjreedy at udel.edu Sat Jul 27 16:45:30 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Jul 2002 20:45:30 GMT Subject: How to detect the last element in a for loop References: Message-ID: "Tom Verbeure" wrote in message news:shD09.10086$9U4.6939 at nwrddc01.gnilink.net... > > Hello All, > > I often have the case where I need to loop through a bunch of elements, but > do something special on for the last line of code. > first = 1 > for port in self.portDefsList: > if first == 0: > string += ", " > else: > first = 0 > string += str(port) > pass You actually special case the first item. However, you really want the string join method: result = ', '.join(map(str, self.portDefsList)) Terry J. Reedy From erict at millfilm.co.uk Fri Jul 19 10:51:30 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Fri, 19 Jul 2002 15:51:30 +0100 Subject: xmlrpclib oddness Message-ID: <3D382772.128F0930@millfilm.co.uk> The only diff between the 2 following scripts are the test on the return value of getConnection() which basically open a xmlrpclib.ServerProxy Any idea ?? Thanks Eric # dd is a dictionnary server = self.getConnection() if server != None: server.SendTask(dd) DUMPS: File "/usr/people/erict/bin//lib/python2.2/xmlrpclib.py", line 763, in dumps data = m.dumps(params) File "/usr/people/erict/bin//lib/python2.2/xmlrpclib.py", line 454, in dumps self.__dump(v) File "/usr/people/erict/bin//lib/python2.2/xmlrpclib.py", line 465, in __dump raise TypeError, "cannot marshal %s objects" % type(value) TypeError: cannot marshal objects Where the following work fine: server = self.getConnection() server.SendTask(dd) From jb at hotmail.com Wed Jul 24 07:31:16 2002 From: jb at hotmail.com (JB) Date: Wed, 24 Jul 2002 13:31:16 +0200 Subject: GUI toolkits References: Message-ID: <3d3e8e2e_4@news.newsgroups.com> Stefano Vedovelli wrote: > Hello all > > in my spare time I am writing a tool in python, with the > intention of deliver it under GPL. > > I am now starting to approach the GUI part. I have read a > lot about Tkinter, PyQT and wxWindows, but I am now > actually even more confused. > > As the interface will be "quite" rich, I'd like to know > the opinions of people who already faced this decision, > which tool they have chosen and why. I have chosen PyQt, as Qt is itself excellent and PyQt is excellent as well. In my opinion Qt is superior to Tk, though you may get problems if you your OS is Ms-Windows. Tkinter is a nice product but suffers somewhat from the limitations of Tk. You may want to need the Tk megawidgets, that is a set of additional widgets for Tkinter, but I had problems with it. Then you may study pygtk. Gtk+ is excellent as well but I had problems with pygtk. -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From emile at fenx.com Tue Jul 2 06:54:40 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Jul 2002 10:54:40 GMT Subject: Python language dedicated Wiki References: Message-ID: > What does mean Wiki; no acronym found. http://www.wiki.org -- Emile van Sebille emile at fenx.com --------- From sjmachin at lexicon.net Mon Jul 8 19:00:20 2002 From: sjmachin at lexicon.net (John Machin) Date: 8 Jul 2002 16:00:20 -0700 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: Tim Peters wrote in message news:... > The rest is history, and "surrogates" are a hack to get the effect of 4 more > bits (way more than enough to last us forever 10 times over). In > pre-Unicode-speak, you'd call them "escape codes". 4 more bits? It needs 21 bits to encode the 2**20 possible surrogate-described characters plus the basic 64K characters. assert 21 - 16 == 5 From maxm at mxm.dk Fri Jul 19 02:51:14 2002 From: maxm at mxm.dk (Max M) Date: Fri, 19 Jul 2002 08:51:14 +0200 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <3D374109.1040202@mxm.dk> <3D3743A1.911F9687@alcyone.com> Message-ID: <3D37B6E2.1010403@mxm.dk> Erik Max Francis wrote: > Max M wrote: >>I don't especially like "self" myself. But wouldn't it be easy enough >>to >>just: > An obvious issue is what happens with respect to bound and unbound > methods. The self argument is often implicit in normal work, but it > _is_ there, and needs to be set up properly. In your scheme, what > happens when you write: Arh bugger. I don't disagree, and I made the typical typo that I often do when creating classes. I forgot to add self as the prameter. So my example should have looked like: class ProjectScheduler: pi = 3.14 def setEstimatedTime(self, hours): self.estimatedTime = hours def calculateRealisticTime(self, estimatedTime): # rebinding vars to make the calculation easier on the eye pi = self.pi estimatedTime = self.estimatedTime # the formula realisticTime = estimatedTime * pi # return result return realisticTime /me slapping himself on forehead repeatedly regards Max M From huaiyu at gauss.almadan.ibm.com Mon Jul 29 14:32:37 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 29 Jul 2002 18:32:37 +0000 (UTC) Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> Message-ID: Tim Gahnstr?m /Bladerman wrote: > >"Terry Reedy" >> > Things I want to change is for example, everything should be "call >> > refferense", >> >> It already is, which is why functions can mutate mutable objects. >> (This surprises some beginners.) Of course, for immutables (numbers, >> strings, tuples), there is no semantic difference between reference >> and value passing except for reduced memory usage. > >I want to make all variables mutable. When you want to make functions like >inc(x) where inc is supposed to increase the value of x by one. How is that >done in Python? >That is my view of CBR, maybe that is not the correct definition and I don't >need CBR. It's not a matter of how you can do it, but what you really want to do. Consider this: x = y = 3 # (1) inc(x) # (2) x == 3 and y == 3 # (3) x == 4 and y == 3 # (4) x == 4 and y == 4 # (5) Let's see what constraints you have for the semantics of inc. - After (1), both x and y are references to an object named 3. - Whatever you want your new language to be, you do not want the object named 3 to actually have a value of 4. So you do not want to change the object referenced by x. - You can change the name x so that it now points to the object named 4. You can keep the change in the function inc, so that (3) is true (as Python currently does), or let it affect the calling scope, so that (4) is true (as you might want to do). Either way (5) is false because y is a separate name. - To make (5) true, there must be a commont "sign post" to which both x and y can refer to, and which can be changed from pointing to the object named 3 to the object named 4. This would be just a mutable int. It can be implemented in existing Python similar to UserDict and UserList. You would need change (1) to x = y = UserInt(3) to use it. Keep in mind that you do not want the object named 3 itself to be mutable. Otherwise you are in for a big surprise next time you do z = 3. I guess what you want is (4), ie to make inc(x) change the reference of x in the calling scope. In other words, you want to make the formal arguments of a function an alias of the actual arguments. In that case these arguments are really in a "tunneled" scope, accessible from both sides of a function call. It would behave very differently from existing Python. For example: def remove(x): del x s = 3 remove(s) s # NameError: name 's' is not defined It might even be more powerful than Python in the sense that many statements and syntax structures can be replaced by functions. Since functions are first class objects you can manipulate them in program, thereby construct program structures without using eval. This has a Lisp feeling. If you decide that this is indeed what you want to do, other people might give you some idea on how easy/difficult it is and where to start. Huaiyu From domingo at visual-tools.com Mon Jul 1 10:03:13 2002 From: domingo at visual-tools.com (Domingo =?iso-8859-1?Q?L=F3pez=20L=F3pez?=) Date: Mon, 01 Jul 2002 16:03:13 +0200 Subject: Problems with Python CGI under Windows Message-ID: <3D206121.7ADCD55F@visual-tools.com> Hello everybody. This is the first time I am writting to this list. I am trying to read -from the standard input- a binary (JPEG) file in a Windows web server with a CGI. The problem is that python does not seem to support binary reading from standard input, because the reading stops when a 0x1A character (CTRL-Z) end of file arrives. Would it be possible to make a whole reading from the stdin of the JPEG file? (with a C CGI I have achieved it) A few lines of my CGI: [...] contentLength = os.environ[CONTENT_LENGTH] x = open('myfile.jpg', 'wb') x.write(os.read(sys.stdin.fileno(), contentLength)) x.close() [...] Some help would be appreciated. Thanks a lot in advance. Domingo L?pez. From paul at boddie.net Tue Jul 2 06:46:43 2002 From: paul at boddie.net (Paul Boddie) Date: 2 Jul 2002 03:46:43 -0700 Subject: Web templating/db tool with best designer/coder separation? References: <3d21259f$0$28006$afc38c87@news.optusnet.com.au> Message-ID: <23891c90.0207020246.793146a1@posting.google.com> Stephen Tyler wrote in message news:<3d21259f$0$28006$afc38c87 at news.optusnet.com.au>... > Bengt Richter wrote: > > > E.g., if you were hoping for an improvement over current practice, > > which do you consider to be the tool(s) to beat, and what would > > the killer improvement(s) be? TIA. > > Well, there are more parties involved than just designer and coder. What > about content providers (authors, illustrators), database administrators > and management (project managers etc). They also play an important role, > and their productivity is affected by the choice of web templating/db > tools. Indeed. But the involvement of many different parties is, in my view, a strong argument for simplified template systems which can be "round-trip" edited in WYSIWYG HTML editors, for example. My justification for this is that otherwise a larger workload may be placed on the person who has to integrate design changes into the system. [Python-HTML-other triangle] > And most of the web templating solutions trend towards either defining a new > programming language, or a way to embed Python in HTML. > > > But, as the new programming language becomes more expressive, it tends to > become yet-another-PHP, and becomes yet another thing to mystify the > non-coders, and another way to write obfuscated code for the coders. That's why there's a strong argument for implementing template systems which are not programming languages - wholly declarative template notations, for example. Whilst such notations cannot express complicated dynamic layout, one can always use a layered approach: one layer builds the forms, another does the fancy colouring, etc. > Code should be written in an efficient code for coding (eg Python). And > likewise for the other elements (but I will stop short of saying that HTML > is an efficient code for markup). No, but HTML is a standard on the Web... > In my view, the next generation of web templating/db tool needs to move > beyond the issue of python/HTML separation and start solving some higher > level issues: > > - Reuse (both of code, markup and content) The biggest challenge in terms of code reuse is arguably where validation of data is performed. One problem with markup reuse (as typically implemented in template systems) is the lack of support for "includes" in various editing tools, as far as I am aware. Thus, previewing of templates is fairly impaired in many tools, although I'm sure that some of them are starting to deal with this. > - Authorisation and security The standard authentication mechanism in J2EE, for example, is interesting because the process of authentication is transparent to the application - it is the application server which prompts the user for their details, even using a Web page. An authorisation scheme can be more complicated to design unless it is deliberately kept simple. > - Higher level structures (forms, tables, lists, trees, navigation should be > handled and manipulated at an abstract level, rather than as a mess of HTML > markup) I agree with you on the issue of forms, in the sense that form fields should be consistent with the underlying schema, but tables, lists and trees all reduce to the same general case. The big question is: how do you allow someone to edit these objects using a tool giving a more sophisticated representation than a text editor (or uninspired XML tree editor)? > - Consistency and style (the "style" of the site should be able to be > changed across an entire site by making small changes to a small number of > items in a small number of places - and my definition of style is much > broader than just CSS) Again, this would be great if one could retain a WYSIWYG HTML editor. > - Configuration management (Can we revert to the previous version if the > change is not working properly? Can we test the new version on particular > users (or classes or users) before fully commiting to the new version? Can > we track changes to the system?) Well, it would be nice to hear the best practices in this area - how to develop, test and deploy Web applications using CVS, perhaps. > Just take the example of form handling: > > You have certains fields in certain tables in your database. And you want > the user to be able to change those fields. This is a pretty simple > requirement, yet the solution in most web templating systems is pretty > complex: In that you often need to build the form fields manually, and don't have many possibilities for automatic verification/synchronisation of those fields against the database? [Access, validation] > - how do we notify the user of errors in user input? This is something that a general mechanism can be very helpful with. Manually coding error checking in both the Python code and the template can be extremely tedious. > - how do we notify the user of errors in authorisation? > > - how do we notify the web administrator of errors? Indeed. It's dubious to say that "we log all errors" - who actually reads the log unless the whole system is down? > - how do we label these fields? If the label needs to be changed or > localised, where do we make those changes? With different templates? Let's say you have a US site and a British site: "Not many spelling differences there," one may think, until one realises that the very nature of the user interface could be different - different information, legal terms, presentation style, and so on, could all apply. > - how do we access these fields? Do we have to write an SQL query for this > (and every other) data access? Or can the templating system generate the > appropriate efficient SQL query? I personally wouldn't look to a templating system to generate SQL queries - that's why we have multi-layered architectures, in my opinion. > - How do we save the results back to the database? How do we cope with > results spread across different tables? Can the templating system generate > the appropriate efficient SQL query? What about transactions? Again, it's arguably best to introduce another layer. > Now in my view, all the templating systems I have seen turn this "simple" > exercise into a fairly complex code. And 99% of the time, the > implementations of this code ignore several important steps in the process. > And 99% of the time, the code has to be reimplemented for every new form > that is required. I'll agree with this assessment in principle. I'll also claim that complicated forms can be a nightmare to implement without specific assistance from the Web development framework in the areas of validation and presentation/templating. [...] > The other contenders for my "next-generation" web templating system > typically use XSLT to transform a variety of XML inputs into XHTML output. > But XSLT can be very obtuse for non-coders (and even coders). And it still > needs to be supplemented with a general-purpose programming language. XSLT is (arguably) not easily previewed - at least not in the sense that one can take an XSL document on its own and say that the final output "will look something like this". In contrast Zope Page Templates is designed to make sense in its "uninstantiated" state. > For my own code, I have developed a number of libraries over the years to > solve these problems. But they have all fallen somewhat short of my goals > in one or more ways (too complex, too specific, inefficient, obtuse or > missing functionality). But I keep trying. My advice would be to not rely on a single specific technology to do everything from Web serving to database management, and to expect to combine frameworks with other projects to solve these kinds of problems. Paul From spam at ob_scure.dk Sun Jul 7 07:40:33 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 13:40:33 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D281526.6000007@ob_scure.dk> <7x1yafokef.fsf@ruckus.brouhaha.com> Message-ID: <3D2828B1.4040705@ob_scure.dk> Paul Rubin wrote: > It sounds like your applciation would speed up a lot by judiciously > adding some indices to your tables. Talk to your DBA. That's me (small company :-) Seriously I've been spending some time optimizing the DB recently, which resulted in a speedup of a factor of about 2. Most long running calls are gone now, but still there are architectual flaws in the (C++) code that cause major slowdowns. Still we'd like be able to handle >10 times the current amount of data, preferably without buying 10 times the horsepower :-). [snip - rewriting jobs] > It doesn't sound to me like you need anything like this. Reorganizing > your database may completely solve your problem. We do need to consider several modifications to our database - indices as well as new/modified tables. However the current job would need substantial modifications to take advantage of it. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From wdraxinger at darkstargames.de Wed Jul 10 10:18:55 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 10 Jul 2002 16:18:55 +0200 Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> Message-ID: <3D2C424F.5020609@darkstargames.de> Michael Hudson wrote: > Wolfgang Draxinger writes: > > >>Michael Hudson wrote: >> >> >>>To me these sentences contradict each other. So I must be missing >>>something... >> >>I want not to add a statically linkes python.lib to my linkage > > > Why not? Do you mean you don't want to use the distributed python.lib? Yeah, right. My fault, I meant the distributed python.lib. > No, you don't: far too much of the internals depends on getting things > out of the sys module. You might be able to hide things from the > scripts that you execute, but that's a different problem, surely? I see. > OK, so I think a better (read: easier) strategy might be to /hide/ > these objects, not /remove/ them. How can I do that? My initial idea was to modify bltinmodule.c to do things I want. What I definitly don't want, is to call Py_Initialize() and then replace the original modules with my own. I'd appreciate it, if it would be possible to modify the sources. > Because there are probably easier ways of acheiving what you want; > executing "engine object scripts" is a heavily custimized environment > is almost certain to be more straightforward than heavily customizing > the interpreter, and sounds to me as if it will do the job. At the moment it works, but the performance is lousy, not because Python is slow, but I had to do a lot of workarounds. Ok: To shorten the discussion: My situatuin is the following: I removed all external modules avilabe to python, so that I only have acces to the builtin's and the one's provided by the engine. Now I want to know: which modules are not really neccesary for the _interpreter_ and the interactive mode to work at all. When I want to start that reduced environment I want, that I can perform nothing very usefull. And from this situation I want to provide the environment I need. At the moment my builtins list looks like the following. I've read the doc-string. Those modules, where I think, that I don't need them at all I marked with a 'X'. Things which shouldn't be touched by the Scripts are marked with a 'T'. Things to be replaced are 'R'. Oh, another important thing: Threads are handled by the engine. All scripts should run in a single thread. So python thread support must be removed. __builtin__ _codecs _hotshot _locale _weakref array audioop X binascii T cPickle T cStringIO T cmath errno T exceptions T gc T imageop X imp T marshal T math md5 X msvcrt X new T nt X operator pcre T regex X rgbimg X rotor sha T signal T strop struct T sys R thread X time R xreadlines X xxsubtype X Hope that helps. If you need a short data flow diagram of the engine to understand why these needs are there I'll post it here. -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From peter at engcorp.com Wed Jul 31 19:33:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 31 Jul 2002 19:33:38 -0400 Subject: a soft real-time system using python References: <20020731145848.GC1800@unpythonic.net> Message-ID: <3D4873D2.93F86044@engcorp.com> anton wilson wrote: > > For further information, we're already having a certain problem where python > threads seem to drastically decrease performance in the middle of the program > for around a second. Garbage collection has been disabled, but it's possible > that there is some other behind-the-scenes work that Python is doing. What > other things should we be worrying about? I need a more complete > understanding of what can happen or is happening that would affect consistent > running of a python program. Do you want consistency or simply a high likelihood that operations will complete within some soft upper limit? The latter is soft realtime, the former is something different. By the way, I don't think you've mentioned yet which platform you are running on. If the underlying platform is not itself realtime, you might be seeing effects from it, rather than from Python itself. We certainly found lengthier pauses in our applications running under NT and (obviously) 98 than we have under Linux for similar hardware... -Peter From scrutinizer at gmx.at Sun Jul 21 07:46:21 2002 From: scrutinizer at gmx.at (Francesco S.) Date: Sun, 21 Jul 2002 11:46:21 GMT Subject: Which gui for slow (133 Mhz) pc Message-ID: <3d3b9eaa.7275472@news.utanet.at> Hello, What gui can you recommend for my slow pc (win95). I was impressed by the Wxpython demo. But for developing, the startup speed for a simple hello world app with about 10 sec is not acceptable for me. I think, the wxmsw232h.dll with about 4 Mb is the slowing factor. Is there any chance to load this dll already when win95 is started or is it a reasonable idea to load this dll in a ramdrive? Or is it better to try Tkinter or gtk? (I searched with google, but i didn't find a satisfied answer) Many thanks in advance, -- Francesco From pete at shinners.org Wed Jul 3 12:36:54 2002 From: pete at shinners.org (Pete Shinners) Date: Wed, 03 Jul 2002 16:36:54 GMT Subject: Creating Subclassable Objects?? Message-ID: <3D232862.9030309@shinners.org> I've been trying to 'update' some extension objects for my python modules. I couldn't find any documentation on this, so I've been trying to follow along from the other object sources inside python. At this point you are able to subclass the objects, the problem is they just don't work. If my new class has an __init__ method, it seems i cannot properly instance the objects (since it needs some args). If i don't have an __init__ method, i can instance the new class, but none of the new methods i add to it work (AttributeError). Anywhere I can look to get all the steps in place? From baf at texas.net Thu Jul 11 20:59:51 2002 From: baf at texas.net (Ben Fairbank) Date: Fri, 12 Jul 2002 00:59:51 GMT Subject: Note form Newbie to Newbies Message-ID: <3d2e2931.1292849@news.texas.net> Hello Fellow Learners -- In case there are any others looking for Python books, some are going for very low prices on Ebay. I have recently bought two or three at startlingly low prices. For example, a copy of "Programming Python," by Mark Lutz, 2nd edition, goes for $55 in bookstores, about $38 on Amazon; I picked it up for about $17 in an eBay auction in which I think I was one of only two bidders. BAF From paul at boddie.net Thu Jul 4 13:44:13 2002 From: paul at boddie.net (Paul Boddie) Date: 4 Jul 2002 10:44:13 -0700 Subject: Web templating/db tool with best designer/coder separation? References: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> <23891c90.0207021228.6809cf9b@posting.google.com> Message-ID: <23891c90.0207040944.71a67d1a@posting.google.com> Stefan Franke wrote in message news:... > > What makes we wonder is, that XMLC was at least mentioned on zope-dev > along with the abandonment of Hiperdom in favour of the upcoming ZPT > about two years ago - as a quick archive search yielded. > > Nevertheless it didn't have influence any influence on the design of ZPT. > Or were there any deliberate design decisions against this approach? I'm not familiar with the ZPT design process, but there are several advantages in having some kind of "declarative" template language which automatically reflects the state of data structures (like DTML does with the looping and value tags, for example) without needing programmatic intervention behind the scenes. Certainly, it can be easier to verify whether a template is going to present the correct data, and to do it properly, if there's no run-time activity which can change the nature of the data being presented. It certainly seems very elegant to use a DOM-like API to edit parts of a Web page, for example, and I would argue that the ability to isolate a document structure (around the data being represented) within another document structure (that describing the final output) is almost essential to separate presentation from logic. However, it's arguably tedious to write lots of stuff for a DOM API, not to mention having to maintain such code (in addition to the other stuff) when the fundamental data structures in a particular system need changing. Paul From spam at ob_scure.dk Thu Jul 25 11:24:59 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Thu, 25 Jul 2002 17:24:59 +0200 Subject: Refer to function name (newbie ques) References: <805bee23.0207250649.5a4d89d0@posting.google.com> Message-ID: <3D40184B.3070308@ob_scure.dk> chris ciotti wrote: > Hi - > > Is there a way to get the name of the running function? In a script > I'm doing some error checking and I want to be able to name the > function that screws up. Something like: Such error handling is often done using exception handling. An (not to elegant) example: --- Python code -- class MyError(Exception): pass def foo(): try: stuff=1 bar=2 if stuff != bar: raise MyError('Mismatch') except MyError, e: import sys print 'Error: "%s" happened in "%s"' % ( str(e), str(sys.exc_info()[2].tb_frame.f_code.co_name) ) foo() --- Python code end --- The above code prints: Error: "Mismatch" happened in "foo" The (sys.exc_info()[2].tb_frame.f_code.co_name) part is where the name is found. Links: * http://www.python.org/doc/current/lib/module-sys.html * http://www.python.org/doc/current/lib/module-exceptions.html Also look at asyncore and cgitb, they do some quite advanced error reporting. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From b.hall at irl.cri.nz Wed Jul 31 17:34:19 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Thu, 01 Aug 2002 09:34:19 +1200 Subject: A generic question: idiom for a paramterized base class? References: <918bc22f.0207311105.50a33dba@posting.google.com> Message-ID: <3D4857DB.CFD1141C@irl.cri.nz> Thanks Donnal, Your idea seems to provide me with the following solution. I have split your code into two modules and added a class: ############### DonnalBase.py class AbstractBase(object): def __iadd__(self,other): return self.TAdd(self,other) def __add__(self,r): return AbstractBase.__iadd__(self,r) def __radd__(self,l): return AbstractBase.__iadd__(l,self) class TAdd(object): pass and ####### Donnal.py from DonnalBase import AbstractBase class MyClass1(object,AbstractBase): # One type of TAdd: class TAdd(AbstractBase): def __init__(self,l,r): print "TAdd instance 1" class TNode(object,MyClass1): def __init__(self): print "TNode instance" ####################### You see that I need 'MyClass' to act as a base for a number of classes (like TNode). This seems to work: >>> x = Donnal.TNode() TNode instance >>> y = Donnal.TNode() TNode instance >>> t = x + y TAdd instance 1 Thanks Blair Donnal Walter wrote: > ...snip... > Does this do what you want? > > ################################################## > class AbstractBase(object): > def __iadd__(self,other): > return self.TAdd(self,other) > def __add__(self,r): > return AbstractBase.__iadd__(self,r) > def __radd__(self,l): > return AbstractBase.__iadd__(l,self) > class TAdd(object): pass > > class MyClass1(AbstractBase): > > # One type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 1" > > class MyClass2(AbstractBase): > > # Another type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 2" > ################################################## > > >>> x = MyClass1() > >>> y = MyClass2() > >>> t = x + y > TAdd instance 1 > >>> u = y + x > TAdd instance 2 > > Donnal Walter > Arkansas Children's Hospital From renzo.tomaselli at tecnotp.it Mon Jul 8 10:13:57 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 8 Jul 2002 07:13:57 -0700 Subject: Embedding: how to extend a C++ instance by Python methods References: Message-ID: <878dc260.0207080613.3d6aca81@posting.google.com> Gerhard H?ring wrote in message news:... > Renzo Tomaselli wrote in comp.lang.python: > > Hi all, > > my current goal is to extend a C++ instance behavior by a Python > > method, > > A C++ class that's exposed to Python, with one method delegating to a > Python method defined in a .py file? Correct, but though an undefined number of methods. > > so that an explicit "execute(scriptName, args)" method on such > > instance will end up into running a Python method defined by > > scriptName. > > Which execute() function is this? I found the rest of your post pretty > confusing. > > If all you want is call a Python callable (function/method/...), you > can use PyObject_CallObject for this. > > Else could you please try to rephrase your question a little? > > Gerhard Ok, I apologize for not begin clear. In short, I start from a C++ environment where I want to store Python scripts into a kind of OODBMS. There is a number of C++ objects I want to expose to Python, no problems here. Then I want to allow users to add their own behaviour to these objects, say add new Python methods and run (execute) them on demand. This is done both for overridding existing C++ methods and for adding quite new methods. So I need to implement a couple of extra C++ methods on my objects such as: add(name, functionBody) where functionBodyis a string containing the declaration of a Python function, to be run having the first arg bound to the invoking "self" object. I expect this operation to add a new method to the current object (e.g. its C-wrapper or a Python object derived from it) under the specified name, so that in the future the user can ask for running it through a second C++ method: execute(name, argList) while getting something back. Adding does some more tricks, like storing the function body into my db, but this is not important here. A key point is that I want users to be able defining just method bodies, not to play around with entire modules. For this reason I would like to implement the housekeeping details in C++ as much as possible. What I miss here is about creating callable objects from these stored declarations, so that they can be added to instances and invoked on the fly. Any help will be appreciated, Renzo Tomaselli --------------------------------------------------------------------------- TecnoTP s.n.c. Special Information System Design Maso Pelauchi I38050 Ronchi Valsugana, Trento TN ITALY e-mail: renzo.tomaselli at tecnotp.it --------------------------------------------------------------------------- From stefan.heimann at web.de Sun Jul 21 06:23:34 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 21 Jul 2002 10:23:34 GMT Subject: XSLT processor References: <21k_8.103407$%%2.4630636@news2.east.cox.net> <871y9yosc0.fsf@pokey.henrik-motakef.de> Message-ID: Henrik Motakef wrote:: > thehaas at binary.net writes: > >> Stefan Heimann wrote: >> > Saxon - a XSLT processor written in Java - provides such an internal >> > API. Does anyone know if there is something similar for python? >> >> I have no idea if the "pure-Python" XSLT processors (4xslt, etc.) have >> that, > > 4XSLT has an API to write extension elements/functions. I can't find > the documentation on the net right now, but my (oldish) installation > came with the files 4XPath-Api.html and 4XSLT-Api.html in the doc/html > directory that should help. I know that. But extension elements/functions is not the thing I need. I want to register my own function as a template. Instead of the content of the element being executed, the registered function should be called. Bye Stefan From sholden at holdenweb.com Mon Jul 29 11:05:52 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Jul 2002 11:05:52 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> "John Roth" wrote ... > "Fredrik Lundh" wrote... > > Bryan Olson wrote: > > > > > The mistake was limiting lambda to expressions. > > > > Guido can channel himself (or Tim will do it), but from what > > I can tell, he's always said that the "mistake" was adding > > something to the language that almost, but not completely, > > works like lambdas do in other languages. > > > > (lambda, map, filter, etc was contributed code) > > > > the really big usage problem (whether you knew lambdas > > from other languages or not) used to be that they were a > > real pain to use under the LGB scoping rule. with the intro- > > duction of nested scopes, that problem no longer exists. > > > > to fix the other "mistake", some needs to come up with a > > really great syntax (and get michael hudson to implement > > it for them ;-). ideas are welcome. > > What's the problem with that? If we give up the notion > that anonamous functions need to look like expressions, > it should be simple. Just stick the function definition inline, > indentation and all. The only issue is defining a new keyword, > since lambda doesn't work that way. "def" would probably > work, since it's only allowed at statement level now. > I'd like to see an example of this, since it appears you haven't fully thought this through. You mean you'd like to be able to write some thing like the following: for word in 'fee fie fo fum'.split(): Button(frame, command=lambda: print word) This is currently acceptable in Python because the lambda's inside a parenthesised argument list. How would I add a second line to the lambda? I'm always suspicious of phrasing like "all you need to do..." or "the only issue...", since it often indicates that insufficient thought has gone into a proposal. And the reason I'm suspicious when other people do it is because I've watched me doing it enough to get into trouble! Conclusion: this idea is currently 0.345-baked :-) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From marklists at mceahern.com Wed Jul 24 11:04:05 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 24 Jul 2002 10:04:05 -0500 Subject: error code In-Reply-To: <3d3ebee7$0$4203$afc38c87@news.easynet.fr> Message-ID: > I want to get the code of an error . > > how can I do that ? > > With "sys.exc_value" and "sys.exc_type" I have a String . > But I want a Integer This probably isn't what you want, but given the vagueness of your question, how the heck would I know that? class MySpecialError(Exception): code = 100 try: raise MySpecialError except Exception, e: if hasattr(e, "code"): print "Code: %d" % e.code // mark - From shalehperry at attbi.com Fri Jul 12 15:45:39 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 12 Jul 2002 12:45:39 -0700 (PDT) Subject: switch recipe? In-Reply-To: Message-ID: On 12-Jul-2002 Mark McEahern wrote: > In response to a question earlier today, I wrote a function I called > make_color_switch: > > from __future__ import generators > > def make_color_switch(color1, color2): > def color_switch(): > i = 0 > while True: > if i % 2: > yield color2 > > It seemed like this could be more generic: > > from __future__ import generators > > def make_switch(*args): > """Return a generator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") > def switch(): > i = n = 0 > while True: > i = n % len(args) > yield args[i] > n += 1 > return switch > out of curiosity, what happens when n reaches the end of the int/long/whatever that stores it? > Is switch a bad name for this? Can anyone suggest a better name? Other > improvements? What I like about this code is it demonstrates several > "advanced" features of Python, all the while retaining (imho) the simplicity > and clarity Python is known for: > > generators > nested scopes > variable length argument arrays > functions as objects > > Here's sample code that shows it used in the context of the original > question: > while the above code is a nice sample, the below code should not be given to people learning the language, it uses way too many tricks. Plus one letter variable names are a pain. > def colorize(s, *colors): > switch = make_switch(*colors)() > template = "<%(color)s>%(c)s" > l = [] > for c in s: > color = switch.next() > l.append(template % locals()) > print ''.join(l) > > colorize("testing", "black", "red", "green", "blue") > switch is an interesting idea, definately needs a new name. From shalehperry at attbi.com Tue Jul 23 12:01:18 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 09:01:18 -0700 (PDT) Subject: re.finditer In-Reply-To: Message-ID: > > You want 'import sre' > >>>> import sre >>>> import re >>>> re.finditer('r+?','library') > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'finditer' >>>> sre.finditer('r+?','library') > > > Is this a documentation bug? > ****WHAT****?????? import re simply is a wrapper around sre to hide the fact that around 1.5 the regex engine was updated. below is my re.py from 2.2.1. engine = "sre" # engine = "pre" if engine == "sre": # New unicode-aware engine from sre import * from sre import __all__ else: # Old 1.5.2 engine. This one supports 8-bit strings only, # and will be removed in 2.0 final. from pre import * from pre import __all__ so it looks like Lundh (or someone else) forgot to make finditer exportable from sre. From chris_mk at hotmail.com Wed Jul 31 14:44:28 2002 From: chris_mk at hotmail.com (Christopher) Date: 31 Jul 2002 11:44:28 -0700 Subject: decoding XML-ified special chars such as " References: Message-ID: For some reason it wasn't posted, but I wrote a message saying that I read the email incorrectly (I thought it was the other way around, trying to encode XML/HTML, just like Skip said). Sorry about that. I did find the unescape module (see my post below). Sorry again. Chris Skip Montanaro wrote in message news:... > chris> from xml.sax.saxutils import escape > chris> data = escape(orig_data) > > That goes the wrong way. I think the OP wanted to go from '"' to '"', > not the other way around. > > chris> ... you might get by using urllib.unquote(data) > > That's for unquoting stuff that's been escape for inclusion into URLs, also > not what the OP asked for. From bokr at oz.net Tue Jul 16 18:55:03 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2002 22:55:03 GMT Subject: Bug? interactive echo clobbering softspace of redirected stdout? Message-ID: ISTM it's a bug one way or another. Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class X: ... def __init__(self): self.s=[] ... def write(self,x): self.s.append(x) ... >>> import sys >>> oso=sys.stdout >>> sox=X() >>> dir(sox) ['__doc__', '__init__', '__module__', 's', 'write'] <<--There's no .softspace yet. >>> sys.stdout=sox >>> dir(sox) <<--This seems to create one before doing dir() >>> print 'sox ss=%s'% (sox.softspace,), <<--This should leave softspace set IMO. Interactive EOL >>> print 'sox ss=%s'% (sox.softspace,), should reset sys.__stdout__.softspace, not sox.softspace >>> def foo(): ... print 'from foo: sox ss=%s'% (sox.softspace,), <<-- these will go out with only one EOL below ... print 'from foo: sox ss=%s'% (sox.softspace,), ... >>> foo() <<-- single interactive EOL doesn't kill first softspace >>> sys.stdout=oso >>> sox.s ["['__doc__', '__init__', '__module__', 's', 'softspace', 'write']", '\n', 'sox ss=0', '\n ', 'sox ss=0', '\n', 'from foo: sox ss=0', ' ', 'from foo: sox ss=1', '\n'] Or, a hand-edited grouping: [ "['__doc__', '__init__', '__module__', 's', 'softspace', 'write']",'\n', <<--from dir(sox) 'sox ss=0', '\n', <<--from 1st print 'sox... -- should have left softspace set for next print 'sox ss=0', '\n', <<--from 2nd print 'sox... -- but it got clobbered 'from foo: sox ss=0', ' ', 'from foo: sox ss=1', '\n' <<-- from foo(), note softspace not clobbered. ] Looks to me like interactive typing echo should operate on the softspace attribute of the output it's going to (sys.__stdout__.softspace ?), and not sys.stdout.softspace, unless they're the same. Or else interactive echo characters ought to be teed/copied to sys.stdout to make the softspace action consistent with modifying sys.stdout.softspace. I prefer the former. Regards, Bengt Richter From jriveramerla at yahoo.com Thu Jul 18 18:33:30 2002 From: jriveramerla at yahoo.com (Jose Rivera) Date: 18 Jul 2002 15:33:30 -0700 Subject: Python v.s. huge files PROBLEM!! Message-ID: <11e94203.0207181433.1c32f5bc@posting.google.com> Hi.. Scenario: OS : WinNT 4.0 FileName: RESPALDO_MENSUAL_Data.MDF Size : 243,386,941,440 bytes Problem: I want to copy this file to another disk. Both disks have 500 GB of free space. Microsoft problem: You May Not Be Able to Copy Large Files on Computers That Are Running Windows NT 4.0 or Windows 2000 (Q259837) Workaround suggested by Microsoft: Use Backup / Restore utilities Result: They didn't work either... using HP OmniBack Workaround made by us: Make a python program that read and writes to the other file in theother disk. Python Code: import sys if len(sys.argv) != 3: print 'Format:' print '\t pyCopy.exe SourceFile EndFile' else: fn1=sys.argv[1] fn2=sys.argv[2] f1=open(fn1,'rb') f2=open(fn2,'wb') data=f1.read(1024*1000) while data: f2.write(data) data=f1.read(1024*1000) f1.close() f2.close() Result: IOError: [Errno 22] Invalid argument Question: Is there anything wrong? From aleax at aleax.it Tue Jul 9 17:08:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 21:08:19 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: <7hIW8.49611$Jj7.1370694@news1.tin.it> Charles Hixson wrote: ... > Let's be explict: > from __future__ import nested_scopes > class A: > def ma(self): > print "ma, ma" > def pa(self): > self.ma() > class B(A): > def ma(): > print "hello, world" > tst = B() > tst.pa() > > Testing this produces the message, "hello, world" This has been named the "Template Method" Design Pattern by Gamma et al, in their wildly and deservedly successful book "Design Patterns", which has given the Patterns movement such huge exposure. Template Method is my equal-first candidate with Factories (which, however, Gamma et al split into several patterns) as THE most powerful and important design pattern of them all. It doesn't show up well in this silly example, because A.pa has no added value at all nor any reason for existing. But it doesn't take much to add "purpose" to Template Methods: class A: def hi(self, *args): print "Hello, World!" def greet(self, n, *args): for i in range(n): self.hi(i, n, *args) There you are -- a Serial Greeter. Method greet encapsulates and abstracts the functionality of repeating a greeting N times. By default each greeting is "Hello World!" on a separate line, but it's not hard to start customizing this...: class B(A): def __init__(self, separatelines=1): self.separatelines = separatelines def emit(self, lastline, message): print message, if lastline or self.separatelines: print def hi(self, i, n, *args): self.emit(i==n-1, "Hello, World!") There -- now we've encapsulated the concept of making line separation optional. But, we aren't quite done yet...: class C(B): message = "Hello, World!" def hi(self, i, n, *args): self.emit(i==n-1, self.message) See what we have separated out now? No? What about...: class D(C): message = "Hi there, Earthling..." ...starting to get it...? The last step is not part of Template Method as published in the Design Patterns book, but that's just because the languages they had in mind (C++ and Smalltalk) aren't as smooth and flexible as Python, and don't let subclasses override data, just methods. In Python, data-overriding is a very useful technique and a perfect complement and completion of the Template Method DP. > This seems to be the wrong message. You really need to get out more, you know. Design Patterns has been out for well over 5 years -- you can hardly call yourself an OO programmer if you don't know it well! > The version of pa that was called > was the version defined in class A, so the routine called should have > been the routine defined in class A. Absolutely not! That's the very reverse of OO programming. Look again: > def pa(self): > self.ma() this very explicitly (and a good thing too, for all the self-haters!-) says: call the version of ma defined ***ON self***. It most clearly does NOT say "call the version of ma defined ***in class A***! Had it wanted to say that, it would obviously be: def pa(self): A.ma(self) and that would normally be a pretty silly thing (just like defining a method as "final" in Java), but the language has not been and will never be invented that _doesn't_ let you do silly things. > Or, to me more accurate, for libraries to have maximal portability, I > would want the message to have generated "ma, ma", and I had been This behavior is perfectly portable among all platforms Python runs on (and, as far as methods are concerned, also to all languages that implement OOP). > assuming that nested_scopes would result in that being the message that > was produced. nested_scopes has to do with nested scopes. Classes inheriting from each others are not scopes and are not nested, so it's peculiar that you expected nested_scopes to affect them in any way. Alex From aleax at aleax.it Wed Jul 24 04:40:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:40:43 GMT Subject: good books References: Message-ID: Shagshag13 wrote: > is it still worth to buy it if you browse through this ? > > http://systems.cs.uchicago.edu/~beazley/tutorial/beazley_advanced_python/advpy.pdf > http://diveintopython.org/ > http://www.ibiblio.org/obp/thinkCSpy/dist/ > http://www.greenteapress.com/thinkpython.html > http://www.mindview.net/Books/TIPython > > because i'm also looking for "The" python's book but i'm tired to buy this > expensive books that i use only a few times and less that some internet > links... By the way, while probably not a saving of money, if you prefer online material consider O'Reilly's "Safari" offering. Several other publishers are together with O'Reilly's in the "Safari" scheme, but I'm not familiar with the other publishers' online offerings -- I do know however that O'Reilly's are excellent. I love books, real, solid, physical paper books -- my house and study are both chock full of them -- but online material does have its own pluses too. People with eyesight problems are probably most sensitive to those pluses -- the worse your eyesight, the more the possibility of using screen readers appeals. But even for you eagle-eyed guys, such pluses as searching and copy-and-paste should not be ignored. Alex From lac at strakt.com Sat Jul 6 11:32:56 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 06 Jul 2002 17:32:56 +0200 Subject: jwz threading algorithm in Python In-Reply-To: Message from "Sean 'Shaleh' Perry" of "Sat, 06 Jul 2002 08:16:57 PDT." References: Message-ID: <200207061532.g66FWuci001558@ratthing-b246.strakt.com> > > On 06-Jul-2002 Gerhard H?ring wrote: > > Has anybody implemented Jamie Zawinski's message threading algorithm in > > Python, yet and would like to share it? > > > > Here's the specification: http://www.jwz.org/doc/threading.html > > > > I'm about half-way thru with converting the Java implementation to > > Python (manual translation finished, in testing stage, now), but it > > looks like the debugging will take me quite some time still. Also, the > > code doesn't look very pythonic. If I could get a finished Python > > implementation, this would be much better :-) > > > > well when it is available be sure to put it somewhere public so we can all us > e > it in our cool python email software (-: > > > -- > http://mail.python.org/mailman/listinfo/python-list Ka-Ping Yee talked about a threading algorithm at IPC 10, but I wasn't there (only heard about it) and I don't know if it is this one or one he designed and wrote himself. Laura From ark at research.att.com Tue Jul 9 10:35:44 2002 From: ark at research.att.com (Andrew Koenig) Date: Tue, 9 Jul 2002 14:35:44 GMT Subject: Splitting a string every 'n' References: Message-ID: Simon> What is the idiomatic way to split a string into a list Simon> containing 'n' character substrings? I normally do Simon> something like: Simon> while strng: Simon> substring = strng[:n] Simon> strng = strng[n:] Simon> How about this? for start in range(0, len(strng), n): substring = strng[start:start+n] -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From dbasch at yahoo.com Thu Jul 18 00:04:35 2002 From: dbasch at yahoo.com (Derek Basch) Date: Wed, 17 Jul 2002 21:04:35 -0700 (PDT) Subject: Simple Pickle Question! In-Reply-To: <20020716204327.GA3124@unpythonic.net> Message-ID: <20020718040435.66515.qmail@web20809.mail.yahoo.com> Jeff, Thanks for the reply. Your answer was just what I was looking for. I am using a try: except: to catch the EOFError. Any other ways to handle an empty file? Thanks, Derek Basch --- Jeff Epler wrote: > You must "seek" the file to the beginning to read it > again from the > beginning. > > Here's an example without the use of pickle: > f = open("test_readwrite", "w+") > f.write("hi there") > # f.seek(0) > print `f.read()` > > If you uncomment the 'seek' line, you'll get some > text in f.read(). > Otherwise, you'll get an empty string (EOF). > > Pickle doesn't seem to handle premature EOF well.. > (the missing key is > probably the empty string) > > Jeff __________________________________________________ Do You Yahoo!? Yahoo! Autos - Get free new car price quotes http://autos.yahoo.com From emile at fenx.com Tue Jul 2 07:01:45 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Jul 2002 11:01:45 GMT Subject: Simple Conceptual Pickling problems References: <3d217732$0$4276$afc38c87@news.easynet.co.uk> Message-ID: "chris lyon" wrote in message news:3d217732$0$4276$afc38c87 at news.easynet.co.uk... > I am trying to pickle instances of a class stored in a dictionary with a MD5 > hash used as the key of the dictionary. > > I can pickle them ok and when I examine the pickle file (I'm using the > default ASCII mode) I can see the instance data in the pickle file. > > However when I try to load the pickle file After I have imported the module > from which it was all derived I get:- > > SystemError: Failed to import class Programme from module __main__ This is the hint. The module's name when the pickle was created was __main__, which only happens when the module is not imported, but is run directly. You need to pickle and unpickle from within the same context, eg, use import in both cases. HTH, -- Emile van Sebille emile at fenx.com --------- From erno-news at erno.iki.fi Thu Jul 11 02:49:07 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 11 Jul 2002 09:49:07 +0300 Subject: try/finally question References: <7xd6twow3x.fsf_-_@ruckus.brouhaha.com> <7x3curfhcb.fsf@ruckus.brouhaha.com> Message-ID: In article <7x3curfhcb.fsf at ruckus.brouhaha.com>, Paul Rubin writes: [about signals interrupting a finally block] | More generally though, this seems like a deficiency in Python. In | Java I believe that this issue can be solved by a synchronized object, | but Python doesn't have those. at least the sun jvm seems to just ignore signals and dies of natural causes if you hit ctrl-c. i am not sure it would feel right to me if a finally block would change how signals are handled. on the other hand the asynchronous nature of signals is pretty much gone already in python. -- erno From linuxbrad at rogers.com Mon Jul 8 21:00:53 2002 From: linuxbrad at rogers.com (Brad Fonseca) Date: Tue, 09 Jul 2002 01:00:53 GMT Subject: Getting IDLE 0.8 to recognize Pyhthon 2.2.1 References: <115W8.7627$Xg%.3561@news01.bloor.is.net.cable.rogers.com> Message-ID: <9BqW8.13703$FH6.6004@news01.bloor.is.net.cable.rogers.com> Gerhard H?ring wrote: > * Brad Fonseca [2002-07-08 00:28 +0000]: >> Hi! >> >> I've upgraded to python 2.2.1 but when I start IDLE it still starts >> Python 2.1.1. How do I get IDLE to start Python 2.2 > > Two possibilites. > > 1) Preferrable: Install the IDLE that comes with your Python 2.2.1. On > Debian: apt-get install idle-python2.2. Other distributions like the > KRUD RPMs from jafo available on python.org have idle in a seperate > package (in python2-tools-2.2.1-1.i386.rpm, IIRC). > > 2) A little more hackish: Find your idle: "which idle". Then change the > first line from > > #! /usr/bin/python > > to > > #! /usr/bin/env python2.2 > > Gerhard To be more clear, I tried the second option and it doesn't work properly. How do I get idle to install on Mandrake. I used the tarball to install 2.2 in my /usr/local/src directory. Thanks, -- --- Brad Fonseca From achim.domma at syynx.de Thu Jul 25 11:50:59 2002 From: achim.domma at syynx.de (Achim Domma) Date: Thu, 25 Jul 2002 17:50:59 +0200 Subject: DLL files References: Message-ID: "Chris Liechti" wrote in message news:Xns9256A7E009E31cliechtigmxnet at 62.2.16.82... > yes. but one could embedd the python interpreter in a DLL and just forward > the calls to the DLL to a loaded script. > this requires a compiler and some code for the DLL that is application > specific (but autogenerable through a script). a COM object might also be an option, depending on the requirements Achim From paul at boddie.net Tue Jul 9 13:34:34 2002 From: paul at boddie.net (Paul Boddie) Date: 9 Jul 2002 10:34:34 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <23891c90.0207090934.30236242@posting.google.com> curt at journyx.com (curt finch) wrote in message news:<96c7f32.0207081518.52ea644a at posting.google.com>... > [Quoting a competitor's "analysis" of Python] I won't go through the points and produce a 300 line post like almost everyone else has done since, as almost everyone has noted, most of them are ridiculous and suggest either cluelessness, arrogance or a vested interest in writing lots of low-level "old school" code, preferably in C++ if only they had the chance. It is true that Python is used to describe algorithms and to prototype software, mainly because Java (for example) is relatively poor at investigating concepts, getting things working, and so on. However, it is absolutely untrue to say that Python developers don't tend to practise code reuse - it's one of the best languages to "leverage your investment in existing components" (in executive-speak), *especially* in the Java scene. And it's laughable to start talking about a lack of J2EE-compliance - Jython is "100% Pure Java (TM)" and works very well with J2EE components... a lot better than various Java products on most occasions, too. > As a new relatively untested development platform in the licensed > software community, Python has certain deficiencies with which all > users and developers should be aware. I suppose when the term "licensed" is used, they actually mean "closed source, proprietary licensed", but this is untrue as well: the Infoseek intranet search products, for example, were both closed source and proprietary Python software before "enterprise Java" was even at the "short trousers" stage. Reading the full list, I suspect that the person who wrote it has never used Python and may even be an inexperienced developer who has been asked to do some "research" on behalf of the project leader at your competitor. Things like... > ? Python does not provide multiple ways to perform tasks as do > most other languages. ...sound like a bizarre rephrasing of "there's only one way to do it" taken literally by someone who doesn't know their stuff. And this... > ? Since Python is relatively a new language, there are only a > few resources available for information on its latest developments. ...deserves special attention. For Python, there's a shedload of decent free, quality material out there on the Internet, and should things not work as expected with a package or module, there are usually good support possibilities and the source code is most often provided and is easy to inspect. That's typically two more things than any given comparable Java technology, in my experience. Firstly, take a look at any Java support forum and it's flooded with questions on how to get things to work. Now, one might claim that the majority of these are from "clueless newbies" who should have read the instructions, but a brief inspection of the instructions frequently suggests that certain classes of Java project just don't have decent manuals. But anyway, such entry-level questions tend to obscure the threads describing non-trivial problems, thus making it difficult for the average developer to solve them and get on with their work. Secondly, it's all very well that Java packages are shipped in binary form for easy installation, but when things go wrong, the class name, method name and line number details are pretty useless. On numerous occasions, it has been necessary for me to investigate configuration issues with WinZip, just to see which classes are there and what bizarre properties have been set by default. Ironically, in the context of this message, the best tool for debugging Java configurations is called Jython. I agree with Anthony Baxter - you should name and shame these people, if only for us to discover if it's a big name consulting house or not. That would be interesting... Paul From charleshixsn at earthlink.net Tue Jul 9 14:08:38 2002 From: charleshixsn at earthlink.net (Charles Hixson) Date: Tue, 09 Jul 2002 11:08:38 -0700 Subject: Why self? References: <3D29DBA4.7070606@onsitetech.com> Message-ID: Robb Shecter wrote: > Brian Quinlan wrote: > ... >> >> Two of those characters are your own fault (the underscores). > > > I don't think so: As I understand it, the double underscores are > necessary in order to for the class to function correctly if subclassed. > ... > Robb > If you were arguing in favor of a smarter scoping rule, that would be reasonable. But as an argument against the explicit use of self as the first parameter of a method..., probably not. The errors that this causes are quickly caught and corrected. Question: is class TestA: def methodb(): ... legitimately accessed as TestA.methodb()? If so, then the question about the self argument is resolved. It's the marker that distinguises instance methods from class methods. It is legitimate to claim that there ought to be a better way to do this, but any language that implemented this would be very divergent from Python. Still, it would be easy to write a pre-processor to turn it into Python, as you aren't really tinkering with the basic syntax. I've sometimes thought of doing this to create a dialect that had explicit loop markers (indentation would still be required, but the loop markers could be used to reconstitute it if the alignments became corrupted). The problem is that dict's use my preferred marker, and tuples and lists use the other reasonable choices, and ... every time I've almost decided to do this I've given it up as a bad idea.\ -- -- Charles Hixson Gnu software that is free, The best is yet to be. From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 11:59:04 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 10:59:04 -0500 Subject: better 'splice' function References: Message-ID: >>>>> "Sean" == Sean 'Shaleh' Perry writes: Sean> something A LOT like this was discussed within the last two Sean> months at length. Many, many, many implementations were Sean> presented. Have a search through the archives. Yep, check http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&frame=right&th=fb73946e707ff1da&seekm=mailman.1019594863.1719.python-list%40python.org#link1 John Hunter From pinard at iro.umontreal.ca Mon Jul 8 15:36:06 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 15:36:06 -0400 Subject: Flush In-Reply-To: <02070815110700.28840@magneto> References: <02070815110700.28840@magneto> Message-ID: [Charles] > Anyone know if python has a flush() function like PHP, to buffer dump > in CGI ? All file objects have a `.flush()' method. Like PHP, I do not know! :-) It is usually convenient doing: sys.stdout.flush() right after outputting the HTTP header, if you are going to do some lenghty computation, and want to convince the user browser to wait after your script. Without this, the browser might decide that your server is not responding... -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From fredrik at pythonware.com Fri Jul 19 04:03:36 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 Jul 2002 08:03:36 GMT Subject: C-API question: Memory returned by PyString_AsString References: <2379a09f.0207182349.58a98350@posting.google.com> Message-ID: Christoph Bennemann wrote: > functions like PyString_AsString return a pointer to a character > vector. Is this memory specially allocated when I call this function > (which implies I have to take care of it in my program) or is this > merely a pointer to a character vector stored by the Python > interpreter (implying that I should not free the memory). I assume > that the later is correct, but would like to have a definitive answer. http://www.python.org/doc/current/api/stringObjects.html char* PyString_AsString(PyObject *string) Returns a null-terminated representation of the contents of string. The pointer refers to the internal buffer of string, not a copy. The data must not be modified in any way, unless the string was just created using PyString_FromStringAndSize(NULL, size). It must not be deallocated. From andreas at kostyrka.priv.at Sun Jul 28 10:45:19 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 28 Jul 2002 16:45:19 +0200 Subject: Guide to the python interp. source? In-Reply-To: References: Message-ID: <1027848771.19639.131.camel@vaio2> Am Sam, 2002-07-27 um 15.19 schrieb Tim Gahnstr?m /Bladerman: > Maybe, maybe not, > Maybe I can just convert everything internaly to uppercase? I don't know, > havn't given it much thought yet. Probably not. You should try first to see how many collisions you get by going case insensitive. > I have thought about that and that is not what I want. In this particular > case I want an integer object to be created with the value 2, that is sent > to inc and changed but when we come to the next line that object will be > garbage collected because none have a refference to it. > Inc will work as it is supposed to do wich is good if you just want to have > the sidefects of it. An other possibility would be to generate a good > looking errormessage. Because it is likely a mistake. Nope it is not. Or you forbid also constructs like: sys.stdout.write("Hello World\n") which would have to be written like: dummyvar="Hello World\n" sys.stdout.write(dummyvar) > > The hard part comes in determining what you want to > > happen on e.g.: > > f(x, x.y, x.y.z, x.y.z.t) > > Cheesch! I will consider that by christmas :-) Especially, if x happens to be an object that is readonly (throws just exceptions upon __setattr__ :) ) Or better even: f(__debug__) (__debug__ happens to be 100% readonly variable, because it changes the way the compiler works :) Andreas From aleax at aleax.it Fri Jul 26 15:28:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 19:28:43 GMT Subject: Derivative of string as a name of list or dictionary (or class?) References: <82fe0bb.0207260749.3059e20a@posting.google.com> Message-ID: John Hunter wrote: ... > of a class, what do you think of the following approach to > manipulating globals, which I discovered doing a little more reading > on this issue in the c.l.python archives. > > name = 'seq' > val = ['John', 'Hunter', 'was', 'here'] > globals()[name] = val > print seq > > globals()['print'] = 'Clobber?' > print seq #no clobber You couldn't clobber print anyway (it's a keyword) -- the exec would fail (noisily -- SyntaxError). Here, you're failing silently instead, in a sense. When you clobber builtins, they stay clobbered -- e.g., use your first stanza to trample over name 'globals', and you'll see how well the 2nd one works. Alex From shalehperry at attbi.com Thu Jul 18 15:47:40 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 18 Jul 2002 12:47:40 -0700 (PDT) Subject: Apply and map function In-Reply-To: <3D369135.6040505@nfg.nl> Message-ID: On 18-Jul-2002 Nico de Boer wrote: > Hi all, > > I want to implement the apply or map function into the following code: > > initmethods = InitMethods() > methods = { > 'SiteNav_OpenTreeLevel': initmethods.init_opentreelevel(), > 'SiteNav_LinkTreeItem': initmethods.init_linktreeitem(), > 'SiteNav_ActiveTreeItem': initmethods.init_activetreeitem(), > 'SiteNav_CloseTreeLevel': initmethods.init_closetreelevel(), > 'local_css': initmethods.init_localcss() > } > for (methodname,method) in methods.items(): > self.createDTMLMethod(methodname, '',method) > hmm let's see. map(lambda item: self.createDTMLMethod(item[0], '', item[1]), methods.items()) should do the trick. Sure it isn't pretty (-: What is wrong with the explicit for loop? From pan-newsreader at thomas-guettler.de Sat Jul 27 14:47:56 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Sat, 27 Jul 2002 20:47:56 +0200 Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> Message-ID: On Sat, 27 Jul 2002 15:44:56 +0200, Jeffrey Keil wrote: > Greetings: > > I'd like to have a Python script open a text file, process the data in > the text file and then write a report to an Excel file. I'm not sure how > I would write to an Excel file from a Python script. Is there any books > that would give me details on doing this? Just create a html-table like this: ....
col 1 col 2
foo ....
Then write this to a file ending with *.xls. I think Excel since Excel97 will read this thomas From ark at research.att.com Tue Jul 9 09:00:36 2002 From: ark at research.att.com (Andrew Koenig) Date: Tue, 9 Jul 2002 13:00:36 GMT Subject: Why self? References: <090720020820257031%pecora@anvil.nrl.navy.mil> Message-ID: Louis> Ugly is in the eye of the beholder. I think it's cleaner (a design Louis> goal of Python as I recall). I'm not convinced. I see two problems: 1) In Python, it is generally not possible to determine what the attributes of an object are by statically examining the source. For example: class Thing: def __init__(self): setname(self) def printname(self): print self.name def setname(x): x.name = "Thing" At the time the compiler encounters the "print self.name" statement, how would it know that name is an attribute of the object of which printname is a member? Note that it hasn't seen the definition of setname yet. 2) Methods are just functions that happen to be attributes. In other words, we could have written this: class Thing: def __init__(self): setname(self) def setname(x): x.name = "Thing" def printname(self): print self.name Thing.printname = printname t = Thing() t.printname() effectively transforming printname into a method, even though it does not have the form of a method when it is written. It seems to me that dropping the explicit "self" would make these two programs much messier. In what way then is it cleaner? (Incidentally, the analogous arguments do not apply to C++ because C++ requires that all of the members of a class be known during compilation--with one exception, namely members inherited from a template base class. In that case, C++ requires the equivalent of an explicit "self" for essentially the same reason.) -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From roy at panix.com Sat Jul 6 16:42:38 2002 From: roy at panix.com (Roy Smith) Date: Sat, 06 Jul 2002 16:42:38 -0400 Subject: Python version of STL multimap? Message-ID: I often want to create a dictionary whose values are lists of items with the same key. I've got variations on: if dict.has_key (key): dict[key].append (value) else: dict[key] = [value] sprinkled throughout my code in many places. Sometimes I write it as: try: dict[key].append (value) except KeyError: dict[key] = [value] In a parallel universe, I recently decided it was about time to finally learn STL, so I picked up a book on it. Lo and behold, there's the multimap container template. Exactly what I've been doing in Python without knowing the right name for it. So, the question is, is there a standard way in Python to do multimaps, or should I just continue to roll my own with one of the above idioms whenever I need one? From akineko at pacbell.net Mon Jul 1 10:50:11 2002 From: akineko at pacbell.net (Aki Niimura) Date: 1 Jul 2002 07:50:11 -0700 Subject: A problem with urllib References: <3D1FD7A1.F265FC8E@engcorp.com> Message-ID: Peter Hansen wrote in message > Are you using the latest version? I was using Python 2.2 (not Python 2.2.1). So, I installed Python 2.2.1 to test my scripts. Unfortunately, the results are the same. > I tried a URL in urlopen() similar to the one you gave > (http://:admin at 192.168.1.1/Status.htm) and it didn't complain, > and tried opening the page with that information. Yes, it seems trying. But even I entered the correct user, passwd, it didn't accept. % test2.py Enter username for Linksys BEFSR41/BEFSR11/BEFSRU31 at 192.168.1.1: Enter password for in Linksys BEFSR41/BEFSR11/BEFSRU31 at 192.168.1.1: Enter username for Linksys BEFSR41/BEFSR11/BEFSRU31 at 192.168.1.1: ... (I entered CR/LF for user, entered 'admin' for passwd. But it didn't succeed.) Peter, thank you for trying out. Any further suggestion? Best regards, Aki Niimura From K.Rdt at TU-Berlin.DE Wed Jul 3 14:36:34 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Wed, 03 Jul 2002 20:36:34 +0200 Subject: HT clear some wxPython fram? In-Reply-To: <20020703110607.00c02458.logiplexsoftware@earthlink.net> Message-ID: Am 03.07.02 20:06:07, schrieb Cliff Wells : >> >> HOW I CAN CLEAR SOME FRAME? Hi 1.) Thank you very much, it's now working with the changes ### I made (s.b.) 2.) A further question: How can I change the font to equal spacing? tia K at Rdt >What you will want to do instead is something more like this: > >from wxPython.wx import * > >class MyPanel(wxPanel): > def __init__(self, parent): > wxPanel.__init__(self, parent, -1) > self.SetBackgroundColour(wxWHITE) > self.text = [] > EVT_PAINT(self, self.OnPaint) > > def OnPaint(self, event): > dc = wxPaintDC(self) > self.draw(dc) > > def write(self, text): > self.text.append(text) > if len(self.text) > 10: > del self.text[0] > dc = wxClientDC(self) > self.draw(dc) > > def draw(self, dc): > dc.Clear() > y = 0 > for t in self.text: > dc.DrawText(t, 0, y) > y += 15 > >class MyFrame(wxFrame): > def __init__(self): > wxFrame.__init__(self, None, -1, "MyFrame") > self.panel = MyPanel(self) > self.timer = wxTimer(self, -1) > self.timer.Start(100) > EVT_TIMER(self, -1, self.OnTimer) > > def OnTimer(self, evt): > self.panel.write("hello") ### y=os.popen( 'netstat -a -n','r').read() self.panel.write("--------------------------------------------------------------") yy=y.splitlines() for i in yy: if i[:5]==" TCP": ry=string.split(i) self.panel.write("%5s %22s %22s %22s" % (ry[0],ry[1],ry[2],ry[3])) ### > > def OnClose(self,event): > self.timer.Stop() > self.Destroy() > >class MyApp(wxApp): > def OnInit(self): > frame = MyFrame() > frame.Show(true) > return true > > >app = MyApp() >app.MainLoop() > > >Please realize that the apparent complexity of something so simple has more to >do with the nature of GUI programming than with Python. > >-- >Cliff Wells, Software Engineer >Logiplex Corporation (www.logiplex.net) >(503) 978-6726 x308 (800) 735-0555 x308 > --------------------------------------------------------------------- Hi K at Rdt --------------------------------------------------------------------- From jnana4 at DELETEhotmailCAPS.com Mon Jul 29 23:54:44 2002 From: jnana4 at DELETEhotmailCAPS.com (jano) Date: Tue, 30 Jul 2002 03:54:44 GMT Subject: beginner's question Message-ID: <66o19.694966$352.150300@sccrnsc02> Hi, I just installed 4suite, under win2k/cygwin, and python complains that it can't find a module that was installed. 08:39:08 /usr/doc/4Suite-0.11.1b3/test_suite :: python test.py Traceback (most recent call last): File "test.py", line 2, in ? from Ft.Lib.TestSuite import TestWalker ImportError: No module named Ft.Lib.TestSuite /usr/lib/python2.1/site-packages/Ft/Lib/TestSuite does exist, and I am uncertain why python does not see this. I would expect python to check in the /usr/lib/python2.1/site-packages directory to look for 'Ft', but it doesn't seem to be doing this. I am probably making a silly mistake, and any help would be appreciated. thanks, jano From whisper at oz.net Tue Jul 9 00:33:26 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 8 Jul 2002 21:33:26 -0700 Subject: Idle setup install falis on Win2k In-Reply-To: Message-ID: > -----Original Message----- > From: Tim Peters [mailto:tim.one at comcast.net] > Sent: Monday, July 08, 2002 20:57 > To: David LeBlanc; Python-List at Python. Org > Subject: RE: Idle setup install falis on Win2k > > > [David LeBlanc, wrestling with Idle on Windows] > > BULLSHIT! > > > > RTFC! > > > > If you run /python22/tools/idle/setup.py install see what happens!!! > > Ah, you didn't mention setup.py before. I didn't even know there > was such a > thing. The PLabs Windows installer installed Idle by itself. There's no > need for you to run setup.py for Idle on Windows; I assume it's there for > the benefit of the Unix distro, but I don't really know. How else would one have installed Idle (as compared to installing Python?) > [various unhappiness snipped] > > ... > > If /python22/tools/idle/setup.py shouldn't be run on Windows, WHY IS IT > > THERE? > > The Windows installer-builder copies the entire Idle source > directory; ditto > the entire Lib directory; and so on. I used to try to be more selective, > but the way Wise works, copying a whole directory is trivial and > fails soft, > while trying to filter it leads to masses of hard-to-maintain script that > fail hard. It's a "better safe than sorry" tradeoff. No argument with that. > > Strange as it might seem to you, some Windows developers use a command > > line and, at least in theory, if you install Idle, you should be > > able to run it from a command line. (BTW, it did install in the python22 > > group of the start menu.) > > You already know that you can extract the command line needed from the > installed shortcut's Properties, if you want to use a command > line. I have > no axe to grind about that either way -- suit yourself. Sure, I can type j:\python\tools\idle\idle.py to start idle from a command line - but I should be able to just type "python idle.py" to get it to run once it's properly installed. The real root of the problem seems to be that idle.py and idle.pyw expect that either the scripts they use are in the same directory or in sys.path (this does assume that those scripts are _in_ site-packages and not a sub-directory of it though). I don't know if U*x Python puts tools/idle on sys.path, but I have never seen AS Python or PL Python do so on Windows. (N.B. I do seem to recall that AS Python tweaks things slightly differently then PL Python during install - I think AS puts lib/tk in sys.path for some reason among other details.) > > AS for things that "only work for me", I have reinstalled C++, > Python and > > re-built standaloneZODB and it STILL compiles and crashes. I personally > > suspect all the weird and funny games that are played by SAZODB when it > > loads. Why, for example, does it import things and then delete them? > > (site-packages/zodb/__init__.py). > > As I've told you several times, I don't currently work on SAZODB as such. > You should raise your ZODB issues on the ZODB mailing list. I can assure > you you'll get a lot of sympathy about the odd import tricks the > code plays; > there's an ongoing effort to reduce this obscure magicalness in Zope3 and > ZODB4. Yes you did. > > Just because I'm the only one experiencing a problem DOES NOT mean that > > there's not a problem with your (Zope's) code! > > Sure. > > > I'm glad you declared the problem solved and then just walked away. > > That's out of line, David. I gave you a lot of help, and the last > communication we had on the subject came from you on Saturday afternoon, > where you said you were *going* to try some things ("reinstall VC6sp5 > without the AMD extensions ASAP (not today though"). I never heard more > about that until now. Now that I hear that it didn't work, I > encourage you > to send me the code you compiled, as I earlier sent you the code > I compiled. > The last I heard, the code I sent you worked for you. It would be helpful > to learn whether the code you compiled fails for me. Yes, you did give me a lot of help and I do appreciate it, particularly since (a) it's not your code, and (b) it was a direct communication and not a ml post. I asked you at least one question in the mail I sent you on Saturday, and since I didn't receive an answer, I supposed (no _WAY_ am I going to assume ;-)) that you where not involved with the problem any more. I don't recall your asking me to send you my breaking binaries (nor can I find it in any of the emails from you). I will do that immediately. BTW, as it turned out, I had d/l'd the VC AMD extensions, but had never installed them. > Chill out. the decaf iced americano is doing that as we speak :) > it's-just-a-computer-ly y'rs - tim Sorry to have been grumpy about this, it's just that the remark about it being just another thing that fails only for me rubbed the wrong way. I doubt that any "setup.py install" of Idle will work on Windows without some tweaking to the two scripts put into python22/scripts. It's worth noting that setup.py outputs a message to the console that it's doing some sort of fixup on idle.py during install. It did modify the #! line to point to my python install. I do apologize if I seemed ungreatful about your assistance on the SAZ problem. It was definately beyond the call of duty. I do appreciate the work you and the other Python core people do to maintain and further Python. Dave LeBlanc Seattle, WA USA From achim.domma at syynx.de Thu Jul 4 08:37:15 2002 From: achim.domma at syynx.de (Achim Domma) Date: Thu, 4 Jul 2002 14:37:15 +0200 Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: not tested, but something like this should work: // can this be done with lambda ??? def myComp(a,b): return cmp(a[1],b[1]) tmpList = yourDict.items() tmpList.sort(myComp) for name,count in tmpList: print name,count Achim "Ben Fairbank" wrote in message news:3d243af0.465960 at news.texas.net... > I have several long (thousands of entries) dictionaries of words used > in plays; associated with each word is the number of times it is used > in the play. I have had no problem printing the words alphabetically > (send keys to a list, sort the list, access dictionary by the sorted > key list), but I have not found an elegant way to sort by frequency > of use. The best I have been able to do is a workable but inelegant > kluge that looks more like Basic than Python. Is there a "Python Way" > of doing that? > > Thanks for any ideas. > > BAF From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 31 10:00:43 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 31 Jul 2002 14:00:43 +0000 Subject: small tkinter problem In-Reply-To: References: Message-ID: <200207311301.g6VD15004991@helios.gatwick.geco-prakla.slb.com> On Wednesday 31 Jul 2002 12:47 pm, Raimo Tuisku wrote: > On Wed, 31 Jul 2002 15:51:26 +0300, oberon wrote: > > File "D:\projects\oberon\mdbapp.py", line 21, in __init__ > > self.results = Listbox(frame, > > yscrollcommand=self.rescroll.set).grid(row=4,column=0,sticky=W+E,columnsp > >an=2) AttributeError: 'NoneType' object has no attribute 'set' > > The error message says it all: > > self.rescroll = Scrollbar(frame).grid(row=4,column=2) > > You set the return value of grid to self.rescroll which is none. IOW self.results = Listbox(frame,yscrollcommand=self.rescroll.set) self.results.grid(row=4,column=0,sticky=W+E,columnspan=2) binding the name self.results to the Listbox NOT the return value of the grid method of the Listbox will give you the desired result Regards Martin From hodroj at terra.net.lb Thu Jul 25 21:20:19 2002 From: hodroj at terra.net.lb (Gerald_Bustock) Date: 25 Jul 2002 18:20:19 -0700 Subject: Python NetBIOS/RPC module ? Message-ID: <83942ed5.0207251720.673c9bc4@posting.google.com> hi, is there any Python module that can do either win32 NetBIOS mecahnisms, or Unix's RPC/NFS..etc calls ? thanks in advance. From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 00:27:57 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 00:27:57 -0400 Subject: Preforked server in Python References: <3D1EB82C.1000501@awal.net.sa> Message-ID: <3D1FDA4D.9060700@removethisandallhyphens-o-n-e.net> Yes, if forked children are true children of the parent (PPID), socket descriptors can be copied from one to the other like a file-descriptor, on linux, and on windows, as an object handle... it gets ugly, but it should be possible - shared memory might be the easiest way to handle this, though. Fran?ois Pinard wrote: > [rayed] > > >>I am looking for module similar to SocketServer that prefork chlidren instead >>of forking on each request. >> > > I wonder. Is there a way to transmit opened sockets to pre-forked children? > > From rzantow at ntelos.net Sat Jul 20 09:44:36 2002 From: rzantow at ntelos.net (rzed) Date: Sat, 20 Jul 2002 09:44:36 -0400 Subject: Python Sets (no not those sets) References: <7f2b571b.0207191546.67583b88@posting.google.com> Message-ID: "Tim Randolph" wrote in message news:7f2b571b.0207191546.67583b88 at posting.google.com... > Check out: > > http://labs1.google.com/sets?hl=en&q1=Tim+Peters&q2=Fredrik+Lundh&q3=Alex+Ma rtelli&q4=Guido+van+Rossum&q5=&btn=Large+Set > > It's worth putting this URL back together if needed. > > Or go to: > > > http://labs1.google.com/ > Or just http://labs.google.com/ -- this is *wonderful* stuff, and I thank you for bringing it to my attention. -- rzed From mh at esh-online.de Mon Jul 15 10:39:48 2002 From: mh at esh-online.de (Michael Hoffmann) Date: Mon, 15 Jul 2002 16:39:48 +0200 Subject: could not import mod_python.apache Message-ID: Hi, I've the folowing Error when I try to run my pythonscript: make_obcallback(): could not import mod_python.apache. make_obcallback(): could not call init. [Mon Jul 15 16:12:46 2002] [error] [client 62.226.50.138] python_handler: make_obcallback returned no obCallBack! but httpd start is ok: [Mon Jul 15 16:14:54 2002] [notice] Apache/1.3.19 (Unix) (SuSE/Linux) mod_python/2.7.2 Python/2.0 mod_ssl/2.8.3 OpenSSL/0.9.6a PHP/4.0.6 mod_perl/1.25 mod_th rottle/3.0 mod_layout/1.0 mod_fastcgi/2.2.2 mod_dtcl configured -- resuming normal operations [Mon Jul 15 16:14:54 2002] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) The directives are: AddHandler python-program .py PythonHandler mptest PythonDebug on Options +ExecCGI the script ist: from mod_python import apache def handler(req): req.content_type = "text/plain" req.send_http_header () req.write ("Hello World!") return apache.OK any Idea????? Regards Michael From pinard at iro.umontreal.ca Mon Jul 8 11:39:49 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 11:39:49 -0400 Subject: stackless python In-Reply-To: References: Message-ID: [Fran?ois Pinard] > [Tim Peters] > > [...] Python's generators are between Icon's generators and Icon's > > co-expressions: [...] BTW, Neil Schemenauer had no trouble rewriting all > > "the usual" coroutine examples to use Simple Generators instead. [...] > Are these examples available for us to browse? Just a bit curious... Oops! I really meant the Python version of these examples, my message did not make this clear! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From claxtonr at beer.com Tue Jul 16 17:11:56 2002 From: claxtonr at beer.com (hejduk) Date: Tue, 16 Jul 2002 17:11:56 -0400 Subject: starting other programs from within python Message-ID: <20020716.171155.619290071.333@beer.com> Hi, I'm writing a small menu like application that I plan to have sitting on my desktop that I want to use to allow myself easy access to certain apllications. My problem has been finding the best way to start up an outside application from within python. Right now I'm using threads in the following manner: I obtain the path and then send it to the following function: def progStart(file): import thread from os import system def progStart(file): system(file) thread.start_new_thread(progStart, (file,)) However, when I monitor the memory usage of the interpreter it appears that when this outside application is closed that not all the memory resource is returned, ie: before: 7248 k during: 18624 k after: 12284 k I'm wondering if this is a problem, or whether the resources will be freed when there needed? If the outside app is another python program will another instance of the interpreter be started? In general what is the best way to start outside applications from something like my menu program? Thanks, From news at prana.eml.cc Fri Jul 26 02:37:13 2002 From: news at prana.eml.cc (Mahesh Padmanabhan) Date: Fri, 26 Jul 2002 06:37:13 GMT Subject: test (please ignore) Message-ID: From amuys at shortech.com.au Sun Jul 28 20:47:56 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 28 Jul 2002 17:47:56 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: <7934d084.0207281647.f0e4f11@posting.google.com> Carl Banks wrote in message news:... > Second, if you're going to do it right often, you might want to wrap > it up in a function like this: > > def sort_the_right_way (f, a): > aux = [ (f(x), x) for x in a ] > aux.sort() > a[:] = [ x for __, x in aux ] > > In which case, the temptation to use lambda returns: > > sort_the_right_way (lambda x:x[1], a) Indeed. I personally only find lambda helpful when I require a truely trivial function, swapping the order of a pair: lambda (x,y):(y,x); applying the second argument: lambda x,f:f(x); etc. Andrae Muys From achim.domma at syynx.de Sun Jul 7 05:09:36 2002 From: achim.domma at syynx.de (Achim Domma) Date: Sun, 7 Jul 2002 11:09:36 +0200 Subject: Total python embedding in a c/c++ app References: <3d27c9f9@dnews.tpgi.com.au> Message-ID: Hi, I have written some kind of Python Server Pages for IIS. The main code is a dll loaded by the IIS. This dll hosts a python interpreter, which allows the executed scripts to access my own C++ functionality via the usual server, request and response objects. Using boost.python V1 I have done the following steps: - implement your core functionality in C++ - use boost.python to create a module which provides classes, which allow you to access your C++ functionality - in your main program create the python interpreter - import your new module - create instances of the C++ classes developed to access the core functionality - add them to the current interpreter - then execute a python script The Script will now be able to call methods of your objects, which will execute code from your core functionality. You may look at boost.python (www.boost.org) for the C++ wrapping part. I have done all this with version 1, but version 2 will be release soon. Achim "tALSit" wrote in message news:3d27c9f9 at dnews.tpgi.com.au... > Damm... I'm just reading this email, and I realise that it makes very little > sense. Anyway, anyone that has totally embedded python into their system, I > would be extreemly gratefull to know how they went about doing it, thanks! From shalehperry at attbi.com Fri Jul 12 16:17:06 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 12 Jul 2002 13:17:06 -0700 (PDT) Subject: switch recipe? In-Reply-To: Message-ID: > > I appreciate your opinion and I mean and say this with respect: One of the > joys of Python is that even supposedly advanced tricks are eminently > explorable. I would rather not patronize someone and I'd rather make the > mistake of offering them too much than too little. Besides, even if they > can't get it, they're not the only ones reading this list now or in the > future. Ultimately, I can trace this sentiment back to something very > personal: That's precisely how I'd want to be treated. Wouldn't you? > > I mean, it's not like I vomitted some obscurified black hole of > context-laden punctuation (i.e., Perl) on them. > the template variable ...... >> Plus one letter variable names are a pain. > > I go back and forth on this one. Presumably, you don't mean for counters > and the like (e.g., i, n). I tend to use one-letter variable names when > locals() is very small, the function is short (e.g., 5-10 lines) and the > meaning is painfully obvious. Perhaps a bad habit? E.g., s, imho, is > better than text or string for a string. I'm not trying to save typing, so > much. I strive for clarity of intent at the level of module, class, > function names. So that I don't feel so bad using one-letter variable > names. But, reasonable people disagree and I enjoy seeing alternative > styles, discussing them. > I always seem to have a semi violent reaction when I see locals(). From sam at webslingerz.com Wed Jul 3 09:34:04 2002 From: sam at webslingerz.com (Sam Brauer) Date: Wed, 03 Jul 2002 09:34:04 -0400 Subject: Web templating/db tool with best designer/coder separation? References: <3d21259f$0$28006$afc38c87@news.optusnet.com.au> Message-ID: <3D22FD4C.4010000@webslingerz.com> My project "maki" offers somewhat similar functionality to Cocoon. http://maki.sourceforge.net/ If you're interested in using XSLT to separate layout/presentation from data/logic, and prefer Python to Java, it's worth a look. Jonathan Hogg wrote: > On 2/7/2002 5:00, in article 3d21259f$0$28006$afc38c87 at news.optusnet.com.au, > "Stephen Tyler" wrote: > > >>The other contenders for my "next-generation" web templating system >>typically use XSLT to transform a variety of XML inputs into XHTML output. >>But XSLT can be very obtuse for non-coders (and even coders). And it still >>needs to be supplemented with a general-purpose programming language. > > > Did anyone mention Cocoon yet in this thread? (I didn't follow the start) > > > > I think they've got a very interesting idea based on transforming XML. The > main feature of their model is "Separation of Concern" - enabling content > authors, designers, and programmers to all work independently. It's sort of > like JSP tag libraries, but in multiple layers. > > Jonathan > From nde at comp.leeds.ac.uk Wed Jul 10 06:33:31 2002 From: nde at comp.leeds.ac.uk (N D Efford) Date: Wed, 10 Jul 2002 10:33:31 GMT Subject: Learning how to program... but what's the best way? References: <3D2BB54C.90500@earthlink.net> Message-ID: Hans Nowak wrote: > To give an idea of what I have in mind: A good start could be, for > example, some kind of game that can be scripted in Python, and > therefore extended at will. The "student" could say, "I want the game > to do this-and-that", then proceed to implement it. Unfortunately, I > know of no such game, and have no time to write it <0.3 wink>. Pygame might be what you need - www.pygame.org > Besides this, does anyone have ideas about what would be a good > starting point Something with graphics - VPython or Alice for fancy 3D, or just stick with 2D turtle graphics using the standard turtle module... Nick From pecora at anvil.nrl.navy.mil Wed Jul 10 10:13:11 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 10 Jul 2002 10:13:11 -0400 Subject: Why self? References: <090720020820257031%pecora@anvil.nrl.navy.mil> <090720021359063518%pecora@anvil.nrl.navy.mil> Message-ID: <100720021013112946%pecora@anvil.nrl.navy.mil> In article , Fernando P?rez wrote: > > Hmmm...a pretty bizzare example or else I just don't have enough > > programming experience.??I've?never?done?anything?close?to?that.??I > > will have to rely on others experience (including yours, which I know > > is substantial).?? > > If you call that bizarre, I simply call it 'you hadn't thought of it yet'. Uh...that's what I said above. -- Lou Pecora - My views are my own. From loewis at informatik.hu-berlin.de Mon Jul 8 11:41:54 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 08 Jul 2002 17:41:54 +0200 Subject: Python 2.1 == Jython 2.1 != Python 2.2? References: Message-ID: sandeep182 at hotmail.com (Sandeep Gupta) writes: > Do Jython version numbers correspond to Python version numbers? Yes, roughly. > Should I expect any Python 2.1 application to run in Jython 2.1? No. If the Python application uses features that are not available in Jython, it will not run out of the box. > Should I expect Python 2.2 features in Jython 2.2? Yes. > If so, is there an ETA on Jython 2.2? What is an ETA? Regards, Martin From syver-en+usenet at online.no Mon Jul 29 20:34:12 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 30 Jul 2002 00:34:12 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: <5pt3ia.i7l2.ln@eskimo.tundraware.com> Message-ID: Tim Daneliuk writes: > Syver Enstad wrote: > > Tim Daneliuk writes: > > > >>On a related note, where in the docs are values for KEY_READ, > >>KEY_WRITE, > >> > >>and so forth, defined? I cannot seem to find these... > > Can't you just do _winreg.KEY_WRITE instead of bothering with the > > exact values? Or if you really want to know: print _winreg.KEY_WRITE > > > in a python console. > > > > It's not really the values I care about - I want to know all the > possible > > names that can go into the sam field... I use the msdn library for that purpose, with a little help from dir(_winreg) or just AttributeError's to see if any constants defined in the win32 api happens to not be available. -- Vennlig hilsen Syver Enstad From walter at livinglogic.de Tue Jul 2 18:19:51 2002 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 03 Jul 2002 00:19:51 +0200 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: <3D222707.6000601@livinglogic.de> Robert Kuzelj wrote: > hi, > > after playing around with all this metastuff it seems > that isinstance is broken (but after all it could also be, > that my brain finally broke down). > > here some script that checks for the instancetype of various > objects defined within that script. > > >>>>typestest.py >>> > import types > import string > > class metatype(type): pass > > class A1: pass > class B1(object): pass > class C1: __metaclass__ = metatype > > values = [ [A1, A1()], > [B1, B1()], > [C1, C1()]] > > def getInstanceInfos(row): > return [row[0].__name__, > str(isinstance(row[0], types.InstanceType)), > str(isinstance(row[0], types.ClassType)), > str(isinstance(row[0], types.TypeType)), > str(isinstance(row[1], types.InstanceType)), > str(isinstance(row[1], types.ClassType)), > str(isinstance(row[1], types.TypeType))] > > print > print "INSTANCEINFOS" > print " name | inst | class | type | inst | class | type " > print "-----------------------------------------------------" > for row in values: > print " " + string.join(getInstanceInfos(row), " | ") > >>>>typestest.py #end >>> > >>>>output >>> > INSTANCEINFOS > name | inst | class | type | inst | class | type > ----------------------------------------------------- > A1 | 0 | 1 | 0 | 1 | 0 | 0 > B1 | 0 | 0 | 1 | 0 | 0 | 0 > C1 | 0 | 0 | 1 | 0 | 0 | 0 > >>>>output >>> > > my question is why are the B1() and C1() not types.InstanceType? That's because types.InstancesType is the type of old style instances (and types.ClassType is the type of old style classes). The type of new style instances is their class. That's what new style classes were made for. > and if this is not a bug This is not a bug, it's one of the main features of new style classes. > of what type are B1() and C1()? B1 and C1. Bye, Walter D?rwald From whisper at oz.net Wed Jul 10 02:56:47 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 9 Jul 2002 23:56:47 -0700 Subject: Python tutorial In-Reply-To: <3d2bce0d.173491234@news.skynet.be> Message-ID: No Dutch Python? I'm _shocked__! ;-) As a consolation, please carefully read this page: http://www.montypython.net/scripts/bookshop.php David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of pixie888 at hotmail.com > Sent: Tuesday, July 09, 2002 23:05 > To: python-list at python.org > Subject: Re: Python tutorial > > > On Tue, 09 Jul 2002 21:38:07 GMT, "Emile van Sebille" > wrote: > > >Henk > >> Is there any Python tutorial out there which happens to be written in > >> Dutch? > >> > > > >Good question! It's well known that all good pythoneers speak dutch, > >but apparently not all write in it. > > > >I'm not sure how far this will get you, but I only found this one link: > > > >http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-vertaling.html > > > >Perhaps there's more? > > I found that link too, but it's not enough, thanks anyway. > > > > >-- > > > >Emile van Sebille > >emile at fenx.com > > > >--------- > > > > -- > http://mail.python.org/mailman/listinfo/python-list From andreas at kostyrka.priv.at Tue Jul 30 02:18:13 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 30 Jul 2002 08:18:13 +0200 Subject: text adventure game module for Python In-Reply-To: References: <7x1y9zmb31.fsf@ruckus.brouhaha.com> Message-ID: <1028009903.1316.12.camel@vaio2> Am Sam, 2002-07-20 um 10.22 schrieb Michael Bauers: > I understand a concern like that actually. > > I am not sure what a system like I am developing could do to avoid it > however. Well, it's trivial. There three categories of people here: 1) you; (makes the game module) 2) game writer; (makes a game) 3) player. Now 1+2 always can sabotage the system. But with the exec string, the player can do it also. Now you still can say the user could have done it anyway without starting a game. But consider say a web version. In this case some anonymous web user might execute arbitraty commands. not nice. Basically, instead of exec you should use rather something like this: objstr # is the object name as a string. obj=getattr(allobjects,objstr) # or: obj=globals()[objstr] In a further consideration you might ask yourself why you do exec at all? Why do you not define something like this: obj # is our object verb # is the verbstr cmd=getattr(obj,"cmd_"+verb,None) if cmd: cmd(verb,obj,....) else: output("I do not know how to do this.") This way every object can define which actions are sensible on it, and you can use inheritence to provide the implementation. (Just make mixin classes, and then define some classes like this:) class Bottle(Dropable,Drinkable,Throwable,Physical,...): pass objs.add(Bottle("blue bottle",location=redSalon) > Someone creating code for this system could do the same thing manually from > within their program whenever they wated to however. I do not see how the > environment I am creating makes it any easier for malicious code. It's about the game players, not the author. :) Andreas From tim.one at comcast.net Mon Jul 29 05:26:17 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 29 Jul 2002 05:26:17 -0400 Subject: Let's Talk About Lambda Functions! In-Reply-To: Message-ID: [Fredrik Lundh] > Guido can channel himself (or Tim will do it), but from what > I can tell, he's always said that the "mistake" was adding > something to the language that almost, but not completely, > works like lambdas do in other languages. I don't think so -- Guido isn't a fan of functional programming styles, and plain doesn't like lambda. Except, of course, when he uses it, which is always for trivial little function arguments, in accord with his oft-repeated claim that the functional gimmicks were never intended to be more than "minor conveniences" (which he later amended to "minor annoyances", after people started clamoring for more of the same). It's not that they don't work exactly the same way in Python as some people expect them to, it's more that programming styles based on composition of higher-order functions simply aren't in his vision of what programming in Python should be. > (lambda, map, filter, etc was contributed code) Change "etc" to "and reduce" and you've got the whole set. Those four were contributed by the same person, in one gulp. I don't think Guido has tried it, but he'd like Haskell much more than he'd like Scheme; e.g., listcomps "felt right" to him, while non-trivial maps and filters don't, and never will. > the really big usage problem (whether you knew lambdas > from other languages or not) used to be that they were a > real pain to use under the LGB scoping rule. with the intro- > duction of nested scopes, that problem no longer exists. Guido's not much of a fan of nested scopes, either, although I believe I've channeled evidence of minor flip-flopping on that. Indeed, by and large people seemed quite happy with the LGB rules *until* lambda got introduced. Then "scope whining" started for real. I expect he'll stay happy enough with lexical scoping until people start writing inscrutably nested monstrosities with it. Objects are Python's intended way to carry state, and Guido isn't a Paradigm-Neutral language designer (you know where to go if you want one of those). > to fix the other "mistake", some needs to come up with a > really great syntax (and get michael hudson to implement > it for them ;-). ideas are welcome. Well, I can channel that one: not bloody likely. If Guido's time machine wasn't in the shop for million-year warranty service, I expect Python wouldn't have any spelling of anonymous functions today. Note that toward the tail end of Guido's OSCON 2002 "State of the Python Union" keynote address: http://www.python.org/doc/essays/ppt/ [bottom link on the page] two language features are mentioned as being "failed experiments" that only compatibility prevents throwing away: `back ticks` lambda With subtle clues like that, channeling is easier than it looks . From aleax at aleax.it Sat Jul 20 16:02:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 20:02:28 GMT Subject: unloading imported modules References: Message-ID: xeon wrote: > Hi, > > Is it possible in python intepreter to unload imported modules? or are No. > there ways to refresh the loaded functions if ever the module is > updated, other than restarting the intepreter? reload(moduleobject) updates the module object. If you use statement import, that's all you need to do to "refresh the loaded functions" (unless you've bound other identifiers to the function objects). If you use statement from, you're SOL: from x import y DOES bind identifier y to object x.y, and after that there's no automatic refreshing. Solution: don't use statement from -- use statement import and be happy. Alex From peter at engcorp.com Mon Jul 8 19:32:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 19:32:14 -0400 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <3D2A20FE.25ACF186@engcorp.com> curt finch wrote: > > Our free web timesheet app is written totally in Python. > One of our competitors is saying the following > things about python to our customers. Help me make them > look stupid. Please? Which competitor? Please post a link to the information they've provided to your customers. If it's not online, please provide at least a link to their home page so we can check them out for ourselves. Many of the things in that list smell a lot like they're made up just for a troll. Is any of this actually true? -Peter From merkosh at hadiko.de Tue Jul 16 21:38:19 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Tue, 16 Jul 2002 18:38:19 -0700 Subject: problem with references References: Message-ID: In article , merkosh at hadiko.de says... > !>> cpy = copy.deepcopy(self.element) > try: > cpy.parse(f) > except ParseError: #reached maximum hits > .... > else: > if (): > self.value.append(cpy) > ... > I did "some" more debuging and came to a more precise result /question. The error is in the copy.deepcopy() call above, but the problem is somewhere else. The "element" class has a __deepcopy__() method which first makes a shallow copy of self.element and then deepcopies of each mutable instance variable. But, there is a problem with file objects. You can't pickle file objects, however each element as an attribute ".file" which takes up a file. The __deepcopy__() method, beeing aware that file objects cannot be copied, decided to set self.file to None. And *this* is my actual problem. Setting self.file to None automatically sets the source elements self.file (the one I'm making the copy from) to None - which is perfectly right, because up until now those two objects are shallow copies and refer to the same self.file objects. Some lines afterwards the copied element is tried to be parsed, fails, raises ParseError and is removed from the queue, leaving no trace of its deeds, but setting the file attribute of the elements left in self.value to None. Now how am I supposed to just create a new "variable space" instead of that shallow copy? All I need is a way to loosen the reference the shallow copy created. Please don't tell me that's not possible?! Thanks in advance Uwe From tundra at tundraware.com Mon Jul 29 03:10:02 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 29 Jul 2002 07:10:02 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: Tim Daneliuk wrote: > Tim Daneliuk wrote: > This is where I run into a problem. I am having a dickens of a time > figuring > out how to remove just a single value within a key. I cannot seem to find > the magic that allows editing of the lowest level leaf nodes of a registry > entry on an individual basis. If I try to treat them as *key* Python > grumbles > something to the effect that it cannot find that file at the OpenKey call. > If I try to use DeleteValue, I get permission denied even though I am > running > with Administrator privileges on a Win2K machine. Never Mind ;-( I just figured out that I was not setting the access control properly when I opened the key which is what was causing the access denied error. On a related note, where in the docs are values for KEY_READ, KEY_WRITE, and so forth, defined? I cannot seem to find these... -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From irmen at NOSPAMREMOVETHISxs4all.nl Mon Jul 22 17:08:01 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Mon, 22 Jul 2002 23:08:01 +0200 Subject: Sockets for a file References: Message-ID: <3D3C7431.60506@NOSPAMREMOVETHISxs4all.nl> Teja Sastry wrote: > I would like to know if we can create a unix socket for a file (like > we do in C or C++ with struct sockaddr_un) > I want to wait on a file in python and trigger some function if the > file gets some data written in it by another program. I'm not sure what you're trying to do, but Python allows you to use the select call on sockets and file objects (in fact, any object with a fileno() method). See the select module. BTW: this doesn't work on Windows. Irmen From mhammond at skippinet.com.au Wed Jul 3 19:22:20 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 03 Jul 2002 23:22:20 GMT Subject: COM component implementing custom interfaces References: <46585325.0207030824.7a22dfa1@posting.google.com> Message-ID: <3D2387EF.6020306@skippinet.com.au> Daniel Pi?ol Laserna wrote: > I tried to write a simple COM component with the code below. > I'm able to correctly instantiate from VB (createinstance), but when > trying to cast it to interface ICapeUnitEdit (QueryInterface( , it > always fails. > > any idea? You need to check out the win32com\servers\test_pycomtest.py - this shows how to implement non IDispatch based interfaces. Mark. From zeitlin at seth.lpthe.jussieu.fr Wed Jul 3 12:24:57 2002 From: zeitlin at seth.lpthe.jussieu.fr (Vadim Zeitlin) Date: Wed, 3 Jul 2002 16:24:57 +0000 (UTC) Subject: wxFont-question References: Message-ID: On Mon, 01 Jul 2002 15:53:15 +0200, Klaus Reinhardt wrote: > f=wxFont(22,wxTELETYPE,wxNORMAL,wxNORMAL,1) > f.SetFamily(wxTELETYPE) > > NO change. These 'things' seem to work, cause > I can test with GetFamily a.s.o. But the appearance > of the font is the same (pro letters). Where does this font appear? I.e. do you draw itself with it or use it with some other control? Regards, VZ -- GCS/GM d? H+ s++:-- p2 au--- a- w+ v C+++ UBLS+++ P- L++ N++ E--- W++++ M? V-- -po+ R++ G`` !tv b+++ D--- e++++ u++ h--- f+ r++ n- y? From aleax at aleax.it Mon Jul 15 15:38:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 15 Jul 2002 19:38:28 GMT Subject: uniform interface for MySQL & MSSQL References: Message-ID: Johann wrote: > I would like to write a hybrid application which works on Linux and > Windows platform so I need the same API for SQL (MySQL and MSSQL2K). I > would like to use Python Database API Specification v2.0 > (http://www.python.org/peps/pep-0249.html) and I found a nice > implementation such interface at > http://www.nmt.edu/tcc/help/lang/python/dbhelpers.html. The problem is > there is no mssql module, only sybase, oracle and mysql. I tried to Have you tried: http://www.object-craft.com.au/projects/mssql/ ? I haven't yet, and I don't think it's yet mature and complete, but it may be worth your while to try it. Alex From mhammond at skippinet.com.au Sun Jul 28 06:28:52 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 28 Jul 2002 10:28:52 GMT Subject: PythonWin ODBC: DSN-less connecting string References: Message-ID: <3D43C789.1080806@skippinet.com.au> Jimmy Retzlaff wrote: > The current odbc module in win32all doesn't support DSN-less > connections. A while back I submitted a patch to Mark Hammond to add > support for this - hopefully it'll make it into the next release of > win32all. Sorry :) I just checked that change in - thanks! If you could check the CVS version I would appreciate it. Regards, Mark. From msqrd at lanl.gov Tue Jul 30 18:17:47 2002 From: msqrd at lanl.gov (Michelle L. Murillo) Date: 30 Jul 2002 15:17:47 -0700 Subject: Embedding/API question Message-ID: <215127f6.0207301417.65343257@posting.google.com> Hi - I have successfully used PyArg_Parse and PyInt_AsLong to parse data from python into C. The data are being returned to C from a python script that does a look up into a dictionary. I can successfully return and print out an integer and a string. But what I can't figure out is how to get PyArg_Parse (or which ever API works) to correctly parse a python tuple - that is we have a value in the dictionary that is in the form of (8,8,8). If I make this a string all works fine - but with out the quotes all that is returned and printed out is garbage. Any ideas? TIA Michelle From raims at dot.com Sat Jul 20 11:32:38 2002 From: raims at dot.com (Rhymes) Date: Sat, 20 Jul 2002 17:32:38 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: On 20 Jul 2002 11:21:00 -0400, aahz at pythoncraft.com (Aahz) wrote: >Yes, it is, unless you're using some strange meaning for "built-in" far >removed from its normal meaning. sorry, "default" not "built-in" -- Rhymes rhymes at myself.com " ride or die " From spenrose at intersight.com Thu Jul 18 16:37:10 2002 From: spenrose at intersight.com (Sam Penrose) Date: Thu, 18 Jul 2002 13:37:10 -0700 Subject: pickle performance on larger objects Message-ID: <22204974-9A8E-11D6-B98C-003065B33450@intersight.com> > Sam Penrose writes: > > > memory usage increases by about 20%, FWIW. For my particular use case > > cPickle is still several (many ?) times slower than just recreating > > the object by reading in a file. Michael Hudson asks: > Are you sure that the file doesn't have an associated .pyc? For then > you're testing marshal perfomance, and that's always going to kill > pickle. Just a thought. Sorry, I wasn't clear. The file in question is a database dump; the object being created a class instance with a few attributes, including the list of dicts referred to in my original post. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 853 bytes Desc: not available URL: From pyth at devel.trillke.net Mon Jul 1 08:16:58 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 1 Jul 2002 14:16:58 +0200 Subject: Semi-static analysis (was Re: Partial Parsing of Python) In-Reply-To: <20020701090659.GA30807@luminance.reworld.org>; from pde@cs.mu.oz.au on Mon, Jul 01, 2002 at 07:06:59PM +1000 References: <20020629141507.GA6507@luminance.reworld.org> <20020630094833.B20310@prim.han.de> <20020701060124.GA9937@luminance.reworld.org> <20020701104513.E10625@prim.han.de> <20020701090659.GA30807@luminance.reworld.org> Message-ID: <20020701141658.H10625@prim.han.de> Peter Eckersley wrote: > [me] > > somestrangefile.read(). > > > A perfect example! > > If is a builtin file object, it should have a read() > method annotated as follows: > > pure == False (calling the method may cause side effects - do not > eval() it in vain!) > > return_type == types.StringType (so we know we can complete using normal string > methods) ah, i understand now what you mean by pure (i.e. no side-effects). My gut feeling tells me that we'd need some kind of static typing, although this horse has been beaten to death in the last years. In fact, specifying the return type might be sufficient. But what are good ways to do it (without changing the syntax)? - use a strict syntax in the first line of a doc string. Methods implemented in C sometimes have this, e.g. the os.kill function has "kill(pid, sig) -> None" as its doc string. - run unittests with a module and determine (by tracing function calls) return type(s). Store this information somewhere and make it accessable. - maintain a list of functions/objects which have serious side effects (ones that even hit you when running in a forked-off process: files, sockets, threads, what else?) > [me] > > Reflecting our EuroPython discussion, GTK or QT seems to be heavyweight. > > We don't need widgets but the ability to put scalable fonts on a screen. > > Having sprites and game-level performance can't hurt either :-) > > It's very worth a try. > > I don't know enough about GTK's implementation to know if it's efficient > at what it does (I was assuming it would be, but I could easily be > wrong). I've certainly found lots of the widget behaviour very useful, > but it might not be all that hard that hard to re-implement. Sorry for beeing unclear. We didn't think of reimplementing those widgets. The idea is to evolve the traditional *cmdline* interface without the burden of readline/curses. Do you know Mathematica? It mixes the cmdline with the display of (computed) graphics. It's more towards this direction than having a traditional GUI-IDE. holger From spenrose at intersight.com Wed Jul 17 18:07:38 2002 From: spenrose at intersight.com (Sam Penrose) Date: Wed, 17 Jul 2002 15:07:38 -0700 Subject: pickle performance on larger objects In-Reply-To: <61957B071FF421419E567A28A45C7FE514A5D1@MAILBOX.nameconnector.com> Message-ID: <9AEF2842-99D1-11D6-A291-003065B33450@intersight.com> Doh! That's what I get for reading the docs too quickly. With bin = 1: >>> time_cPickle_Load() dumping list of 10 dicts: dumped: 0.00358998775482 loading list of 10 dicts: loaded: 0.00386297702789 dumping list of 100 dicts: dumped: 0.0141079425812 loading list of 100 dicts: loaded: 0.0700759887695 dumping list of 1000 dicts: dumped: 0.188324928284 # ~ 2x speedup loading list of 1000 dicts: loaded: 0.379488945007 # ~ 20x speedup dumping list of 10000 dicts: dumped: 2.23442697525 # ~ 2x speedup loading list of 10000 dicts: loaded: 3.07298398018 # ~ 40x speedup memory usage increases by about 20%, FWIW. For my particular use case cPickle is still several (many ?) times slower than just recreating the object by reading in a file. What implications this has for best practices in persistence of larger objects I do not know, but I hope the data point is of interest to others. On Wednesday, July 17, 2002, at 02:13 PM, Geoffrey Talvola wrote: > Try using binary pickle format (pass in 1 as an extra third argument to > dump()). It's quite a bit faster both dumping and loading. > > - Geoff > >> -----Original Message----- >> From: Sam Penrose [mailto:spenrose at intersight.com] >> Sent: Wednesday, July 17, 2002 5:09 PM >> To: python-list at python.org >> Subject: pickle performance on larger objects >> >> >> On a recent project we decided to use pickle for some quick-and-dirty >> object persistence. The object in question is a list of 3,000 >> dictionaries >> whose keys and values are short (< 100 character) strings--about 1.5 >> megs worth of character data in total. Loading this object >> from a pickle >> using cPickle took so long we assumed something was broken. >> > From tilah78 at hotmail.com Fri Jul 19 14:16:30 2002 From: tilah78 at hotmail.com (Rafael Garcia) Date: Fri, 19 Jul 2002 14:16:30 Subject: Help!: Embedding python in a multithreaded application Message-ID: Hello. I'm working in a project in C++ in which I'm required to embed a python interpreter. For that I have made a python/C module that works as a wrapper to my c++ classes. The project is multithreaded and one of my C threads calls python code through the python/C API when some event occurs. When I execute my python scripts -that register a callback function for an event and call functions in my module that throw events- in my interpreter sometimes an exception that most of the time is "Fatal Python error: ceval: orphan tstate" is thrown. If I don't use the callback functions the scripts run well so the problem is in the way multiple threads access the python interpreter. I use the following snip of code (as readed in the documentation): void OnEventX(...) { PyThreadState *tstate; tstate = PyThreadState_New(mainThreadState->interp); PyEval_AcquireThread(tstate); PyObject *arglist; PyObject *result; arglist = Py_BuildValue(...); result = PyEval_CallObject(CallbackFunc_OnEventX, arglist); Py_XDECREF(result); Py_XDECREF(arglist); PyThreadState_Clear(tstate); PyThreadState_DeleteCurrent(); } There are more pieces of code like the later in my module, one for each event my system can throw. The global variable mainThreadState is a PyThreadState object that was filled using the function PyThreadState_Get() in the main() function in my program. Could you tell me what I'm doing wrong?. Is it a bug?. Could you tell me how should I make a multithreaded python interpreter? The documentation about this is very poor. I use version 2.2.1 Python binaries under Windows XP. I'm working with MS Visual C++ 6.0. Thanks for your attention. Rafael Garcia, tilah78 at hotmail.com From cce at clarkevans.com Thu Jul 4 18:41:00 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Thu, 4 Jul 2002 18:41:00 -0400 Subject: Calling stdlib functions from pyrex In-Reply-To: <20020704173445.A44106@doublegemini.com>; from cce@clarkevans.com on Thu, Jul 04, 2002 at 05:34:45PM -0400 References: <20020704173445.A44106@doublegemini.com> Message-ID: <20020704184100.A45006@doublegemini.com> On Thu, Jul 04, 2002 at 05:34:45PM -0400, Clark C . Evans wrote: | Hello. This pyrex stuff looks like a great tool. I tried to convert | the module that I just posted recently, but I ran into a bit of | difficulty... here is my error message: | | pyrexc tztool.pyx | Unpickling lexicon... | Done (0.11 seconds) | gcc -c -fPIC -I/usr/local/include/python2.2/ tztool.c | tztool.c:21: redefinition of `struct tm' | tztool.c:35: conflicting types for `setenv' | /usr/include/stdlib.h:123: previous declaration of `setenv' The problem seems to be that the generated code makes type declarations. Is there a way to shut this feature off? When I go into the generated .c file and delete the declarations everything is happy... Great product BTW, I just converted a few other modules to use pyx without a hitch. What is superb is that I can have one .pyx file mixing my .c and my .py stuff instead of having two files. This is just outstanding. Now we just need to get the python build system to grok .pyx files! Clark P.S. I had _one_ a bug in tztools.pyx (the fact that I could read the instructions and only have one bug on the first compile is just great... your documentation is very good). | ctypedef long time_t | cdef extern struct tm: | int tm_sec | int tm_min | int tm_hour | int tm_mday | int tm_mon | int tm_year | int tm_wday | int tm_yday | int tm_isdst | long tm_gmtoff | char *tm_zone | cdef extern void setenv(char *key, char *val, int override) | cdef extern void unsetenv(char *key) | cdef extern void tzset() | cdef extern int time(time_t *junk) | cdef extern tm * localtime_r(time_t *now, tm *fill) | | def offset(zone): | cdef time_t now | cdef tm a setenv("TZ",zone,1) | tzset() | now = time(0) | localtime_r(&now, &a) | unsetenv("TZ") | tpl = (a.tm_zone,a.tm_gmtoff/60) | tzset() | return tpl From larry.tami at gte.net Fri Jul 26 23:22:55 2002 From: larry.tami at gte.net (Larry Wright) Date: Sat, 27 Jul 2002 03:22:55 GMT Subject: Developers needed References: <3D41A38F.2030106@users.sourceforge.net> Message-ID: This is a nice idea, but where is the project?? Volker Cordes wrote: > Hi, > > I started a project on sourceforge that you might be interested in: > Goal of the project is to develop a python plugin for eclipse > (www.eclipse.org). > At the moment the project is still in an early state. I have some > pre-alpha sourcecode but I need help. So if you are interested and have > some knowledge in programming java-classes you're welcome to join. > > Hope to see you, > Volker From guido at python.org Wed Jul 24 20:04:51 2002 From: guido at python.org (Guido van Rossum) Date: Wed, 24 Jul 2002 20:04:51 -0400 Subject: Powerpoint slide for keynotes available Message-ID: <200207250004.g6P04pP20522@pcp02138704pcs.reston01.va.comcast.net> I've put the powerpoint slides for my keynotes at EuroPython and OSCON on the web. If someone can donate PDF that would be great (the HTML generated by Powerpoint sucks too much to be worth it IMO). http://www.python.org/doc/essays/ppt/ (scroll to end) --Guido van Rossum (home page: http://www.python.org/~guido/) From rjones at ekit-inc.com Thu Jul 4 20:19:36 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 5 Jul 2002 10:19:36 +1000 Subject: Math irregularity ... is this normal? In-Reply-To: References: Message-ID: <200207051019.36316.rjones@ekit-inc.com> On Fri, 5 Jul 2002 10:10 am, Some One Else wrote: > Hello! > > I just compiled and installed Python 2.2.1 on Linux-Mandrake 8.0. When I > > do the following: > >>> 2/5.0 > > 0.40000000000000002 > > In 'Learning Python', a similar example says I should get the more logical > answer of 0.4. Did I install something wrong? I can see where this could > result in creeping math errors. Yes, this is normal :) http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp Richard From sholden at holdenweb.com Sat Jul 27 00:48:01 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:48:01 -0400 Subject: PythonWin ODBC: DSN-less connecting string References: Message-ID: "Jimmy Retzlaff" wrote in message news:mailman.1027727437.25355.python-list at python.org... > Gabe Newcomb [mailto:Gabe.Newcomb at noetix.com] wrote: > > I'm unable to find the right combination of options to build a DSN-less > > connection string with which I can connect to a database using the odbc > > module. Has anybody out there found the right way to do this? > The current odbc module in win32all doesn't support DSN-less > connections. A while back I submitted a patch to Mark Hammond to add > support for this - hopefully it'll make it into the next release of > win32all. > In the meantime I'd be happy to send a copy of my patched odbc.pyd > compiled for Python 2.2/2.2.1, or I can also send odbc.cpp if you'd like > to compile it yourself for another version of Python. Note, however, that the ODBC documentation inludes teh following gem: """ DriverConnect(DSN_string, clear_auto_commit=1, errorhandler=None) This constructor returns a connection object for the given datasource which is managed by an ODBC Driver Manager (e.g. the Windows ODBC Manager or iODBC). It allows passing more information to the database than the standard Connect() constructor. """ You might want to consider mxODBC if the licensing doesn't put you off. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From jdhunter at ace.bsd.uchicago.edu Mon Jul 29 10:32:20 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 29 Jul 2002 09:32:20 -0500 Subject: DIV and MOD In-Reply-To: <5.1.1.6.0.20020729112008.009fa0c0@imap.datacraft.com.br> (Marcus Vinicius Laranjeira's message of "Mon, 29 Jul 2002 11:21:47 -0300") References: <5.1.1.6.0.20020729112008.009fa0c0@imap.datacraft.com.br> Message-ID: >>>>> "Marcus" == Marcus Vinicius Laranjeira writes: Marcus> I need to use some function like DIV (returns the integer Marcus> part of a division) and MOD (returns the reminder of a Marcus> division) in python, but I don't know how to do that. % Marcus> does not work as expected (in this context) and in the Marcus> MATH module, I didn't find any kind of function to do such Marcus> thing. When you say it did not work as expected, what did you want, what did you try, and what did you get? Assuming you are working with integers/longs, then >>> i = 13 >>> j = 5 >>> i/j # DIV 2 >>> i%j # MOD 3 Note that in future pythons, The / operator will no longer be integer (floor) division. See http://www.python.org/peps/pep-0238.html. John Hunter From news-and-lists at the-me.de Mon Jul 29 05:45:17 2002 From: news-and-lists at the-me.de (Axel Bock) Date: Mon, 29 Jul 2002 11:45:17 +0200 Subject: python class question References: Message-ID: On Fri, 26 Jul 2002 23:27:23 +0200, Jonathan Hogg wrote: > On 26/7/2002 18:32, in article ahs0to$v8ku5$1 at ID-138381.news.dfncis.de, > "Axel Bock" wrote: > > Well just put the code you originally wrote into a method something like > so: > > def getDB( self ): > dbc = getattr( self, self.connection ) DB = dbc() > return DB > > Then use this in your methods when you need to talk to the database: > > def doSomething( self, withThis ): > DB = self.getDB() > result = DB.query( withThis ) > return result.getOne() > > or something along those lines. > > I'm not sure I quite understand what you're trying to do in the first > place though. Isn't the point of Zope that it manages the database for you > and provides an object persistence mechanism? I'm not sure what I'm doing either ;-)), but as long as it works I really don't care right now :-)) But thaks for that tip, this is like I do it right now. Greetings and thanks, Axel. From joju at ncst.ernet.in Tue Jul 23 07:51:18 2002 From: joju at ncst.ernet.in (Jojumon Kavalan) Date: 23 Jul 2002 04:51:18 -0700 Subject: KBCS-2002 Call for Papers - Deadline Extended to Aug.31, 2002 Message-ID: <4754df2b.0207230351.4db27d7a@posting.google.com> . KBCS-2002 INTERNATIONAL CONFERENCE ON KNOWLEDGE BASED COMPUTER SYSTEMS Mumbai, India, December 18 - 21, 2002 http://www.ncst.ernet.in/kbcs2002 Call for Papers: Deadline Extended to August 31 +++++++++++++++++++++++++++++++++++++++++++++++ Note: ================================================================ The deadline for paper submission to KBCS2002 has been extended to August 31, 2002. International authors, please note that the travel advisory for India by the US Department of State and the UK Foreign and Commonwealth Office has been relaxed. KBCS is the premium International AI Conference held in India. Don't miss out on it! ================================================================ The KBCS series of conferences, held every two years, is intended to act as a forum for promoting interaction among researchers in the field of Artificial Intelligence in India and abroad. The schedule includes a three-day conference on KBCS from Dec 19-21, and one day of tutorials, on the 18th. Papers are invited on substantial, original and unpublished research on all aspects of Artificial Intelligence, including, but not limited to those given below. This year, ICON-2002, International Conference on Natural Language Processing, will be held concurrently with KBCS-2002. Authors may, therefore, choose to submit papers focusing on Natural Language Processing (NLP) to ICON-2002. KBCS-2002 will also consider NLP papers provided they have substantial AI content. The programme committee may shift some papers between these two conferences based on content and suitability. Topics for the Conference: -------------------------- Case Based Reasoning Cognitive Modelling Data Mining Expert Systems Foundations of AI Fuzzy Logic Genetic Algorithms Intelligent Agents Intelligent Tutoring Systems Knowledge Acquisition Knowledge Representation Knowledge Management Intelligent Information Retrieval * Machine Learning Machine Translation * Natural Language Processing * Neural Networks Planning and Scheduling Reasoning Robotics Search Techniques Soft Computing Speech Processing Theorem Proving Uncertainty Handling Vision * overlapping areas with ICON Format of Submission: --------------------- Papers should be in English, not exceeding 5000 words (including figures and references). Papers should include an abstract of about 100-200 words. Papers outside the specified length are subject to rejection without review. Since reviewing will be "blind", the authors' names and affiliations along with the main area of the paper should be given only on a separate cover sheet. Authors should also exercise care to see that there aue no indirect clues to the identity of the author or the institution (e.g. self-citations reading 'in our earlier work cited below' ... etc) Submissions should be in electronic form and can be in any of the following formats: PDF, Latex or Microsoft Word (RTF format). Papers may be submitted by E-mail or via the web at the URL given. Those who are unable to make electronic submissions may send four hard copies of the paper. Papers selected for the conference will be published in the proceedings. Call for Tutorials: ------------------- Proposals are invited for conference tutorials. Tutorials can be of half-day or full-day duration. The proposal should be presented in the form of a 200-word abstract, one page topical outline of the content and bio-data of the speakers, including their qualifications relating to the tutorial content. Submission Deadlines: --------------------- Papers Due: August 31, 2002 Acceptance Notification: October 10, 2002 Camera Ready Copy Due: November 5, 2002 Tutorial Proposals Due: August 31, 2002 Acceptance Notification: September 15, 2002 Materials Due: November 25, 2002 Address: -------- KBCS-2002 Secretariat National Centre for Software Technology Gulmohar Cross Rd No. 9 Juhu, Mumbai 400 049, India Phone: +91-22-6201606 Fax: +91-22-6210139 E-mail: kbcs at ncst.ernet.in For ICON-2002: http://www.iiit.net/conferences/icon2002.html E-mail: icon2002 at iiit.net Advisory Committee: ------------------- Nick Cercone, University of Waterloo, Canada J.R. Isaac,Professor Emeritus, IIT Mumbai Aravind K. Joshi, U of Pennsylvania, USA H.N. Mahabala, Indian Inst. of IT, Bangalore R. Narasimhan, CMC, Bangalore P.V.S. Rao, Tata Infotech Ltd., Mumbai Programme Committee: -------------------- K.S.R. Anjaneyulu, ESN Tech Ltd., Hyderabad Vivek Balaraman, TRDDC, Pune Pushpak Bhattacharya, IIT Mumbai PP Chakraborti, IIT Kharagpur B.B. Chaudhuri, ISI, Calcutta R. Chandrasekar, Microsoft, USA S. Kambhampati, Arizona State Univ, USA M. Narasimha Murty, IISc, Bangalore Bernd Neumann, Univ Hamburg, Germany Arun K Pujari, Univ of Hyderabad, Hyderabad S. Ramani, HP India, Bangalore P.V.S. Rao, TataInfotech, Mumbai (Chair) Durgesh D. Rao, NCST, Mumbai P. Saint-Dizier, U of Paul Sabatier, France K. Samudravijaya, TIFR, Mumbai R. Sangal, IIIT, Hyderabad M. Sasikumar, NCST, Mumbai (Co-chair) S. Sen Gupta, Tata Infotech, Mumbai R. Uthurusamy, GMR Labs, USA (Co-chair) From opengeometry at NOSPAM.yahoo.ca Tue Jul 9 11:49:46 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 9 Jul 2002 15:49:46 GMT Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: William Park wrote: > Found it! > > For those of you who need to set system clock only periodically, say once a > day, here are methods that are available: > > 1. Network Time Protocol (RFC-1305, port 123): > ntpdate time.nist.gov ... > > 'ntpdate' is part of standard NTP package on any Linux distribution. > > 2. Time Protocol (RFC-868, port 37): > netdate time.nist.gov ... > > Slackware includes 'netdate' as part of base TCP/IP package. You can > use 'rdist' from I meant 'rdate'... a typo. > ftp://ibiblio.org/pub/Linux/system/network/misc/ > but it is now deprecated in favour of 'netdate'. > > 3. Daytime Protocol (RFC-867, port 13): > date -u -s `telnet time.nist.gov 13 | grep UTC | cut -f2,3 -d' '` > > This is shell solution that I've been after. > > Of course, one the system clock is set, you can set the CMOS clock by > hwclock --systohc -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From mrlogic at users.sourceforge.net Sat Jul 27 06:37:40 2002 From: mrlogic at users.sourceforge.net (Volker Cordes) Date: Sat, 27 Jul 2002 12:37:40 +0200 Subject: Developers needed References: <3D41A38F.2030106@users.sourceforge.net> Message-ID: <3D4277F4.8030909@users.sourceforge.net> Hi, the project page is http://sourceforge.net/projects/pythoneclipse. Volker From smst at bigfoot.com Mon Jul 8 11:37:17 2002 From: smst at bigfoot.com (Steve Tregidgo) Date: 8 Jul 2002 08:37:17 -0700 Subject: metaclass & __slots__ References: Message-ID: phoebe_1 at att.net (Holden Caulfield) wrote in message news:... > class MX(type): > def __init__(cls,name,bases,dict): > super(MX,cls).__init__(name,bases,dict) > props = {} > slots = getattr(cls,'__slots__', []) > print slots > for v in dict.keys(): > vs = v.startswith > if vs("_get_") or vs("_set_"): > props[v[5:]] = 1 > for v in props.keys(): > fget = getattr(cls,"_get_%s" % v, None) > fset = getattr(cls,"_set_%s" % v, None) > setattr(cls,v,property(fget,fset)) > slots.append("_%s__%s" % (name,v)) > setattr(cls,'__slots__',slots) Holden, Others have commented on all the groovy metaclass stuff (which I am at last coming to terms with); I just wanted to point out something I presume to be a typo in the above code (maybe not in your original, but in the version I see posted, and which therefore others may be using). The indentation of the 'slots.append' line is such that the statement falls outside of the preceding 'for' loop. In the example that you gave, this would not have shown up whilst running the code. It so happens that in the case where get/set methods exist for exactly one property, the above code will work as expected (since the 'for' loop is iterated over just once, and therefore upon finishing the local name 'v' will be set to the only property). However, if two or more properties are defined then only one of them will have the munged name added to the slots list (whichever ended up being last in 'prop.items()'). If no properties are defined, I would expect the code to fail with a NameError (probably an UnboundLocalError actually). Apologies if the indentation error is an artifact of copying from editor to mail package; otherwise, consider this a pre-emptive attempt to answer your next question . Cheers, Steve -- Steve Tregidgo From jcc at ibdosnorte.com Mon Jul 8 05:50:16 2002 From: jcc at ibdosnorte.com (=?ISO-8859-1?Q?Juan_Carlos_CORU=D1A?=) Date: 8 Jul 2002 02:50:16 -0700 Subject: Message Queueing Message-ID: Hi all, I'm new to this group but not to python. I'm testing different solutions to implement message queueing between Zope (http://www.zope.org), that is written in python, and the Navision ERP (http://www.navision.com), that supports COM (I will try to develop a Visual Basic dll to interface with the selected message queueing system). So, I need a message queueing system with bindings to python and visual basic/COM. At the moment I have checked the following MOMs: - Spread (http://www.spread.org): Does not implement message queueing. Active project. - Open3 (http://www.open3.org): Does not have python bindings yet and uses JMS that is very complicated. No news on their web since January, is it active? - Isectd (http://pweb.netcom.com/~tgagne/index.html): Does not implement queues, and seems to be not very active. Not visual basic/COM bindings. - Jabber (http://www.jabber.org): queues? - MUSCLE (http://www.lcscanada.com/muscle/index.html): Does not support queueing. Does not have Visual Basic/COM bindings. Active project. - OpenQueue (http://openqueue.sourceforge.net/): Last update on July, 2000. - OSE (http://ose.sourceforge.net/): Only libraries. Must make a big effort to implement such a solution. - SwiftMQ (http://www.swiftmq.com/): uses JMS, not open source. - XMLBlaster (http://www.xmlblaster.org/): uses CORBA and xml-rpc. I tested it some time ago with poor results. Maybe someone can give me a better opinion. - XmlMom (http://www.xmlmom.org/): Young project. Last update May. Robustness? I tried to test it, but since it requires a lot of third party libraries, that I must install apart, I gave up. Maybe, someone can tell me about this program. In my opinion, Open3, XmlMom and XMLBlaster are the best options. I have tested Open3 and developed some programs in python that implements part of JMS, since Open3 uses JMS. And, now before continuing the development of the python bindings to open3, since it implies to create a JMS implementation in python, I like to hear the opinions of people in the same situations. From gerhard.haering at gmx.de Tue Jul 9 09:45:15 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 15:45:15 +0200 Subject: Table Widget (without Installation) In-Reply-To: <200207091534.21993.b.maryniuk@forbis.lt> References: <3D2A9948.5090304@thomas-guettler.de> <3D2AE4D9.3060104@thomas-guettler.de> <200207091534.21993.b.maryniuk@forbis.lt> Message-ID: <20020709134515.GA17563@lilith.my-fqdn.de> * Bo M. Maryniuck [2002-07-09 15:34 +0200]: > On Tuesday 09 July 2002 15:27, Thomas Guettler wrote: > > wxPython is very nice on win32. I tried once to build the latest > > version for linux, but failed. > > Since I use _German_ SuSE Pro Linux (suitable for you especially), it *really* > works. Trust me. Let's be honest. wxWindows and wxPython be problematic to build on Unix. But it's all solvable with actually reading INSTALL.txt and BUILD.unix. People on the wxpython users' list will be happy to help with build problems, should problems arise. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dmitri.gouliaev at telkel.net Mon Jul 8 02:52:26 2002 From: dmitri.gouliaev at telkel.net (Dmitri I GOULIAEV) Date: Mon, 8 Jul 2002 01:52:26 -0500 Subject: Linux clock-setting script In-Reply-To: <7x7kk691g0.fsf@ruckus.brouhaha.com>; from "Paul Rubin" on Sun, Jul 07, 2002 at 11:30:07PM References: <7x7kk691g0.fsf@ruckus.brouhaha.com> Message-ID: <20020708015225.A16118@lifebook> Hi, Paul Rubin ! On Sun, Jul 07, 2002 at 11:30:07PM -0700, Paul Rubin wrote: > "David LeBlanc" writes: > > No, the ftp site I pointed to has a simple client in C - admittedly with > > some "windowisms" for setting the cmos clock on a PC mobo (which might > > translate pretty directly over to linux). It's spread over several files and > > looks to be about 20kb total of c source. > > Yeah, that's what I mean. I'd rather have 10 lines of Python than > 20kb of C. Or you can have just one line of shell command, like # ntpdate host which is (most probably) already in your distribution. Do you have it in your distribution ? (just curious) Best regards, -- DIG (Dmitri I GOULIAEV) From mgilfix at eecs.tufts.edu Fri Jul 26 18:34:27 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 26 Jul 2002 18:34:27 -0400 Subject: Let's Talk About Lambda Functions! In-Reply-To: <7x3cu6f8sv.fsf@ruckus.brouhaha.com>; from phr-n2002b@NOSPAMnightsong.com on Fri, Jul 26, 2002 at 03:01:20PM -0700 References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> <7x3cu6f8sv.fsf@ruckus.brouhaha.com> Message-ID: <20020726183427.D10773@eecs.tufts.edu> If it were the case that 'arbitrary code' could be truly 'lambdafied', wouldn't it be safe to say that arbitrary code could then be pickled as well? While I know GVR designed like lambda in themselves, even if functions definition could have a true lambda property, that might be rather beneficial... -- Mike On Fri, Jul 26 @ 15:01, Paul Rubin wrote: > I agree that the current incarnation of lambda is deficient. I > think it should be strengthened so you can lambdafy arbitrary code, > not eliminated. The current version is better than nothing, though. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From list-python at ccraig.org Mon Jul 8 01:22:21 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 08 Jul 2002 01:22:21 -0400 Subject: structs in python In-Reply-To: <20020706231200.A25295@arizona.localdomain> References: <20020706231200.A25295@arizona.localdomain> Message-ID: "Kevin O'Connor" writes: > What if a syntax like the following were permitted: > >>> p = ( .x = 10, .y = 11, .color = 'blue') > >>> print p.x > 10 > >>> Why don't you just use a dict? >>> p = {'x'=10, 'y'=11, 'color'=blue} >>> print p['x'] 10 >>> -- Christopher A. Craig "Going to school make a person educated, any more than going to a garage makes a person a car" Slashdot From aleax at aleax.it Fri Jul 19 06:41:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 19 Jul 2002 10:41:35 GMT Subject: PDF creating again! References: <3D37D1A9.1030909@weknowthewayout.com> Message-ID: Johan Holst Nielsen wrote: > interested in TKinter but I can ony use bitmaps font, and I need Type1 > fonts at least (maybe other too). > > Isn't there any kinds of libraries that can do this for me? Output have > to be PS or PDF... http://www.reportlab.com/toolkit/index.html Alex From see_reply_address at something.invalid Thu Jul 4 21:36:08 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 13:36:08 +1200 Subject: replacing instance __setattr__ References: Message-ID: <3D24F808.3090908@something.invalid> Tim Peters wrote: > The notion that data attributes are attached to instances while methods are > attached to classes isn't unique to Python. Smalltalk, for example, where methods and instance variables are utterly different things, and methods are always looked up in the instance's class (doing anything else wouldn't even make sense). It's the way that old-style Python classes blurred this distinction that has been responsible for much of the complexity and confusion during the old-to-new-syle transition that we're now in the midst of. Hopefully, when old-style classes go away altogether, things will become simpler and more consistent. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pete at shinners.org Thu Jul 25 12:30:15 2002 From: pete at shinners.org (Pete Shinners) Date: Thu, 25 Jul 2002 16:30:15 GMT Subject: Speed up Python by up to 5% ? References: Message-ID: <3D4027BE.4000809@shinners.org> Edward K. Ream wrote: > 18686 LOAD_FAST > 14276 SET_LINENO > 9635 LOAD_CONST > 9555 POP_TOP > 6721 LOAD_GLOBAL ** > 5890 CALL_FUNCTION ** > ... > total 96454 > > ** denotes "heavy hitter" > > Dynamic execution frequencies will not match these static frequencies > exactly, but I see no reason to suppose they will be wildly different. If > anyone has real dynamic data, I would like to see it :-) i was always under the impression that some sort of "layered" switch statement could speed up execution. basically put the most frequent opcodes inside the toplevel switch. then a section of regular opcodes, and finally falling down to a switch statement with the rare opcodes. switch(opcode): { COMMON: default: switch(opcode) { REGULAR: default: switch(opcode) { RARE: } } } of course, some fine tuning might be required to get the most out of this, but it seems like an easy enough change? (maybe one day i'll bunker in and go for it). i'm guessing that further sampling of "dynamic execution frequencies" would tell what opcodes are most likely to go in which switch statement. on the other hand, it's probably a pretty sensitive thing inside the bytecode processor. little changes can likely have unconsidered consequences. From syver-en+usenet at online.no Sat Jul 20 11:43:24 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sat, 20 Jul 2002 15:43:24 GMT Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> <918bc22f.0207200441.7a5a130d@posting.google.com> Message-ID: donnal at donnal.net (Donnal Walter) writes: > > Yes, it's all very confusing to me. I love unit tests, but I've been > unable to grok the API for TestSuites. Let's say I have a module named > > "cell.py" and a corresponding test module "unit.cell_unit.py" with the > > following code: > > import unittest > from cell import Cell > > class Test(unittest.TestCase): > > def test1(self): > x = Cell() > self.failUnless(isinstance(x, Cell)) > > def test2(self): > assert_(1 != 2) > > if __name__ == '__main__': > unittest.main() > > This is just as Peter suggested above, and I can run this unit test > from the command line just fine. But, now let's say that I want to > make it part of a test suite by adding the following code to cell.py: > > if __name__ == '__main__': > import unittest > import unit.cell_unit > ts = unittest.TestSuite() > ts.addTest(unit.cell_unit.Test()) > unittest.TextTestRunner().run(ts) > > Now I get the following error: > ValueError: no such test method in unit.cell_unit.Test: runTest > > unless I add a runTest definition to cell_unit.Test: > > def runTest(self): > self.test1() > self.test2() > . > . > . > > Somehow I don't think this is how it was intended to be used, but so > far it is the only way I can figure out to make it work. Can anyone > tell me what am I doing wrong? The derived TestCase class works as follows, if you instantiate it without any arguments to the ctor it will run setUp (if it exists) then run the method runTest (which doesn't exist in your case) and then run tearDown (if it exists). If you want to build you're own TestSuite with all methods prefixed with test, you can do like this: suite = TestSuite() suite.addTest(unit.cell_unit.Test('test1')) suite.addTest(unit.cell_unit.Test('test2')) There is a TestLoader class (or hierarchy I can't remember) in unitttest.py that will do this automagically for you by introspecting your module and sucking out all TestCase derived classes and building TestSuite objects with all 'test' prefixed methods. As for me I just put: if __name__ == '__main__': unittest.main() In the bottom of my module and I can just run the module and it will be done for me. -- Vennlig hilsen Syver Enstad From shagshag13 at yahoo.fr Mon Jul 22 09:25:45 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 22 Jul 2002 15:25:45 +0200 Subject: how to delete or change... Message-ID: hello, i'm looking for the easiest way to delete or change last n character(s) of a text file. (i must avoid using a temp file - i had many huge files not enough place left, and can buy new hdd ;o) thanks, s13. (ps : i was thinking of some kind of open in rwb, seek at end, write new char once at a time, but i get a i/o error) From nospam at bigfoot.com Tue Jul 30 08:36:39 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 30 Jul 2002 14:36:39 +0200 Subject: ICQ package anywhere ? Message-ID: Hi, I'm actually building a monitoring system that sends mail alerts to sysadmins. I'd like to add ICQ messages and didn't find python packages (google, parnassus, sourceforge) to send alerts to ICQ recipients. Any hint ? Thanks in advance ! --Gilles glenfant AT bigfoot DOT com From olc at ninti.com Fri Jul 5 20:16:02 2002 From: olc at ninti.com (Michael Hall) Date: Sat, 6 Jul 2002 09:46:02 +0930 (CST) Subject: HTMLgen module Message-ID: I'm wondering which version(s) of HTML that the HTMLgen module supports. The website (last updated 1999?) mentions up to 3.2. Does anyone know if HTMLgen is still being maintained? I'm interested in something like HTMLgen that produces XHTML compliant code and has good support for CSS stylesheets and Javascript (i.e. supports name attributes on elements). Anything out there? Thanks -------------------------------- Michael Hall ninti at ninti.com -------------------------------- From msachet at hotmail.com Tue Jul 16 07:28:54 2002 From: msachet at hotmail.com (Marc) Date: 16 Jul 2002 04:28:54 -0700 Subject: How to get the list of the current system process under W2K ? Message-ID: Thanks In advance !! Marc From none at nospam.org Mon Jul 15 14:20:21 2002 From: none at nospam.org (Frank Fejes) Date: Mon, 15 Jul 2002 13:20:21 -0500 Subject: python2 import trouble (linux - redhat) References: Message-ID: On Sun, 14 Jul 2002 13:17:57 -0500, Mike Mellor wrote: > Hello - > > I am using RH7.2, and have the following python packages installed: > [...] > > I am having trouble importing modules with python2 (Python 2.2) that I > think should be there, for example, _gtk and GTK. What do I need to do > to get python (actually python2) to import these modules? Personally, I just delete all the python2-related packages and dependencies from RedHat 7.3 and then build all the python/gtk/mysql/etc. tools from source myself. It's more work initally, but at least you know exactly where you stand. --frank From dyoo at hkn.eecs.berkeley.edu Mon Jul 15 01:47:10 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 15 Jul 2002 05:47:10 +0000 (UTC) Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: Fredrik Lundh wrote: : ppcdev wrote: :> i was working on an old pentium II and wanted to send a very long :> string in the USER parameter but it made my computer bug.. is it :> normal??? :> :> str='a'; r=range(1024); :> for x in r[:]: :> str=str+str The code here is saying "double the length of 'str' on every iteration." This is usually not a good thing to do. *grin* But if we want your string to be of length 1024, and we want to construct the string with a loop, we'll can do the loop about lg(1024) times: ### >>> str = 'a' >>> for i in range(10): ... str = str + str ... >>> len(str) 1024 ### Notice here that we can avoid using variable names for values that we use in Python. That is, we don't need to say: r = range(10) before using a range of length 10: we can plug that 'range(10)' in "in-place" in our for loop statement, since that's probably the only place that will use it. But an alternative way of building that 'aaaa...' string, as the others have mentioned, is to avoid using a loop and to use string multiplication instead. This is probably a better solution for your problem. Hope this helps! From m.faassen at vet.uu.nl Tue Jul 2 08:41:29 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 2 Jul 2002 12:41:29 GMT Subject: Newbie: Zope Formulator TALES question References: <3D214E86.6070908@LarryCurlyMolingo.com> Message-ID: Kevin Chambers wrote: > I'm trying to use the Formulator TALES functionality to change the default > value of a field object for every record in an sql result set that I'm looping > through with tal:repeat. Just putting in this_record/FirstName, as I would do > in tal:attributes="default this_record/FirstName", doesn't work. I've also > tried variations on python:here['FirstName'] with no luck. > Is there any way to get this to work, or should I just make my own fields to > get this kind of functionality? This is not really the right forum to ask this question; try the Formulator mailing list: http://lists.sourceforge.net/lists/listinfo/formulator-general Anyway, changing the default you wouldn't usually do with the TALES tab at all, instead just pass an argument from the code that renders the fields: is the most simplest case of that. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From bokr at oz.net Thu Jul 25 02:45:11 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 06:45:11 GMT Subject: Letting a program get a StringIO instance by file('test.txt') virtual file redirection Message-ID: Sometimes I like to make a quick example to post without actually creating files (except maybe one for the example source). This is hard if the example involves opening a file as in f=file('test.txt','rb'). If file and open would look first in a (proposed new) directory (like sys.modules), but perhaps named sys.vfiles, and do different things according to the value found using the file path as a key (if found there) instead of always opening a disk file, then one could write import sys, StringIO sys.vfiles['test.txt'] = StringIO.StringAsFile("""\ def foo(): print 'Hello' """ execfile('test.txt') foo() and expect to get a Hello. This assumes a new class in StringIO to create an object containing a string which would have an open method to return a new StringIO instance containing the string. That's so it could be opened multiple times to get independent StringIO "files". It would be recognized by file/open when it looked in sys.vfiles. Also, file/open could recognize plain string values as redirections, like a symbolic link. You could even have it recognize some URI strings and do the appropriate open, e.g., sys.vfiles['python_site'] = 'http://www.python.org/' top_page = file('python_site').read() It could also be a way make file/whatever names platform independent. site.py could do whatever standard setup was decided upon. Just some thoughts, after cluttering my pywk/junk directory, and then thinking there might might be a useful idea in there somewhere ;-) Something similar came up before, and apparently lisp has ways to do similar things, but the idea died. I just thought the sys.vfiles incarnation might be clearer. Regards, Bengt Richter From erno-news at erno.iki.fi Mon Jul 22 07:12:20 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 22 Jul 2002 14:12:20 +0300 Subject: ssh and Python References: Message-ID: In article , "Bo M. Maryniuck" writes: | On Sunday 21 July 2002 20:34, John Hunter wrote: || import os || h = os.popen('ssh -2 somehost.com ls') || print h.read() | That's solves half of problem. How to automatically pass the password? Yes, | you need a pipe to write in... use a rsa key with ssh-agent (or without passphrase if you need it to run unattended). -- erno From tim.one at comcast.net Fri Jul 12 18:17:59 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Jul 2002 18:17:59 -0400 Subject: switch recipe? In-Reply-To: Message-ID: [Cliff Wells (I think)] > def make_switch(*args): > """Return a generator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") > def switch(): > while True: > for a in args: > yield a > return switch [Alex Martelli] > Wouldn't you get exactly the same observable effect from > the simpler function: > > def make_switch(*args): > """Return an iterator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") > return iter(args) The top one generates an unbounded sequence, due to the "while True". The Icon language calls this "repeated alternation", and actually has a prefix operator for it (the vertical bar). What I'm unclear about is why we're writing a function to return a generator function: why not write a generator function directly? So my candidate for simplification is: def make_switch(*args): """Generate the elements in args repeatedly.""" if not args: raise TypeError("at least one argument required") while True: for a in args: yield a I'd lose the "if not args:" block, though; if the arglist is empty, it will simply terminate without yielding anything, and that's what I expect the empty case to do. From fredrik at pythonware.com Wed Jul 10 05:28:32 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jul 2002 09:28:32 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: <47TW8.47023$n4.11330013@newsc.telia.net> Alex Martelli wrote: > Things aren't all that different regarding the eval builtin > function rather than the exec statement: > > result = eval(something, fakelocals) > > there are a bit fewer issues with eval than with exec, but it > doesn't take much to bypass the "can only do expressions" > limit, alas. most importantly, note that "any shell command" qualifies as an expression: something = "__import__('os').system('echo j00 h4v3 b33n 0wn3d')" From akuchlin at ute.mems-exchange.org Fri Jul 12 08:11:36 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 12 Jul 2002 12:11:36 GMT Subject: What went wrong in Python1.6 ? References: Message-ID: In article , Rhymes wrote: > Now I ask my self: what went wrong in that release? Where i could find > some further infos about this "miscarriage" ? After the primary Python developers left CNRI, CNRI management requested a release that wrapped up everything the developers had done while still working here. Development had continued to roll on, though, and a year's worth of community patches had been incorporated into CVS, resulting in Python 2.0. Python 1.6 therefore ended up being 1.5.2 + Unicode + new SRE regex engine + some bugfixes. Work had to be done to backport the 2.0 Unicode code to 1.6, because you wouldn't want 1.6 and 2.0 to be incompatible, but no one in their right mind would have used 1.6, because 2.0 was 1.6 + cyclical GC + augmented assignment + list comprehensions + XML support + more bugfixes and was available at the same time. This meant the backporting work was mostly wasted effort, occupying time that could have been spent on other things. --amk (www.amk.ca) That's the trouble with computers, always think in black and white. No aquamarines, no blues, no imagination. -- The Doctor, in "The Invisible Enemy" From mgilfix at eecs.tufts.edu Wed Jul 31 10:33:58 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 31 Jul 2002 10:33:58 -0400 Subject: global interpreter lock not working as it should In-Reply-To: <200207302156.RAA31962@test-area.com>; from anton.wilson@camotion.com on Tue, Jul 30, 2002 at 05:57:32PM -0400 References: <200207302156.RAA31962@test-area.com> Message-ID: <20020731103358.C26901@eecs.tufts.edu> Out of curiosity, did you get this description from David Beazley's Python Essential Reference, under the threading section? While the book is absolutely fantastic, it's description of threading can be a little misleading and directly quotes what you were getting after here. Or perhaps it's in the py documentation - I haven't looked. -- Mike On Tue, Jul 30 @ 17:57, anton wilson wrote: > I think I understand what you mean. I assumed that python should block and > allow others to work every x byte codes on EVERY platform. I see that that's > a wrong assumption. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From mfranklin1 at gatwick.westerngeco.slb.com Fri Jul 12 14:49:50 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 12 Jul 2002 18:49:50 +0000 Subject: newbie question: getting rid of space in string :( In-Reply-To: References: Message-ID: <200207121753.g6CHrb705813@helios.gatwick.geco-prakla.slb.com> On Friday 12 Jul 2002 5:30 pm, Alex Martelli wrote: > Martin Franklin wrote: > ... > > > as a matter of taste I would use this:- > > wholeString=wholeString+"<%s>%s" %(color, a, color) > > but as I say this is a matter of taste! > > Building up a large string by + concatenation of many > small ones is Python's main performance trap. If you > want to build things up, build them up in a list instead, > then at the end you can use sys.stdout.writelines to write > it out or ''.join to make the big string. I agree. I guess I was giving the OP what I consider the simplest way (without introducing anything too 'new' to him (he did say he was a newbie) Best Regards Martin From bogus@does.not.exist.com Mon Jul 29 23:37:49 2002 From: bogus@does.not.exist.com (chris) Date: Mon, 29 Jul 2002 23:37:49 -0400 Subject: pretty basic: get variable name from list of strings? References: <34kbku4j76104d193oevjfi83mk3olvsbt@4ax.com> Message-ID: On 30 Jul 2002 02:18:11 +0200, Chris Liechti wrote: > >box = [] #create an empty list >#and populate it: >for j in range(1,100): > id = wxNewId() > box = wxRadioBox(self, id, name, wxDefaultPos, > wxDefaultSize, TeamList[j], 1, wxRA_SPECIFY_COLS) > EVT_RADIOBOX(self, id, self.EvtRadioBox) > self.boxes.append(box) > >and EvtRadioBox can find out which was the event source, no need to write >100 distict functions... Hi other chris, thanks for the advice. i'm definitely new to programming in addition to python, so I appreciate the big-picture advice. leaving that for another day, my quick follow-up question is: is the ID passed to the EvtRadioBox function? Because I don't want all 100 radio buttons to do the *exact* same thing, I need it to be slightly RadioBox (id) specific, something like print id . Alternatively, are arguments passable to the general event function? thanks again for your time and instruction chris, chris From sheershion at mailexpire.com Fri Jul 19 19:39:08 2002 From: sheershion at mailexpire.com (Robert Amesz) Date: Fri, 19 Jul 2002 23:39:08 -0000 Subject: [Q] wxPython - layout & placement References: Message-ID: Rolf Marvin B?e Lindgren wrote: > I'm trying to place a button in a dialog window. this works: > > dlg = wxDialog(parent,-1,FileName,size=(400,400)) > > wxButton (parent=dlg, > id = -1, > label = 'This is a button', > pos=(10,10)) > > dlg.ShowModal() > > but I'd like to use layout controls. I've figured out how to do it > with wxPanel, but wxDialog doesn't seem to work the same way. the > example on > > b = wxButton(self.panelA, 100, ' Panel A ') > lc = wxLayoutConstraints() > lc.centreX.SameAs (self.panelA, wxCentreX) > lc.centreY.SameAs (self.panelA, wxCentreY) > lc.height.AsIs () > lc.width.PercentOf (self.panelA, wxWidth, 50) > b.SetConstraints(lc) > > does not work if the parent object is a wxDialog. > > any clues? > > Hmmm, puzzling... But then, there's a lot of code which you aren't showing. What, for instance, is panelA (and why do you use it), things like that. But you'd better forget about wxLayoutConstraints altogether. The manual states: Note: constraints are now deprecated and you should use sizers instead. Don't worry: sizers are pretty easy to use. Nearly always easier than using constraints. Robert Amesz From jonathan at onegoodidea.com Tue Jul 30 04:36:47 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 09:36:47 +0100 Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 References: <3D45E665.3C34CDF@alcyone.com> Message-ID: On 30/7/2002 2:05, in article 3D45E665.3C34CDF at alcyone.com, "Erik Max Francis" wrote: > Looks like a typo to me. That may well be so, but that would result in a parser well-formedness (what a great word) error. The traceback appears to be pointing to something else: > Traceback (most recent call last): > File "", line 1, in ? > doc = PyXMLReader.fromString(xmlText) > File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/__init__.py", > line 63, in fromString > return self.fromStream(stream, ownerDoc) > File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/Sax2.py", > line 373, in fromStream > self.parser.parse(s) > File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", > line 107, in parse > self.reset() > File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", > line 236, in reset > self._parser = expat.ParserCreate(intern = self._interning) > TypeError: 'intern' is an invalid keyword argument for this function Is this some weird mismatch in expat module version? Jonathan From shagshag13 at yahoo.fr Mon Jul 22 05:11:53 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 22 Jul 2002 11:11:53 +0200 Subject: args command line... References: <409a56e2.0207200133.35cdc06b@posting.google.com> <3D399A3D.1060002@usa.net> Message-ID: Thanks to all, that's the kind of stuff meeting my goals (and formalism wasn't a trouble) s13. From nhodgson at bigpond.net.au Fri Jul 26 05:34:51 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 26 Jul 2002 09:34:51 GMT Subject: how to count lines in a file ? References: <7aU%8.139472$vm5.4528856@news2.tin.it> <1027656130.63094@yasure> Message-ID: <%I809.493664$o66.1339193@news-server.bigpond.net.au> Alex Martelli: > One thought I've toyed with, at times, is to have the optional > ability to mark a few objects as _requiring_ stricter finalization > semantics than the run-of-the-mill kinds of objects. E.g., files > could be marked that way. Some of the history behind .NET not having deterministic finalization even for a subset of objects: http://www.managedworld.com/articles/0003/article.aspx Neil From peter at engcorp.com Fri Jul 19 09:45:12 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Jul 2002 09:45:12 -0400 Subject: HTML DOM parser? References: <7xwursj0a4.fsf@ruckus.brouhaha.com> <3D373D7C.2237E7A3@engcorp.com> <7xvg7ck6dq.fsf@ruckus.brouhaha.com> Message-ID: <3D3817E8.13203964@engcorp.com> "Daniel E. Burrow" wrote: > > My present task requires the automation of IE. After much prayer, I > found that the "dom = ie.Document" assignment IS case sensitive. The > lower case form of "ie.document" just would not work for my > ActiveState ActivePython 2.2.1 distribution. That's odd. I have never had to worry about case in almost any aspect of IE automation, especially this one. Does anyone with greater knowledge of the guts of this stuff have any input on why Daniel would have to worry about case while I do not? Peter From jeffrey.b.layton at lmco.com Mon Jul 29 12:09:57 2002 From: jeffrey.b.layton at lmco.com (Jeff Layton) Date: Mon, 29 Jul 2002 12:09:57 -0400 Subject: Newbie: How to touch "global" variables Message-ID: <3D4568D5.3254F968@lmco.com> Hello, I've got a defeinite newbie question (I searched some, but to be honest I don't know what keywords to search on - which has brought me here :). I want a module to be able to "touch" a variable defined globally (from the main script). I don't necessarily want to change the value ofthe variable, but to query it. For example, get the length. How do I do this? Thanks! Jeff P.S. If someone needs some sample code I can cook something up. From Noslwop at Hotmail.com Wed Jul 10 13:43:00 2002 From: Noslwop at Hotmail.com (David Fillmore) Date: Wed, 10 Jul 2002 18:43:00 +0100 Subject: Z-machine/Infocom interpreter in Python? References: <3D2BE29E.4C49B91C@alcyone.com> Message-ID: <3D2C7224.1030108@Hotmail.com> Erik Max Francis wrote: > Anyone know of a Python library for interpreting Infocom Z-machine > games, up to at least z5 (or whichever the version is _before_ the one > that had support for graphics and sound, I have no need for that)? > > I'm looking for something that can be hooked into chat systems so that > people can send it messages (as commands) and get back the results. I > can't recall whether the status line in Z needs to be treated specially > or not. > > Some Web searches came up with PUB, > > http://py-universe.sourceforge.net/ > > which is an authoring system and not an interpreter, and viola, > > http://sourceforge.net/projects/viola/ > > which as far as I can tell is a dead project which never made any > releases [grumbles about the use of the present tense to describe > projects which are not yet created]. Viola isn't dead, it's just undergoing serious rewriting due to the fact that the code is basically a mess. It should be ready for a proper release before too long. Hopefully. -- Fillmore From rjones at ekit-inc.com Thu Jul 25 17:46:00 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 26 Jul 2002 07:46:00 +1000 Subject: how to count lines in a file ? In-Reply-To: <7aU%8.139472$vm5.4528856@news2.tin.it> References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> Message-ID: <200207260746.00524.rjones@ekit-inc.com> On Fri, 26 Jul 2002 12:45 am, Alex Martelli wrote: > Michele Simionato wrote: > > Can somebody provide a simple example where the idiom > > > > file(name,'w').write(something) > > > > fails, in the sense that the file is not closed or something is not > > written ? I tried to hang the program with a memory overload > > [alex at lancelot jython-2.1]$ jython > Jython 2.1 on java1.4.0_01 (JIT: null) > Type "copyright", "credits" or "license" for more information. > > >> open('aname','w').write('something\n') > > [alex at lancelot jython-2.1]$ cat aname > [alex at lancelot jython-2.1]$ ll aname > -rw-rw-r-- 1 alex alex 0 Jul 25 16:41 aname > [alex at lancelot jython-2.1]$ > > I exited the interactive interpreter with a clean, normal > control-D, but as you see file aname was created but its > contents not written. > > Any implementation of Python is perfectly free to choose > this behavior if it provides some other advantage. I think the major problem that we're running into here is that before there was GC, the refcounting-based cleanup of objects was clear, straight-forward and reliable. Now it's not clear when objects are cleared up. That's a fairly major problem for some of us old-timers (and, quite possibly, a lot of newbies) to come to terms with. I hadn't realised that GC threw such a big, ugly spanner in the works :( Richard From glingl at aon.at Tue Jul 23 18:16:20 2002 From: glingl at aon.at (Gregor Lingl) Date: Wed, 24 Jul 2002 00:16:20 +0200 Subject: good books References: Message-ID: <3D3DD5B4.5080507@aon.at> Percy Tambunan schrieb: > what is a good book in python, If i can only afford to buy just one book? > > > what is a good book for you depemds decisevly on what you need. Beazley's has been characterized by other postings. If you want to learn the core of Python up to an intermediate level, a cheap, readable and very useful (because not too fat) companion is Chris Fehily's Python Visual Quick Start Guide. Go to a book store and have a look at it. If you want to learn how to approach every facette of the Python world an undispensable guide will be Mark Lutz Programming Python ... ... or perhaps we should stick with online ressources until we can see what martellibot will be giving to us gl From spam at ob_scure.dk Sun Jul 7 06:26:54 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 12:26:54 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> Message-ID: <3D28176E.4030709@ob_scure.dk> Paul Rubin wrote: [snip] > You may be best off with a hybrid approach, writing the control > structure of your program in Python but the inner computational loops > in C, called through the Python-to-C API or through SWIG. These have > a bit more learning curve than programming in pure Python, but will > let you get at the performance of C code when you need it. I gotta look into this. However I am uncertain as how to structure my program. One of the tasks of the program will be to calculate the standard deviation of rows of daily values (which are the result of another calculation, etc). I was planning on using lists and tuples like this: [(date, value), (date, value), ...] How well will this perform i wonder? Since lists and tuples are Python structures, won't they still be "slow" to traverse? -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From brueckd at tbye.com Wed Jul 31 00:27:43 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 30 Jul 2002 21:27:43 -0700 (PDT) Subject: global interpreter lock not working as it should In-Reply-To: <200207302247.SAA21093@test-area.com> Message-ID: On Tue, 30 Jul 2002, anton wilson wrote: > > Just curious: how do you explain all the multithreaded Python programs > > that currently work just fine? Are these all flukes? > > This brings me to the second reason that your program seems to work. > The Linux OS gives threads time-slices and when these time-slices are used up > every 150 or so milliseconds, the process is forcibly removed from the CPU. > I presume that the reason your program seems to work is that in the time > between when a thread releases the GIL and a thread tries to reaquire the > GIL, it is forcibly removed from the CPU, and the other thread can now run. > This would not be a rare occurence due to the high frequency at which the > lock is released. Well, I guess you can believe what you want. :-) But at my last job I had multithreaded Python programs running just fine on Windows, Linux, and Solaris and they worked great. In fact, some of them were direct ports of C/C++ code - there was no need to change the approach to using threads because it worked pretty much the same in C as in Python. At my current job I have production multithreaded Python programs in both Windows and Linux, and again, I'm not doing anything 'special' to 'deal' with the GIL or anything like that. I guess it seems a bit hard for me to believe that they just 'seem' to work; I know for myself, from direct experience, that they really do work great. -Dave From gb at cs.unc.edu Tue Jul 16 20:25:27 2002 From: gb at cs.unc.edu (gb at cs.unc.edu) Date: 16 Jul 2002 20:25:27 -0400 Subject: SVG viewer in python? Message-ID: Does anyone know of an open source SVG viewer written in Python? I'm working with some students on a project to make SVG drawings (maps in particular) accessible to visually impaired students. Thanks for any pointers. Gary Bishop Associate Professor University of North Carolina Chapel Hill From spum at piels.com Thu Jul 25 00:36:46 2002 From: spum at piels.com (Bobby Beckmann) Date: Wed, 24 Jul 2002 21:36:46 -0700 Subject: ANNOUNCE: PyDumper - GDB Helper script Message-ID: <3D3F805E.9050205@piels.com> I'm sure this has been done before, but I needed one, and I couldn't find one. I wrote a script that wraps GDB and is able to extract a stack trace and all relevant data (func args, globals, locals, instance vars) to help debugging apps that get stuck. Take a look at http://www.piels.com/PyDumper.html If there's something better out there, please let me know! Thanks, Bobby From emile at fenx.com Fri Jul 5 09:30:09 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 05 Jul 2002 13:30:09 GMT Subject: IMAP Email Question References: Message-ID: Charel Yueng > I cannot process any string data because it's a tuple. I can't seem > to be able to parse any data. > > What should be my approach to this problem? > what I need to extract is separated by the '=' sign ie. > charles,yueng,someaddress > >>> s = 'fname=charles\r\nfname=yueng\r\naddress=someaddress\r\n\r\n\r\n' >>> [x.split("=") for x in s.split()] [['fname', 'charles'], ['fname', 'yueng'], ['address', 'someaddress']] -- Emile van Sebille emile at fenx.com --------- From tim at zope.com Thu Jul 25 17:07:21 2002 From: tim at zope.com (Tim Peters) Date: Thu, 25 Jul 2002 17:07:21 -0400 Subject: random 64-bit int In-Reply-To: <7BP%8.31421$4T2.9101969@twister.socal.rr.com> Message-ID: [Jeff Davis] > ... > random() isn't really all that random either, since it is only zero to > one and a conversion to a float loses a lot of information (I think... > let me know if I'm mistaken). A Python float is a C double, which on most boxes has 53 bits of precision. That means, e.g., that there are 2**53 distinct Python floats in the range [0.5, 1.0) alone. Also 2**53 distinct Python floats in the range [0.25, 0.5) alone; etc. That's a lot of floats. Python's Wichmann-Hill generator has only about 45 bits of internal state, and no information is lost in representing one of those states as a Python float. A direct and quicker pure-Python method of generating random N-bit ints can be found here: http://www.faqts.com/knowledge_base/view.phtml/aid/4406 From ryanmorillo at hotmail.com Mon Jul 15 06:07:06 2002 From: ryanmorillo at hotmail.com (Ryan) Date: 15 Jul 2002 03:07:06 -0700 Subject: Convert to Python and compile to executable References: <3D307578.9080307@softhome.net> <3D307AB9.9070707@softhome.net> Message-ID: <4a7fde99.0207150207.1d3c0d49@posting.google.com> Colin Barschel wrote in message news:<3D307AB9.9070707 at softhome.net>... > I kind of answered the question myself with the (very good) faq at > python.org where > the solution would be with the freeze option. > > I guess I have to try it myself to see how it works. I still want to > ask: does id work good? Is it a viable solution to distribute a program > or is it better to go java or c++ from the beginning? > > Thanks > Ciao > Colin A way out of that whole question is to check out Jython http://www.jython.org and use it to change your Python code to Java (works very well once you get it to work, but it kils any gui stuff (SWING or AWT vs. TkInter). Freeze works well, but if someone wants to disassemble the code, it isn't too aweful hard to do. From mnations at airmail.net Wed Jul 24 11:25:18 2002 From: mnations at airmail.net (Marc) Date: 24 Jul 2002 08:25:18 -0700 Subject: Need a better way to pause a thread References: <4378fa6f.0207231456.3057babe@posting.google.com> Message-ID: <4378fa6f.0207240725.37b8854@posting.google.com> Thanks Chris, and you hit upon something I've been wondering about for a while. I've used queues before to do simple things like strings and variables when I simple wanted to display or use something. But when I tried to do whole commands, it got klunky. The only way I had found to do it was putting the commands in a string and using eval() on the command on the other side. This was too painful to use in large applications. However you did it the following way: > #now you can feed your thread with work: > q.put( (time.sleep, 1) ) > q.put( (sys.stdout.write, "Hello its the thread speaking up") ) Basically it appears the format is the command placed in nested () with things that would be passed thru as parameters being delimited by commas. Is this a general format that will work for all commands, or is there a place I can check the format? There are several examples of queues I've found but none showing all the ways you can pass commands through. Marc From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 10:20:39 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 09:20:39 -0500 Subject: signature for a file ? In-Reply-To: ("Shagshag13"'s message of "Tue, 30 Jul 2002 11:49:36 +0200") References: Message-ID: >>>>> "Shagshag13" == Shagshag13 writes: Shagshag13> i had at home many hdds, that could contain many time Shagshag13> same files, in many places/directories (-> i'm really Shagshag13> disorganized). i would like to do some sort on theses Shagshag13> files. to do this i'm planning to write a python Shagshag13> script that would compute a kind of CRC32, MD5 or SHA Shagshag13> (i'm really not competent in that - so here i need Shagshag13> advices and pointer to some implementations - and to Shagshag13> know which is the best to had a unique unambiguous Shagshag13> signature for a file) and then use it to find Shagshag13> "doubles" : same size + same signature = probably same Shagshag13> file. I do a daily backup of some of my zope folders using cron, and get some identical files if the folder hasn't changed since the last backup. I wrote this script to kill identical files and (optionally) replace the duplicates with symbolic links to the original. It has a debug mode, where it just reports what it would have done and how much file space you save but doesn't actually do anything. I never intended this for distribution, but it seems close enough to what you are talking about that I thought it might give you some ideas. Use with extreme caution. (never tried it on a non linux platform. you could replace md5sum with the built-in md5 lib... ) you can call the script like # check all dat files in current dir kill_identical_files.py *.dat # somefile contains a list of files to check kill_identical_files.py somefile # files from stdin find . | kill_identical_files.py --- begin kill_identical_files.py --- #!/usr/local/bin/python import string, os, sys, re from JdhMixins import Debug, Verbose # Note stdin approach assumes you have no empty lines in the stdin, to # allow it to terminate on commands like # find . | myscript.py class NextFile: fh = None args = None val = None count = 0 def __init__( self, args): """Pass sys.argv[1:] and this will get the file list from a single file arg, the stdin, or argv list""" self.Nargs = len(args) if self.Nargs==0: self.stdin = 1 self.fh = sys.stdin elif self.Nargs==1: self.file = 1 self.fh = open( args[0], 'r') else: self.args = args def more(self): if self.fh: try: self.val = self.fh.readline()[:-1] return len(self.val)>0 except: return None else: if self.count >= self.Nargs: return None self.val = self.args[self.count] self.count = self.count + 1 return 1 def nextfile(self): return self.val rgx = re.compile('([^\s]+)\s+(.*)$') n = NextFile( sys.argv[1:] ) v = Verbose('extreme') d = Debug('on') #make this 'off' to actually alter the file system link = 1 #replace the killed files with symlinks s = {} savings = 0 minSize = 5000 # don't remove files smaller than this while n.more(): file = n.nextfile() #Only operate on plain files if not os.path.isfile(file) or os.path.islink(file): if v.verbose('extreme'): print 'Skipping non plainfile %s' % file continue fileSize = os.path.getsize(file) if fileSize<=minSize: continue if v.verbose('extreme'): print 'Computing md5sums for %s' % file line = os.popen('md5sum %s' % file).readline() match = rgx.match(line) if not match: continue (sum, file) = (match.group(1), match.group(2)) if s.has_key(sum): origFile = s[sum] savings = savings + fileSize if v.verbose('moderate'): print 'Removing file %s identical to %s' % (file, origFile) if link: print '\t...making symlink from %s to %s' % (file, origFile) if not d.debug(): os.remove(file) if link: os.symlink( origFile, file) else: if v.verbose('unbearable'): print 'Adding new file %s' % file s[sum] = file if v.minimal(): print 'Total savings is %1.2fMB\n' % float(savings/1e6) --- end kill_identical_files.py --- --- begin JdhMixins.py --- import types class Debug: """A mixin class to set and test whether you are in debug mode""" __s = {'on' : 1, 'off' : 0} __debug = 1 def __init__(self, val='on'): """val can be a logic value (eg, 0 or 1) or an string ('on' or 'off')""" self.set_debug(val) def set_debug(self, val): if isinstance(val, types.StringType): self.__debug = self.__s[val] elif isinstance(val, types.IntType): self.__debug = val else: raise ValueError, \ 'Expected a string or and integer for debug value level' self.__debug = val def is_debug(): return self.__debug def debug(self): return self.__debug class Verbose: """ A mixin class for verbosity.""" __SILENT = 0 __MINIMAL = 10 __MODERATE = 100 __EXTREME = 1000 __UNBEARABLE = 10000 __level = __MINIMAL __s = { 'silent' : __SILENT, 'quiet' : __SILENT, 'minimal' : __MINIMAL, 'moderate' : __MODERATE, 'extreme' : __EXTREME, 'unbearable' : __UNBEARABLE } def __init__(self, level='moderate'): self.set_verbose(level) def verbose(self, val='minimal'): """So you can do class MyClass(Verbose()) if self.verbose(): print something if self.verbose('moderate'): print something else """ return self.__level >= self.__s[val] def set_verbose( self, level): if isinstance(level, types.StringType): if level not in self.__s.keys(): raise ValueError, 'Unrecognized level %s' % level self.__level = self.__s[level] elif isinstance(level, types.IntType): self.__level = level else: raise ValueError, 'Expected a string or and integer for level' def is_silent(self): return self.__level == self.__SILENT def minimal(self): return self.__level >= self.__MINIMAL def moderate(self): return self.__level >= self.__MODERATE def extreme(self): return self.__level >= self.__EXTREME def unbearable(self): return self.__level >= self.__UNBEARABLE --- begin JdhMixins.py --- From amuys at shortech.com.au Thu Jul 4 21:13:05 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 4 Jul 2002 18:13:05 -0700 Subject: REPEAT... UNTIL ? References: <3D2487CB.9000102@gmx.de> Message-ID: <7934d084.0207041713.741e4a5@posting.google.com> Ingo Linkweiler wrote in message news:<3D2487CB.9000102 at gmx.de>... > I know that I can use a while loop with break instead of repeat-until. I > am using it, but I just think a repeat-until looks better. If nobody > else has this opinion: Let's forget my stupid question <8-) > Two comments: Please do a google-groups search for "repeat until do while" in c.l.p, once you've finished reading all the past discussion on this topic I'll join you in celebrating the start of the 4th millenium ;). Of course to summarise, you will ask about adding a post-tested loop to python; somebody will reply that they use while 1:/if:break; you will suggest you don't like while 1:; eventually the noise will wake up the martelli-bot who will rave about Knuthian N-1/2 loops and generic looping constructs; the thread will petter out and lie dormant until next time. IOW, you're going to have to do alot better then a two line post if you want to overcome the inertia this issue has achived over the years. Personally I couldn't care less, if I find myself writing any form of explicit loop I tend to consider it an algorithmic flaw. So I tend to use list comprehensions, and occasionally map(). Of course I recognise that sometimes a foreach loop (written for..in..: in python) is cleaner, and less regularly a while-loop, but when it comes to aesthetics by the time I get to a while loop, using while 1:/if:break is a trivial matter. Andrae From nas at python.ca Mon Jul 29 16:55:46 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 29 Jul 2002 13:55:46 -0700 Subject: Python design failures (was Re: Let's Talk About Lambda Func In-Reply-To: ; from shalehperry@attbi.com on Mon, Jul 29, 2002 at 01:03:42PM -0700 References: Message-ID: <20020729135546.D31926@glacier.arctrix.com> Sean 'Shaleh' Perry wrote: > I could submit a patch for the repr cleanup in pretty short order. Guido's not big on this kind of "hit and run" cleanup. He prefers it if someone looks at the entire module while modernizing it. Keep in mind though, I'm an amateur when it coming to channelling the BDFL and he might tell you differently himself. Neil From fredrik at pythonware.com Mon Jul 15 03:16:23 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Jul 2002 07:16:23 GMT Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: Daniel Yoo wrote: > Fredrik Lundh wrote: no, I didn't. can you please spend the two seconds it'll take to get the attributions right before you post. thanks /F From erict at millfilm.co.uk Fri Jul 12 08:23:07 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Fri, 12 Jul 2002 13:23:07 +0100 Subject: SimpleXMLRPCServer help Message-ID: <3D2ECA2B.B1CA01EB@millfilm.co.uk> help(SimpleXMLRPCServer) describe how to install an instance on the server: 2. Install an instance: class MyFuncs: def __init__(self): # make all of the string functions available through # string.func_name import string self.string = string def pow(self, x, y): return pow(x, y) def add(self, x, y) : return x + y server = SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(MyFuncs()) server.serve_forever() BUT I cannot figure out the syntax to access it from a client point of view I will appreciate a quick example even not tested. Thanks, Eric From just at xs4all.nl Tue Jul 30 05:08:35 2002 From: just at xs4all.nl (Just) Date: Tue, 30 Jul 2002 11:08:35 +0200 Subject: global interpreter lock not working as it should References: <200207292348.TAA31011@test-area.com> Message-ID: In article , loewis at informatik.hu-berlin.de (Martin v. Lowis) wrote: > Just writes: > > > I can see it on MacOSX, three different Linux boxes and a FreeBSD box. > > Various Python versions. The output is always sequential. > > As Aahz explains, that can indeed happen (and, depending on the thread > implementation of your operating system, might be even likely to > happen). It is in no way "wrong". Please replace the for statement > with a while 1: loop - even on systems where my script produces > sequential output, I find that the operating system will eventually > switch threads. Oh, I wasn't complaining it doesn't work as designed, merely that I could reproduce something easily, that you claimed you couldn't... Just From edream at tds.net Tue Jul 30 11:14:15 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 30 Jul 2002 15:14:15 GMT Subject: Leo 3.1 Bugs References: Message-ID: > Font Dialog: > Leo windows won't change to selected font unless one of (bold, italic) is > clicked after the new font is selected. Double-clicking the font name also selects the font. This behavior is due to a non-existent option in the Tk ListBox class. AFAIK it can't be fixed until the Tk ListBox class is improved. Fredrik Lundh discusses this at: http://www.pythonware.com/library/tkinter/introduction/x5453-patterns.htm "Unfortunately, the listbox doesn't provide a command option allowing you to track changes to the selection. The standard solution is to bind a double-click event to the same callback as the OK (or Select, or whatever) button. This allows the user to either select an alternative as usual, and click OK to carry out the operation, or to select and carry out the operation in one go by double-clicking on an alternative." If anyone knows of a better solution I'd like to hear about it. > Color Picker: > Reverts to color in use before choice is made - i.e. user's new choice is > ignored. This was seen on the 'keywords' picker at least. I'll look into this. Thanks for reporting it. > Would be nice if the log window could be disappeared when not being used/not > wanted. You can resize it to a very small size by dragging the separator bar. You could also try the Toggle Split Direction command... > It would be nice if ?untangled? code was written a bit prettier. It might > not generally be intended to look at, but then again, I don't forsee a need > to send out tangled code... Do mean code in the derived files? For code reviews, publishing, etc. you can use the Remove Sentinels command in the File-Import & Export menu. > N.B. Leo on SF doesn't allow posts by unregistered users. Is registering a problem? I don't believe comp.lang.python is the appropriate place to discuss all SourceForge project that happen to be written in Python :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From pixie888 at hotmail.com Mon Jul 22 03:33:07 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Mon, 22 Jul 2002 07:33:07 GMT Subject: Python to Excell Message-ID: <3d3bb483.250106359@news.skynet.be> Hi all, I want to use Python to automate Excell. What I want to do is writing a script which updates an Excell sheet and which prints it out then. I know the stuff about DispatchEx but I do not know the interface which is exposed by Excell. Can anybody help me further on this one? Thanks, Henk From rajarshi at presidency.com Wed Jul 17 15:09:58 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 17 Jul 2002 15:09:58 -0400 Subject: popen2 question Message-ID: Hi, I'm writing a driver routine for some fortran programs. basically I use the statement: cin, cout = popen2.popen2('qnetin') I provide input like: cin.write('train\n10\n\n1000\n') The write's work fine. However when at a certain point, the fortran program will output to stdout, which I catch with line = cout.readline() But after reading 2 lines of output like this, the fortran program crashes with the error: Input/Output Error 173: Broken pipe In Procedure: main program At Line: 297 Statement: Formatted WRITE Unit: 6 Connected To: Stdout Form: Formatted Access: Sequential Records Read : 0 Records Written: 5 End of diagnostics Why does the popen2 command work for the first 2 lines of output and then fail on the third? Any suggestions would be helpful. TIA From cliechti at gmx.net Sat Jul 27 14:22:13 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jul 2002 20:22:13 +0200 Subject: Newbie - help request with serial line (termios?) setup in Python 2.2 References: <4860ce4f.0207271004.4cbc8880@posting.google.com> Message-ID: billintucson at yahoo.com (Bill Gillespie) wrote in news:4860ce4f.0207271004.4cbc8880 at posting.google.com: > I'm trying to open a serial line on a SunOs using python 2.2. > I'm new to programming, and fairly new to unix/linux. I have the two > pink Oreilly Python books and have read a couple of tutorials - but I > am a newbie. welcome > After much googling (there is not a lot of novice python/unix/termios > info out there) - this is what I think? I should be doing.... > > Open the line > Configure the line? termios?? > Communicate with the line (ASCII charachters < > at 4800) > Close the line ok, i make it short... you could use my library http://pyserial.sf.net if, for some reason, you still want to do it by hand, you can at least look at the sources. (you may need to specify the port by name: s = serial.Serial('/dev/ttyC43', baudrate=4800, timeout=1)) chris -- Chris From robin at jessikat.fsnet.co.uk Wed Jul 17 18:50:46 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 17 Jul 2002 23:50:46 +0100 Subject: ANN: Pyrex 0.3.4 References: Message-ID: In article , Greg Ewing writes >Pyrex 0.3.4 is now available: > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > > .... I'm probably being stupid, but I get this with the Demos\setup.py using win32 2.2.1 after doing the base setup.py install C:\Tmp\Pyrex-0.3.4\Demos>setup.py build_ext running build_ext building 'primes' extension creating build creating build\temp.win32-2.2 creating build\temp.win32-2.2\Release C:\Program Files\Microsoft Visual Studio\VC98\BIN\cl.exe /c /nologo /Ox /MD /W3 /GX -IC:\Python\include /Tcprimes.c /Fob uild\temp.win32-2.2\Release\primes.obj primes.c primes.c(114) : warning C4102: '__pyx_L4' : unreferenced label primes.c(85) : warning C4102: '__pyx_L6' : unreferenced label primes.c(76) : warning C4102: '__pyx_L5' : unreferenced label primes.c(67) : warning C4102: '__pyx_L3' : unreferenced label primes.c(141) : error C2375: 'initprimes' : redefinition; different linkage primes.c(139) : see declaration of 'initprimes' error: command '"C:\Program Files\Microsoft Visual Studio\VC98\BIN\cl.exe"' failed with exit status 2 C:\Tmp\Pyrex-0.3.4\Demos> -- Robin Becker From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 07:37:46 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 04:37:46 -0700 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> Message-ID: <7xeldq1zzp.fsf@ruckus.brouhaha.com> Dale Strickland-Clark writes: > I've not done any research into this yet so I could have this > completely about my ears. > > We need to do some basic authentication to control access to some > resources through HTTP. If you mean HTTP Basic authentication, that works by sending the password as plaintext. There's also HTTP Digest authentication which work sort of like the scheme you described, but most browsers don't support it. > Can anyone see any holes in this and does anyone have any experience > of such a scheme? Is there anything we should look out for? If you mean HTTP Digest auth, the trouble is that most browsers don't support it, so if you want to control your app with a browser, you're limited in browser choices. If you mean a roll-your-own protocol, avoid those if you can. It's incredibly easy to make mistakes in protocol design. For low-security applications, HTTP Basic is ok. For medium-to-high security applications where you need protection against someone sniffing your network, use HTTP Basic over SSL--that way the authentication headers get sent over an encrypted channel. For very high security applications, use SSL with client certificates, preferably stored on hardware tokens such as smart cards. If you really have to code up your own protocol, replace > 4. client produces SHA/MD5 digest of random string > 5. client updates digest with password producing client digest with: 4. client computes SHA/HMAC of random string (use the Python 2.2 hmac module for that) using password as key instead of just appending the password to the random string. That avoids certain attacks against the hash functions. I don't see anything else wrong with your protocol, but I may have missed something. It's very easy to miss things. It's almost always better to use existing, standard, well-tested protocols. From tom.verbeure at verizon.no.sp.am.net Sun Jul 28 09:16:48 2002 From: tom.verbeure at verizon.no.sp.am.net (Tom Verbeure) Date: Sun, 28 Jul 2002 13:16:48 GMT Subject: How to detect the last element in a for loop References: <3D4388C8.6040005@nowhere.org> Message-ID: <49S09.13011$9U4.7618@nwrddc01.gnilink.net> > For a simple solution, how about: > > for a in myList[:-1]: > do_stuff(a) > special_stuff(myList[-1]) No, I still want to do 'do_stuff' for the last element also. This may be, say, 10 lines of code. Too much to duplicate it outside the loop, not enough for a separate function... > > Given that you have an explicit iterator, wouldn't it be trivial to > add an > > 'end()' method to this iterator to indicate the end of the sequence > (just > > like C++ iterators) ? > > > > This would result in: > > > > for item in iterator: > > if iterator.next().end(): > > do_something_special > > > > do_something_for_all > > I think you've misunderstood the end() value in C++ STL iterators. It > is not the last item, but one past the last item. The iterator can take > the end value, but dereferencing the end value is illegal. That would be the case if I would check for iterator.end(), but I check for iterator.next().end() ! Tom From smurf at noris.de Fri Jul 19 08:03:13 2002 From: smurf at noris.de (Matthias Urlichs) Date: Fri, 19 Jul 2002 14:03:13 +0200 Subject: Recursion References: Message-ID: <1ffkjwu.1rdosep1g6a6qzN%smurf@noris.de> Abhijit Soman wrote: > def showbits(x): > if x != 1: > showbits(x >> 1) > if x & 01: > print 1, > else: > print 0, It's interesting that nobody seems to have caught the infinite recursion when you try to show a value which happens to be zero... -- Matthias Urlichs -- No cute .sig today... From fdrake at acm.org Wed Jul 3 01:10:00 2002 From: fdrake at acm.org (Fred L. Drake, Jr.) Date: Wed, 3 Jul 2002 01:10:00 -0400 Subject: [Doc-SIG] Re: [Python-Dev] [development doc updates] In-Reply-To: <20020702231715.GG25927@laranja.org> References: <20020702222813.8990118EC22@grendel.zope.com> <20020702231715.GG25927@laranja.org> Message-ID: <15650.34600.410233.510315@grendel.zope.com> Lalo Martins writes: > Re: textwrap.TextWrapper.fix_sentence_endings ... > Well, actually the convention of separating sentences by two spaces is also > specific to the English language, so I don't see that as a problem. Insidious, isn't it? I've tried to clarify the matter further in the documentation; please let me know if you think more is needed. -Fred -- Fred L. Drake, Jr. PythonLabs at Zope Corporation From BPettersen at NAREX.com Fri Jul 26 13:08:18 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 26 Jul 2002 11:08:18 -0600 Subject: how to count lines in a file ? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151DC@admin56.narex.com> > From: Alex Martelli [mailto:aleax at aleax.it] [snip] > It's not as bad as it looks. I wish there was some slightly > handier way to express try/finally, yes -- say the equivalent > of atexit but applied to exiting the current function, to > avoid the deep nesting and open/close separation that > try/finally may require: > > a = open('a') > try: > b = open('b') > try: > c = open('c') > try: > process(a,b,c) > finally: > c.close() > finally: > b.close() > finally: > a.close() If you make it a little more special purpose, I could propose syntax like e.g.: let a = open('a'): process(a) being equivalent to: a = None try: a = open('a') process(a) finally: del a assuming a's __del__ was guaranteed to close the file, although it would probably be safer to create a new statement like: close a which would call a.__close__ which would "do the right thing". Something like 'let' also works well with Python indentation. For a different approach you can look at Ruby which only has M/S GC, but also can guarantee file object lifetimes. -- bjorn From whisper at oz.net Fri Jul 12 16:49:49 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 12 Jul 2002 13:49:49 -0700 Subject: Is count supposed to still work? In-Reply-To: Message-ID: No! I'd never ever do anything like that! :o) Aren't these all built in anyway? I don't recall having to do it for len(mystring). David LeBlanc Seattle, WA USA > -----Original Message----- > From: Mark McEahern [mailto:marklists at mceahern.com] > Sent: Friday, July 12, 2002 13:41 > To: David LeBlanc; Python-List at Python. Org > Subject: RE: Is count supposed to still work? > > > > Whether or not you explicitly import string, > > count(mystring, substring) > > isn't working ("NameError: global name 'count' is not defined") > > You wouldn't perhaps be making this mistake I occasionally make, > would you? > > import foo > x = bar() # forgetting to say foo.bar() > > >From what I can see, count works: > > $ python > Python 2.2.1 (#1, Jun 25 2002, 10:55:46) > [GCC 2.95.3-5 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import string > >>> string.count("foo", "bar") > 0 > > Cheers, > > // mark > - > From jdhunter at ace.bsd.uchicago.edu Wed Jul 31 12:10:19 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 31 Jul 2002 11:10:19 -0500 Subject: signature for a file ? In-Reply-To: ("Shagshag13"'s message of "Wed, 31 Jul 2002 11:18:32 +0200") References: Message-ID: >>>>> "Shagshag13" == Shagshag13 writes: >> files. to do this i'm planning to write a python script that >> >would compute a kind of CRC32, MD5 or SHA (i'm really not >> competent in that >- so here i need advices and pointer to some >> implementations - and to know >which is the best to had a >> unique unambiguous signature for a file) and >then use it to >> find "doubles" : same size + same signature = probably same >> >file. >> >> That would be very useful indeed. (Concurs another >> disorganized person :-) You may be interested in the dircmp, which will give you reports on which files are in common in dirs A and B, which files are unique to A, which are unique to B, and so on... http://python.org/doc/current/lib/dircmp-objects.html This built-in library is (naturally) much more efficient than the script I posted because 1) It only computes sums on identical files. No need to check sums on files that have no other file the same size 2) It computes the sums of identically sized files in blocks and compares the files blockwise. No need to compute the entire sum if the first 1000 bytes differ. 3) It has a nice OO interface to get lists of common and unique files, and will recurs subdirs upon request. >>> import filecmp >>> x = filecmp.dircmp('mnet', 'mncvs') >>> x.report_full_closure() diff mnet mncvs Only in mnet : ['.cvsignore', 'Broker', 'Broker.bat', 'COPYING', 'CREDITS', 'ChangeLog', 'GNUmakefile', 'MacOSX', 'artwork', 'client', 'common', 'contenttypes', 'hackerdocs', 'linux', 'localweb', 'mnmods', 'overview.txt', 'rmnlib', 'server', 'tarexclude.txt', 'utilscripts', 'win32', 'wxBroker'] Only in mncvs : ['extsrc', 'mnet'] John Hunter From mgilfix at eecs.tufts.edu Tue Jul 23 17:44:51 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Tue, 23 Jul 2002 17:44:51 -0400 Subject: good books -- Python Essential Reference by David Beazley In-Reply-To: <3D3DCCBD.FEBE7086@cascade-sys.com>; from jb@cascade-sys.com on Tue, Jul 23, 2002 at 02:38:05PM -0700 References: <20020723133309.A20383@lifebook> <3D3DCCBD.FEBE7086@cascade-sys.com> Message-ID: <20020723174451.C3170@eecs.tufts.edu> In fact, if you have considerable experience with other programming languages, then you can use the Essential Reference as a cut-the-crap means of quickly learning Python. I did this myself and I found that the book delivered everything I needed to master the language and get a feel for its style. This may not be desirable for others who want to hear about the glory of OOP and its uses, etc., but I found the book to be fantastic. Definitely one of the better books I own. -- Mike On Tue, Jul 23 @ 14:38, James J. Besemer wrote: > > DIG wrote: > > > > If you want a book with a long shelf life, many including myself, > > > recommend Python Essential Reference by David Beazley. > > > > I agree with that. > > Me too. IIRC, there's a 2nd edition just out. > > --jb -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From cliechti at gmx.net Mon Jul 22 20:49:14 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 02:49:14 +0200 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> <7x7kjne14g.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in news:7x7kjne14g.fsf at ruckus.brouhaha.com: > Chris Liechti writes: >> considering the backwards incompatibility, it makes no sense to add a >> __call__ right now. > > What incompatibility? Do you think people are out there writing > modules with __call__ functions, and then depending on raising an > exception when they call the module directly? if a __call__ feature was added, it would of course only work in newer versions of python. so every code that uses this not backwards compatible. the value of having a __call__ is just not big enough to require a dependency on the latest python. when you do a try: module() except ??: module.__call__() just to be backwards compatible, its already a waste... you could have called __call__ directly and save the extra try:..except: and at the same time you could have given it a reasonable name. chris -- Chris From claird at starbase.neosoft.com Wed Jul 10 17:12:08 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 10 Jul 2002 16:12:08 -0500 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: In article , Steve Menard wrote: . . . >See, this is something I really don't understand. I will agree that PDF or >html would have been a better choice, but not everyone can generate PDF ya >know. With this kind of attitude, we'll forever be regarded as the >extremists who won't listen to anything .... > > Steve > > I'll leave aside for the moment all questions about whether: * distribution of information encoded in a .doc; * declining to download .doc-s; * refusal to agree to Microsoft EULAs; or * other stances are "extreme". I'll make a couple of technical points, though: * It is EXTREMELY rare that I receive a .doc whose content is not satisfactorily available through a simple strings(1) capture; * ReportLabs represents a delightfully Pythonic way to manage PDF. In fact, I'm working now on an article I think I'll entitle, "Everyone *can* generate PDF". -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From duncan at NOSPAMrcp.co.uk Wed Jul 10 06:50:41 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 10 Jul 2002 10:50:41 +0000 (UTC) Subject: PDf creating with Python? Howto? References: <3D2BE41E.3040508@weknowthewayout.com> Message-ID: Johan Holst Nielsen wrote in news:3D2BE41E.3040508 at weknowthewayout.com: > Im right now beginning a project where I have to make a generator to PDF > files. It includes images, and fonts (thats not are embedded in the > Adobe PDF specification). > > It have to be used for Offset printing, so all images must have a > resolution about 304 dpi. > > Anyone know tutorials or libraries in Python that can help me with this > project? See http://www.reportlab.com/toolkit. I think it should do everything you ask for. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tebeka at cs.bgu.ac.il Mon Jul 22 09:19:34 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 22 Jul 2002 06:19:34 -0700 Subject: Command history (up arrow) in IDLE on Windows 2000 References: <8d3e714e.0207212143.3b692496@posting.google.com> Message-ID: <33803989.0207220519.4e65b93d@posting.google.com> > Is it possible to enable command history in IDLE ? > I'm using version .8 on Windows 2000. It's really irritating not to > have command history, like in BASH or Cshell. >From IDLE Help/Help (F1) Command history: Alt-p retrieves previous command matching what you have typed Alt-n retrieves next Return while on any previous command retrieves that command Alt-/ (Expand word) is also useful here HTH. Miki From gumuz at looze.net Wed Jul 3 10:00:24 2002 From: gumuz at looze.net (Guyon Morée) Date: Wed, 3 Jul 2002 16:00:24 +0200 Subject: what's up with 'patterns'? References: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> <3D22F5FF.9070408@mxm.dk> <3d22fb61$0$235$4d4ebb8e@news.nl.uu.net> <3D22FE02.6050106@mxm.dk> Message-ID: <3d230282$0$224$4d4ebb8e@news.nl.uu.net> actually, i am re-writing my 'instant messaging server'. i first made a draft to check out how this socket-stuff works and now am re-writing it completely in objects. it's cool and all, but i feel the need of good 'pre-design' as i'm walking into walls sometimes which requires me to backtrack a lot. i hope 'patterns' can help me in solving these problems. thanx, guyon "Max M" wrote in message news:3D22FE02.6050106 at mxm.dk... > Guyon Mor?e wrote: > > > > is this something i should really look into or is it something that only is > > usefull when i am designing large systems and such? > > > You should definetively look into it, but only if you have allready > written some applications with objects. > > The leap from functional to patterns is probably to big. But if you have > done some apps with objects it might be a valuable experience rewriting > one, or part of it with the "Programming Patterns" book in one hand. > > regards Max M > From tsailipu at attbi.com Tue Jul 23 16:25:01 2002 From: tsailipu at attbi.com (Philip Tsai) Date: Tue, 23 Jul 2002 20:25:01 GMT Subject: Jython: any workaround for the missing array module References: <20f81d64.0207221651.6d57a39@posting.google.com> <3D3D2A29.7000906@ivs.tu-berlin.de> Message-ID: Right; jarray, however, only exposes two methods while the array module provides a number of useful methods. In my case, I have a (c)python class that manipulates an array of bits using array.array('I') structure. The class uses several array methods such as tostring() and fromstring(), which do not seem trivial to re-implement in python or jython.... Would you have any suggestion on how to implement such array methods (I guss at the end there is always the approach of looking into the source code and try to port it...)? Thanks, Philip "Andreas Ulbrich" wrote in message news:3D3D2A29.7000906 at ivs.tu-berlin.de... > Philip Tsai wrote: > > Hello group, > > > > I learned from Jython's documentation that the Python array module is > > currently unsupported. I am writing to see whether you would happen > > to know a clean, good workaround? So, instead of "import array" in > > the *.py, one can perhaps do something about equally easy and > > efficient in Jython.... > > > > Thanks much! > > Philip > > There is a jarray module. You can use it to build a Java-array and then > use everything Java provides to deal with arrays (so it's fairly > efficient). But you probably knew this already ... > From jb at cascade-sys.com Thu Jul 11 10:48:19 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 11 Jul 2002 07:48:19 -0700 Subject: Python in the enterprise: Pros and cons References: <3962B981CBF8BA3C.FC44CF01C7D6700F.D17D6744589A142C@lp.airnews.net> Message-ID: <3D2D9AB3.10901705@cascade-sys.com> Cameron Laird wrote: > While you probably recognized the humor in timbot's > reply, it's hard to appreciate from the outside its > analytic perfection. His definition PRECISELY cap- > tures the arrogance and anti-intellectualism that > "enterprise" generally bears. Correct. Many enterprise apps only handle peoples' money whereas most consumer, research and educational apps process vastly more valuable data. --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From edcjones at erols.com Sat Jul 6 17:50:30 2002 From: edcjones at erols.com (Edward C. Jones) Date: Sat, 06 Jul 2002 17:50:30 -0400 Subject: Python version of STL multimap? References: Message-ID: <3D276626.2060807@erols.com> Roy Smith wrote: > So, the question is, is there a standard way in Python to do multimaps, > or should I just continue to roll my own with one of the above idioms > whenever I need one? I wrote a module called MultiDict.py. It is at http://members.tripod.com/~edcjones/MultiDict.py it also contains class Table which is a two dimensional nested list viewed as a "relation" (a set of n-tuples). This is the same viewpoint used in SQL. Thanks, Edward C. Jones From a-steinhoff at web.de Wed Jul 17 07:05:19 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 17 Jul 2002 04:05:19 -0700 Subject: Making code faster References: <3d3445f9_7@news.newsgroups.com> Message-ID: JB wrote in message news:<3d3445f9_7 at news.newsgroups.com>... > How can I make the following code faster? I open a (text) > file and read the lines in the file. The lines of the file > have the form > > [,] > > After the lines have been loaded, I set up a new list via > the function tmp1. > > i = -1 > print 'loading file' > def tmp1(s): > global i > i += 1 > return QSimpleViewItem(i,self.sv.lv.newColor,eval(s)) > > try: > myfile = open(filename) > except: > pass > else: > tmp = myfile.readlines() > print 'lines loaded' > datei.close() > self.sv.lv.rows = map(tmp1,tmp) > self.sv.lv.visible = range(len(self.sv.lv.rows)) > print 'lines decoded',self.sv.lv.rows[0].col[0] > > Any ideas? It is astonishing that loading the lines ... how man lines? How long are the lines? > from external storage takes much less time than the mapping > itself! Have you considered to use Pyrex in order to convert it into a C module?? Armin From jkraska at san.rr.com Fri Jul 5 22:00:14 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 06 Jul 2002 02:00:14 GMT Subject: Why self? References: Message-ID: >Did you know that for larger projects people like to use "this->name" >or prefix the member variables with 'm_' to introduce expliciteness >into c++? Indeed, explicit self in Python solves the age old question: "what should I call my method arguments for data that stands for member attributes"? Ala, class C: i = 0 def setit ( self, i ): self.i = i In other environments, you're stuck doing things like: m_i = i; or... i = i_arg; ... a clear sign of a struggle to resolve mishandled ambiguity. So, the question should be, why on earth _confuse_ everything with implicit this? It really doesn't help. C// From loewis at informatik.hu-berlin.de Tue Jul 9 11:22:12 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Jul 2002 17:22:12 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: Piet van Oostrum writes: > I looked it up in The Online Edition of The Unicode Standard, Version 3.0 > In chapter 3, section 3.8 it said: > > Because every Unicode coded character sequence maps to a unique > sequence of code values in a given UTF, a reverse mapping can be > derived. Thus every UTF supports lossless roundtrip transcoding: > mapping from any Unicode coded character sequence S to a sequence > of code values and back will produce S again. To ensure that > round-trip transcoding is possible, a UTF mapping _must also_ map > invalid Unicode scalar values to unique code value sequences. These > invalid scalar values include FFFE, FFFF and unpaired surrogates. [...] > Technical Reports tr27 and tr28 do not withdraw this. Notice that this is a requirement onto UTFs, not onto implementations of Unicode. So the UTF must define a mapping. UTF-8 happens to map invalid code sequences to illegal byte sequences. Unicode 3.1 now mandates that such sequences are flagged as an error. > I found a long discussion in the i18n-sig archives in which you also > participated. One conclusion was that the Unicode standard contradicts > itself in this area. That may well be. If so, the implementation should chose the most likely interpretation. Since the requirement to flag errors is a new one, it is likely that this is intentional, and any text contradicting this requirement is in error. This is the interpretation that Python has chosen. Regards, Martin From mark.charsley at REMOVE_THIS.radioscape.com Thu Jul 4 05:45:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Thu, 4 Jul 2002 10:45 +0100 (BST) Subject: Forward Declaring Py_complex References: Message-ID: In article , gerhard.haering at gmx.de (Gerhard Haering) wrote: > In article , Mark Charsley wrote: > > Is there any way to forward declare Py_complex in C++ headers? > > #include "complexobject.h" should do the trick. Hmmm, my system also needed #include #include #include before complexobject.h. > > I'm trying to create a C++ function that returns a Py_complex, and > > would > > really prefer not to have to pull in all of Python.h in the header > > file. > > Any reason why? I can't think of any good reason. Compilation times. There are a lot of clients using the C++ class with the Py_Complex-returning member function. Many of them don't need to use the function at all, and those that do don't care about any python objects other than Py_Complex. As such if it's possible to say "a Py_Complex is just a struct with two doubles" or even "look, there's a struct called Py_Complex, kicking around that most of you don't care about. Those that do ought to look up it's details later, those that don't just take my word for it, and don't treat it as a syntax error" then I can avoid having to force all my class's clients from having to pull in a lot of header files that most of them don't care about. This will have two benefits: 1) build times won't be hit by having to process unnecessary headers for each cpp file 2) my workmates won't spend the next week moaning that I've broken their build and asking which directories they have to put in their project's include path to fix it. 1) I can live with, 2) is something I'd rather avoid :-) At the moment I've avoided the problem by having a tiny wrapper class I can forward-declare, but it would be nice to avoid having to copy the doubles between my wrapper class and a Py_Complex. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From martin at strakt.com Mon Jul 1 09:24:36 2002 From: martin at strakt.com (Martin =?iso-8859-1?Q?Sj=F6gren?=) Date: Mon, 1 Jul 2002 15:24:36 +0200 Subject: old thread: SSL support for socket module for server sockets In-Reply-To: References: Message-ID: <20020701132436.GA11101@ratthing-b3cf> On Mon, Jul 01, 2002 at 08:00:58AM +0200, Martin v. Loewis wrote: > Gerhard H?ring writes: > > > There was an old patch, that was rejected, and > > http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=452110 > > which I recommended not to include. > > I disagree. I think the standard SSL module is still the most > convenient one to use, and I encourage gradual improvements to > it. Waiting for the "big complete rewrite" likely means to wait > forever. > > Yes, there are alternative SSL modules, but unless their authors step > forward and contribute them, it is just as if they would not exist. I'm pretty sure that's what I did from the very start ;) Pretty soon I will release version 0.5 of pyOpenSSL, with both new features and bufixes. Laura tells me that you had some comments on pyOpenSSL, Martin? Feel free to mail me :) Regards, Martin (the other one ;)) -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From paoloinvernizzi at dmsware.com Fri Jul 12 03:48:49 2002 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Fri, 12 Jul 2002 07:48:49 GMT Subject: Automating MSDEV studio build process References: <60FB8BB7F0EFC7409B75EEEC13E201922151C2@admin56.narex.com> Message-ID: <3D2E8943.6070306@dmsware.com> And under VS7... C:\Program Files\Microsoft Visual Studio .NET\Common7\IDE>devenv /? Microsoft (R) Development Environment Version 7.00.9466. Copyright (C) Microsoft Corp 1984-2001. All rights reserved. Usage: devenv [solutionfile | projectfile | anyfile.ext] [switches] Cheer Paolo Invernizzi DMSWare.com From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 11 10:50:20 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 11 Jul 2002 16:50:20 +0200 Subject: Good SOAP lib for Python 2.2 Message-ID: <3D2D9B2C.3030606@NOSPAMREMOVETHISxs4all.nl> Hi I'm using Python 2.2.1 and I'm searching a current, up-to-date SOAP library for Python. I tried ZSI but it fails because apparently it uses an old XML api. What should I try instead? Thank you Irmen de Jong From chaynes at email.unc.edu Mon Jul 22 12:45:37 2002 From: chaynes at email.unc.edu (Chad Haynes) Date: 22 Jul 2002 09:45:37 -0700 Subject: setting the screen resolution Message-ID: <6edeb2ff.0207220845.86b6ebd@posting.google.com> i am currently working on a program using wxPython which requires the screen resolution to be 1024x768. is there a way to set this from python? -ch From brian at sweetapp.com Mon Jul 8 17:56:57 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 8 Jul 2002 14:56:57 -0700 Subject: Why self? In-Reply-To: <3D2A06F9.7050805@onsitetech.com> Message-ID: <001c01c226ca$61209610$bd5d4540@Dell2> Robb Schecter wrote: > > (1) All self variables have to be initialized in __init__. That's just > > good practice anyway. They are labeled with self in __init__ otherwise > > they are local. > > > > (2) There can be no name conflicts between local and self variables. > > Also good practice within an object. > > > > Good ideas. Or just do nothing: make self optional as in Java, and the > innermost scope is searched first if no self is given. I've done > years of Java programming, and have never had issues with instance vs. > local variables. It just really doesn't happen in practice because of > the differences in naming and usage of variables. In doesn't happen in practice because Java is much less dynamic than Python. The complete list of instance variables is known at compile time. The complete list of instance variables is not generally discoverable in Python (not even at runtime). Since variable declarations are not used, searching the innermost scope wouldn't work. Imagine this: def foo(): x = 5 How would you know if that is an instance variable or a local? > How does Ruby handle this? Instance variables are prefixed with '@'. > I think that any of these ideas are good. Yech. Cheers, Brian From pixie888 at hotmail.com Mon Jul 22 05:48:10 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Mon, 22 Jul 2002 09:48:10 GMT Subject: Python to Excell References: Message-ID: <3d3bd4aa.258337515@news.skynet.be> On Mon, 22 Jul 2002 09:49:33 +0100, Stefan Schukat wrote: >Search for excel8/9/10.olb an run makepy on it. There you'll have >all the classes available from Excel. > >or run "win32com.client.EnsureDispatch('Excel.Application', 0)" >and search the [PYTHON_ROOT]\Lib\site-packages\win32com\gen_py >directory for the generated module. When I try the code above I get: >>> import win32com >>> win32com.client.EnsureDispatch('Excel.Application', 0) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'win32com' module has no attribute 'client' >>> from win32com import client >>> win32com.client.EnsureDispatch('Excel.Application', 0) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'win32com.client' module has no attribute 'EnsureDispatch' Any idea? > >or use the macro recorder of excel and translate it to python code > >or use the excel online help > >or buy a book "Python Programming on Win32" > >or ... > > > Stefan > > >-----Original Message----- >From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] >Sent: Monday, July 22, 2002 8:33 AM >To: python-list at python.org >Subject: Python to Excell > > >Hi all, > >I want to use Python to automate Excell. What I want to do is writing >a script which updates an Excell sheet and which prints it out then. I >know the stuff about DispatchEx but I do not know the interface which >is exposed by Excell. Can anybody help me further on this one? > >Thanks, > >Henk >-- >http://mail.python.org/mailman/listinfo/python-list > > From emile at fenx.com Sun Jul 7 12:00:16 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 07 Jul 2002 16:00:16 GMT Subject: newbie-question: more then one constructor in a python-class? References: <3D285A64.6000904@snafu.de> Message-ID: T. Kaufmann > is there a way to have more (then one) constructors in a python-class (like in Java)? One common way is to use keyword arguments: class Test: def __init__(self, arg1=None, arg2=None, arg3=None): # do stuff based on the args passed -- Emile van Sebille emile at fenx.com --------- From emile at fenx.com Thu Jul 18 08:04:09 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Jul 2002 12:04:09 GMT Subject: Serial Port Returning Garbage. Why? References: Message-ID: max > IBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: > Invalid command.^M^JIBoot> 68.0.B^M^J^M^JError: Invalid commandexec > tftp192.^M^J^M^JError: Invalid command.^M^JIBoot> 68.0.B^M^J^M^JError: > Invalid commandexec tftp192.^M^J^M^JError: I > Could this be some variant of terminal character positioning codes that hyper terminal properly intercepts and interprets, but a direct ssh link doesn't? You might try testing with a terminal emulator that supports a hex dump mode. -- Emile van Sebille emile at fenx.com --------- From dougz at cs.washington.edu Wed Jul 17 16:41:40 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Wed, 17 Jul 2002 20:41:40 GMT Subject: hide mouse pointer in Tkinter Message-ID: How can I hide the mouse pointer in a Tkinter window? The Tk docs say that cursor "no" is an empty image, but on my system it's a slash-and-circle icon. I tried using Tk_GetCursorFromData to create an empty cursor, but this function always fails on Win32. From ods at fep.ru Thu Jul 18 10:36:31 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Thu, 18 Jul 2002 18:36:31 +0400 (MSD) Subject: property problem In-Reply-To: <3D36C65A.5040300@mplusr.de> Message-ID: On Thu, 18 Jul 2002, Peter Maas wrote: PM> class proptest: You must define new-style class (subclass object) to use descriptors. PM> PM> def __init__(self): PM> self.__data = 0 PM> PM> def get_data(self): PM> return self.__data PM> PM> def set_data(self, value): PM> self.__data = value PM> PM> data = property(get_data, set_data) PM> PM> def meth(self): PM> return self.__data PM> PM> This is my testcode: PM> PM> >>> x = proptest() PM> >>> x.data=234 PM> >>> x.data PM> 234 PM> >>> x.meth() PM> 0 PM> >>> x.set_data(234) PM> >>> x.meth() PM> 234 PM> PM> Explanation: PM> PM> The "data" property works but a change using the property PM> name doesn't show in meth(). If I use the access function PM> set_data PM> it works as expected. Is it my fault or Python's? -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From pyth at devel.trillke.net Mon Jul 1 04:54:38 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 1 Jul 2002 10:54:38 +0200 Subject: private In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192F1AA02@admin56.narex.com>; from BPettersen@NAREX.com on Sun, Jun 30, 2002 at 10:57:16PM -0600 References: <60FB8BB7F0EFC7409B75EEEC13E20192F1AA02@admin56.narex.com> Message-ID: <20020701105438.F10625@prim.han.de> Bjorn Pettersen wrote: > The OP asked about private vars/methods like C++. Above are three ways > to get around private in C++ without recompiling the (possibly third > party) C++ library you're #including. As you see, the private > declaration in C++ is mostly informational. In Python we use _ or __ > prepended to var/method names to achieve the same effect. Python does > have true private vars/methods through the Bastion module, but most > Pythonistas don't see the purpose. After all, if you can't trust your > developers you have bigger problems. nicely put. I'd apply this true axiom to security related stuff, also. I mean, we don't even know anything about 99% of the code we are running. All the secret services people may have long put trojan horses into huge amounts of free software. Good enough peer review only happens with the well known packages like apache/sendmail/python/... For the other gazillion software packages you have to trust the developers to be honest. If you can't trust your developers you have bigger problems. holger From roffe at aqualene.uio.no Fri Jul 19 12:17:23 2002 From: roffe at aqualene.uio.no (Rolf Marvin Bøe Lindgren) Date: Fri, 19 Jul 2002 18:17:23 +0200 Subject: [Q] wxPython - layout & placement Message-ID: I'm trying to place a button in a dialog window. this works: dlg = wxDialog(parent,-1,FileName,size=(400,400)) wxButton (parent=dlg, id = -1, label = 'This is a button', pos=(10,10)) dlg.ShowModal() but I'd like to use layout controls. I've figured out how to do it with wxPanel, but wxDialog doesn't seem to work the same way. the example on b = wxButton(self.panelA, 100, ' Panel A ') lc = wxLayoutConstraints() lc.centreX.SameAs (self.panelA, wxCentreX) lc.centreY.SameAs (self.panelA, wxCentreY) lc.height.AsIs () lc.width.PercentOf (self.panelA, wxWidth, 50) b.SetConstraints(lc) does not work if the parent object is a wxDialog. any clues? -- Rolf Lindgren http://www.roffe.com/ roffe at tag.uio.no From maxm at mxm.dk Wed Jul 3 16:28:46 2002 From: maxm at mxm.dk (Max M) Date: Wed, 03 Jul 2002 22:28:46 +0200 Subject: Patterns and all that new fangled stuff ... References: Message-ID: <3D235E7E.1090100@mxm.dk> Sean 'Shaleh' Perry wrote: >if your new facade class is only used once, in one place there is little >benefit. However if this type of thing occurs in several places you have no >limited your changes to one class rather than every call. > >A programmer must learn when to use a tool. Just because you have a toolbox >brimming with solutions does not mean you should use all of them on a single >project. > > No i know that. But the advantage in using the facade class, which is used only once per page, are these: - It uses the same approach on every page, making it easier to view at a glance what a single page does in a larger system. - It is possible to have a minimum amount of code in the .asp page, and develop more of the code in an ide with better debugger etc. - It is easier to unit-test the app, as the facade class is pure Python, and not dependent on .asp. - It eliminates most of the bugs I get when writing linear code, and then inserting a new line of code in a place where something isn't initialised yet, as all the data structures gets initialised in the __init__() method. - There are fewer namespace issues on long pages when using the facade with methods. - If the page is a controller it's easier to make it clear where the updating of persistent data from forms takes place with code like this: page = PageFacade(sagsId, artId) if req.has_key('save'): page.update(req) - In longer pages it is easier to se where the views are generated as they are always methods or attributes on the PageFacade object. In linear code it is not clear which one of the many variables that is also a view. So I think there are many of advantages, but it's just that it gets so verbose regards Max M -- "Sorry I would Really Like To Help More On This Project, But Am To Busy Doing Paid Work On A Tight Deadline" Max M From yduppen at xs4all.nl Thu Jul 25 14:39:32 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Thu, 25 Jul 2002 20:39:32 +0200 Subject: if(debug), optimized away? References: Message-ID: <3d4045be$0$94920$e4fe514c@dreader3.news.xs4all.nl> > if(debug): > if(items > 9): > print "fatal error..." > do_some_check_foo(42) > ... > > If I set debug=0, is this code optimized away as in most > C/C++?? compilers? I doubt it. However, if you use the (predefined) __debug__, it does get optimized away (at least, I think so). if __debug__: # do stuff Note that you cannot set __debug__; it is always true, except when running python with the -O flag. Furthermore, for checks such as these it is better to use the 'assert' keyword. This too is removed when python -O is used. assert items > 9, "Fatal error, too many items" YDD -- .sigmentation fault From pablo.pernot at albert.com Thu Jul 4 12:34:08 2002 From: pablo.pernot at albert.com (Pablo Pernot) Date: Thu, 04 Jul 2002 18:34:08 +0200 Subject: start working with gzip : probs with linux/windows Message-ID: Hello all, I started working with the gzip module. It works fine in full linux env. But when I upload (working with socket) gzip files in a windows env, the files appear corrupted. any clue ? Txs From akakakhel at attbi.com Sun Jul 28 20:40:52 2002 From: akakakhel at attbi.com (Ali K) Date: Mon, 29 Jul 2002 00:40:52 GMT Subject: Where to find freeze Message-ID: I would like to know where to find the freeze utitly or any other utility for making exe files. Please Reply!!! Thank You!!! From rotundo52 at hotmail.com Tue Jul 30 16:27:12 2002 From: rotundo52 at hotmail.com (Jon J. Morin) Date: 30 Jul 2002 13:27:12 -0700 Subject: code examples for rfc822 module? Message-ID: Does anyone know of any sites or other resources with code examples using the rfc822 modulde? I am writing an app that sends and receives email and I really don't understand the documentation on the python.org site (I'm kind of a Python newbie). Any help is appreciated. Sincerely, Jon J. Morin From jepler at unpythonic.net Thu Jul 11 19:45:24 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 11 Jul 2002 18:45:24 -0500 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <7934d084.0207111530.130b00b6@posting.google.com> References: <33803989.0207110328.5ef01f1e@posting.google.com> <7934d084.0207111530.130b00b6@posting.google.com> Message-ID: <20020711184523.B1008@unpythonic.net> On Thu, Jul 11, 2002 at 04:30:59PM -0700, Andrae Muys wrote: > aahz at pythoncraft.com (Aahz) wrote in message news:... > > In article <33803989.0207110328.5ef01f1e at posting.google.com>, > > Miki Tebeka wrote: > > > > > >Although it's in the Humor section I take the Python Zen > > >(http://www.python.org/doc/Humor.html#zen) quite seriously. > > >However I can understand what does “Sparse is better than > > >dense” means. > > > > To rephrase the dictum another way, "Don't try to stick too much code on > > one line." > > Well seeing as we are discussing Python Zen, the one I don't currently > understand is "Flat is better than Nested". I had always thought the Nested is A B C D flat is A B C D Python has lots of namespaces, but they're relatively flat. Usually, module->class->function or module->function, but with nested_scopes sometimes an additional level of function is seen. That's my take on it ... Jeff From ajs at ix.netcom.com Thu Jul 4 23:44:55 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Thu, 4 Jul 2002 23:44:55 -0400 Subject: __slot__ issues Message-ID: <001201c223d6$5676e080$0334fea9@carol> (The following is copy of my post to tutor at python.org. Since I believe it to involve a (minor) bug issue, I thought I'd copy it here for possible comment) Apologies to the folks who do not share my new found interest in slots. Which I am starting to think of as the quark of the Python object world. >>> class A(object): __slots__=("a") >>> class B(A): __slots__=("b") >>> b=B() >>> b.__slots__ 'b' >>> b.a=4 In other words "a" is somehow acting as a slot for B instances, but is not *in* B.__slots__. How would one then reference, introspect, whatever as to what are in fact available slots for instances of B? And a possibly minor bug: >>> class A(object): __slots__="a" >>> class B(object): pass >>> class C(A,B): __slots__=("b") >>> c=C() >>> c.a=1 >>> c.b=2 >>> c.c=3 Traceback (most recent call last): File "", line 1, in ? c.c=3 SystemError: C:\Code\221\Objects\dictobject.c:511: bad argument to internal function If B is a classic class and I do the same multi-inheritance I get the expected error message: AttributeError: 'C' object has no attribute 'c' So its the error message, not the behavior that I am pointing to as probably unintended. Art _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From shagshag13 at yahoo.fr Fri Jul 19 07:32:15 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 19 Jul 2002 13:32:15 +0200 Subject: file ops on the fly ? Message-ID: hello, is it possible (and how) to do "on the fly" reading and updating on file ? thanks in advance, s13. From achim.domma at syynx.de Wed Jul 3 15:32:05 2002 From: achim.domma at syynx.de (Achim Domma) Date: Wed, 3 Jul 2002 21:32:05 +0200 Subject: PythonMagick (with ImageMagick 5.4.7) Message-ID: Hi, I'm looking for somebody to provide PythonMagick binaries for non-windows plattforms. The project homepage is http://pythonmagick.procoders.net. If you are interested, please contact me to get the latest version. Achim From skip at pobox.com Tue Jul 30 22:25:51 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Jul 2002 21:25:51 -0500 Subject: How do you import a module with "." in its filename? In-Reply-To: <20020730183714.P13827-100000@mail.allcaps.org> References: <20020730183714.P13827-100000@mail.allcaps.org> Message-ID: <15687.19119.517381.21414@localhost.localdomain> Andrew> So, how do I import a module with "." in its filename? Take a look at the execfile builtin function. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 20:18:31 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 19:18:31 -0500 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: >>>>> "Mack" == Mack writes: Mack> I found out, however, that there were now three pythons in Mack> /usr/bin, python, python1.5 and python2. python were Mack> identical to python 1.5 so I just did a cp /usr/bin/python2 Mack> /usr/bin/python. I can always revert if somethings wrong. Revert, Revert! A lot of people put their nonstandard applications in /usr/local/bin. If you get the src distributions from python.org or some mirror, rather than the SRPMs that ship with redhat, the install will automatically go to the /usr/local dir by default. Don't know if you can do this with rpm. Also, you'll want to update your PATH environment var to make /usr/local/bin occur earlier than /usr/bin. In your bash config file, do some variant of export PATH=/usr/local/bin:/usr/bin Also note that there is a more elegant way than 'cp' to do what you did when you made python2 the default python. Say you have two pythons in /usr/local/bin, python2.1 and python2.2. You want to make one of these the default python. Do this with a symbolic link > cd /usr/local/python > ln -s python2.2 python > ls -l python* You'll see something like: lrwxrwxrwx 1 root root 9 Jul 18 09:10 python -> python2.2 -rwxr-xr-x 1 root root 2585908 May 31 14:38 python2.1 -rwxr-xr-x 1 root root 2335384 Jul 17 09:04 python2.2 So you haven't copied the file (and wasted space) but python now points to the latest version and it's easy to revert back to 2.1 by doing > rm python > ln -s python2.1 python Have fun, John Hutner From phr-n2002b at NOSPAMnightsong.com Mon Jul 8 00:13:34 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 21:13:34 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <7xwus7n5q4.fsf@ruckus.brouhaha.com> <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> Message-ID: <7xznx2j1qp.fsf@ruckus.brouhaha.com> claird at starbase.neosoft.com (Cameron Laird) writes: > You've mentioned once already that you might do more with your SQL. > I can imagine that much the greatest returns in performance will > come from writing more of your algorithms in SQL. That's likely to > be a more scalable and satisfying ap- proach than the > multi-processing complexities at which you've hinted. -- Actually, SQL tends to be awful slow too. Recent Oracle versions let you write stored procedures in Java, which are orders of magnitude faster than PL/SQL procedures. MySQL also has some alternate language interfaces for stored procedures now but I'm not up on them. From wdraxinger at darkstargames.de Fri Jul 12 18:57:56 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sat, 13 Jul 2002 00:57:56 +0200 Subject: How to exchange parts of builtin moudules/methods permanently using C-API Message-ID: <3D2F5EF4.1050505@darkstargames.de> I want to change sys.stdout, sys.stdin, sys.stderr permanently, so I replace them using e.g. PyObject_SetAttr(sys_module, "stdout", my_stdout) that work fine until a script does a del sys import sys reload(sys) After that my override is not longer valid. Another problem I have, is to prevent specific modules from loading/importing. Say I loaded a module spam, that conflicts internally with eggs or even a builtin module like os. How can I prevent those modules from loading in a elegant way? My idea was to set __builtins__.__import__ to a custom load function, that checks the name of the module and imports it, if it is not on the exclusion list. However I'm not sure if this cannot be overriden in some way and I wonder, if there is some C-API function lets me hook into the import process. -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From glc at well.com Mon Jul 15 14:33:44 2002 From: glc at well.com (Greg Chapman) Date: Mon, 15 Jul 2002 18:33:44 GMT Subject: cPickle and copy_reg.safe_constructors Message-ID: During its initialization, cPickle (in the init_stuff function) grabs a reference to copy_reg.safe_constructors; it appears this reference is never released. Unfortunately for me, this means that registered constructors are never released -- I have a constructor which holds a reference to a PyObject which I would like to have released to ensure that my module is cleaned up properly. I can work around the current behavior if necessary, but I was curious if this behavior should be considered a bug. Anyone have any idea? Thanks. --- Greg Chapman From pyth at devel.trillke.net Tue Jul 2 04:37:30 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 2 Jul 2002 10:37:30 +0200 Subject: python threads and the linuxthread pthread library In-Reply-To: <3D211DB1.70309@removethisandallhyphens-o-n-e.net>; from coventry@removethisandallhyphens-o-n-e.net.trillke.net on Mon, Jul 01, 2002 at 11:27:45PM -0400 References: <3D210EFB.51E375EA@earthlink.net> <3D211DB1.70309@removethisandallhyphens-o-n-e.net> Message-ID: <20020702103730.L10625@prim.han.de> - c o v e n t r y - wrote: > > > > > Does Jython lift this limitation, by any chance? Or is > > the GIL a universal and unchangable Python artifact? > > I don't know about jython, but _nothing_ is unchangeable (well, almost > nothing) - the GIL is whats used right now... Theres no reason to > believe that a non-GIL solution couldn't be found if people put thier > minds to it - it would be *hard*, and might break compatability (ACK!), > but it is possible. I have been told (at EuroPython and anywhere else) that removing the GIL is just too hard. I'd still like to agree with you :-) > How about a read-lock on global data? - all threads could maintain thier > own locals-state, and just lock on trying to read/write a global... > of course, first, all code in the current implementation would need to > be rentrant for true (OS) threads... I think its not that much about global data. Any object can be accessed from threads. Refcounting is the first problem. Modifying dictionaries and lists is the second. Coming to think of it, these two types are really the two types that underly *any* modification!?! Except maybe for the global and local namespaces which are highly optimized because of their importance. Other than dicts, lists, namespaces and refcounts what objects does python actually modify? (ints,strings,tuples,floats etc. are immutable). Based on these observations i'd guess that interesting stuff could be done. I'd like to check out if it is possible to make an object and everything it recursively references 'read-only'. This requires hacking dict-proxy objects at the C-level. They'd have to prevent write-access to themselves and everything they pass out (e.g. the value of an attribute lookup). Note that there have been discussions on python-dev about adding an observer-pattern to python objects (get notifications on object changes). I think this is much too heavy-weight and a simple read-only property would be enough for many use-cases. Most important it would support Copy-On-Write (COW) - semantics. Very important for transactional systems which have a lot more reads than writes (like e.g. Zope). Ultimately i'd really like to have extremly lightweight transactional behaviour at the language level. Of course this doesn't really answer any of your questions about the GIL but i have the gut feeling that having read-only mechanisms at the type level would be a step towards a relaxed GIL handling ... really just my 2c, holger From duncan at NOSPAMrcp.co.uk Tue Jul 16 04:26:08 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 16 Jul 2002 08:26:08 +0000 (UTC) Subject: Common list in distinct objects' References: <3d331fa9.361390031@news.byu.edu> <3d332491.362646438@news.byu.edu> Message-ID: otijim at yahoo.com (Jake R) wrote in news:3d332491.362646438 at news.byu.edu: > Now that I think about it some more I seem to remember reading > somewhere in the tutorial that class definition is only processed once > and being so means that the default list (myList=[]) in my __init__ is > only created once and thus any objects created all point to the same > list unless I create a new list (ie pass one in or have the __init__ > function do it when its called) > > Does that sound right? Still....I don't think thats what way it ought > to behave. Please read the FAQ entry number 6.25: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.025.htp It is all extremely logical once you understand what is going on, but admittedly can be confusing for beginners. You might also find it useful to read the eff-bot guide to Python objects at http://effbot.org/guides/python-objects.htm to make sure you understand how Python's objects and assignments work. Also the tutorial section 4.7.1 has the 'important warning' that you half remembered. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gerhard.haering at gmx.de Tue Jul 2 21:45:03 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 3 Jul 2002 03:45:03 +0200 Subject: what can i expect... In-Reply-To: References: Message-ID: <20020703014503.GB3084@lilith.my-fqdn.de> Hi "Shagshag13", * Shagshag13 [2002-07-02 17:03 +0200]: > what can i expect if i change my python application to java? Wasted time. > (or when do you think it's time to change parts of python code to > java? This will IMO rarely make sense. > for what purposes?) Except if your dominatrix is on vacation and you haven't got your share of pain recently ;-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 15.2 ?C Wind: 2.4 m/s From jacek.generowicz at cern.ch Thu Jul 11 03:18:18 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jul 2002 09:18:18 +0200 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: "Matt Gerrans" writes: > > ... I take doc extensions to mean "This document is intended > > for Microsoft customers only". > > Or "Open this to install the latest VBScript virus on your machine" Fortunately enough, not being a Microsoft customer (or pirate) offers strong protection against VBScript viruses :-) From raims at dot.com Fri Jul 12 06:26:58 2002 From: raims at dot.com (Rhymes) Date: Fri, 12 Jul 2002 12:26:58 +0200 Subject: What went wrong in Python1.6 ? Message-ID: I've just read this in "Dive Into Python" online book... ------- Actually, Python has had unicode support since version 1.6, but version 1.6 was a contractual obligation release that nobody likes to talk about, a bastard stepchild of a hippie youth best left forgotten. Even the official Python documentation claims that unicode was ?new in version 2.0. It's a lie, but, like the lies of presidents who say they inhaled but didn't enjoy it, we choose to believe it because we remember our own misspent youths a bit too vividly. ------ Now I ask my self: what went wrong in that release? Where i could find some further infos about this "miscarriage" ? thanks in advance -- Rhymes rhymes at myself.com " ride or die " From heikowu at ceosg.de Mon Jul 29 12:19:42 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 29 Jul 2002 18:19:42 +0200 Subject: What is a glue language? In-Reply-To: References: Message-ID: <1027959582.2947.5663.camel@d168.stw.stud.uni-saarland.de> Hi Jens! Also, kurze Erkl?rung zu "glue language": Eine Sprache, die die Integration von anderen Paketen/Modulen sehr gut geeignet ist. Python versteht sich als solche, da Python sehr viele Schnittstellen zu propriet?ren/heterogenen Systemen besitzt (z.B. lassen sich COM-Objekte unter Windows mit Python steuern), und genauso ist es (relativ) einfach einen Python-Wrapper f?r eine C/C++/etc.-Library zu schreiben. Da es sehr viele Leute gibt, die sich bereits ums schreiben von diesen Schnittstellen gek?mmert haben, kannst Du also halt relativ schnell loslegen. Kleines Beispiel: Du schreibt ein Datenbank-Frontend unter Windows, was sowohl mit einer MySQL-Datenbank arbeiten muss, aber zu den Eintr?gen aus der MySQL-Datenbank sind auch noch Eintr?ge aus einem Apache-Log zu lesen (1 zu 1 Entsprechnung), und des weiteren gibt es noch einen Mail-Account, bei dem Mails zu manchen Eintr?gen in der MySQL-Datenbank eintrudeln, allerdings kann ich auf diesen Mail-Account nur ?ber IMAP zugreifen... H?rt sich kompliziert an? Ist es nicht. Kleine Erkl?rung zum Programm: In der MySQL-Datenbank sind Logging-Eintr?ge eines Webscripts, genauer gesagt vorl?ufige Registrierungen von Benutzern. Der Webmaster m?chte sich gerne anschauen, welchen Log-Eintrag Apache zu diesem Benutzer gemacht hat, und Benutzer antworten auf ihre Registrierung mit einer Mail, in der ihre Best?tigungs-Nummer drin steht. Soweit so klar? Dann gibt es noch ein Web-Script, was eine _Excel_-Datei "on the fly" erzeugen soll, in der Statistiken des Webscripts stehen. Unm?glich? Nein. Hier kommt dann COM ins Spiel. usw. Python ist bei meinen ganzen Projekten (ich hab mehrere in der Art) immer der "Kleister" zwischen den verschiedenen propriet?ren/heterogenen Systemen gewesen. Ich w?sste nicht, wie ich das (einfach) in C programmieren sollte (besonders das zweite Beispiel). Darum bezeichnet man Python als "Kleister-Sprache" (fast w?rtliche ?bersetzung von "glue language"). Hope this helps! Heiko W. From peter at engcorp.com Fri Jul 12 04:27:29 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Jul 2002 04:27:29 -0400 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) References: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: <3D2E92F1.F67BCB04@engcorp.com> Ian Bicking wrote: > > Unlike most of the other people in this thread, I always thought of > sparse v. dense as a syntactic/semantic issue. > > For instance, I think Perl is a very syntactically dense language. If > you change one character, you'll probably end up with a valid -- and > different -- piece of code. Every meaning is being squeezed out of the > available combinations of characters. This is really coming out with > Perl 6 too, it seems. > > Python isn't like that at all -- there's a lot of punctuation that isn't > even used. There's also a fair amount of redundancy -- for instance, a > colon introduces a block, even though the block explains itself through > its indentation. Good call. I think you must be right about that, relative to the less useful whitespace issue. Of course, "right" doesn't apply here -- I just mean your approach is ultimately more useful than one applying only to ASCII 0x20... In a trivial way, this also expresses the rationale behind longer but more descriptive and pronouncable variable names, relative to the Hungarian notation-inspired and -sired abominations that we still sometimes see (but more rarely in Python I think). -Peter From aleax at aleax.it Sat Jul 27 03:11:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 07:11:46 GMT Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: Jeremy Bowers wrote: ... >> for word in 'fee fie foo fum'.split(): >> Button(frame, command=lambda: print word) >> >> The poster is typically nonplusses that all buttons print 'fum'. > > Speaking as one who recently posted this, what's the alternative? > > for word in 'fee fie foo fum'.split(): > def printThing(): > print word > Button(frame, printThing) > > doesn't work any better, you still need > > for word in 'fee fie foo fum'.split(): > def printThing(word = word): > print word > Button(frame, printThing) Not sure why you snipped the closure solution, which looks like the obvious one to me once one has seen it: def makePrinter(word): def printit(): print word return printit for word in 'fee fie foo fum'.split(): Button(frame, command=makePrinter(word)) > Lambda wart, or just scoping wart in general? Not sure if it qualifies as a "wart", just as a little trap which is empirically observed to catch users of lambdas, not users of named functions. I've never met anybody who expected the solution with 'def' in the loop to somehow snapshot the values in the surrounding environment (maybe I've just led a sheltered life?), while several users of lambda seem to expect exactly that. Given which, touting the appropriateness of lambda's scoping seems weird! > (And I'll still take the lambda form; the def statement feels wrong here.) Guess that's what wrong with having lambda in the language: without adding any capability, it gives two ways to solve some problems, one of which feels wrong to you, the other one of which IS wrong. Because, you see, I put a little trap in this example... and it seems to me that you fell right into it. The lambda solution doesn't work. At all. It gives you a SyntaxError if you try it! lambda cannot include a statement. print is a statement. Oooops...!-) So, if you structure your code with lambda, the moment you want to add a print statement, boom -- can't do. You have to restructure your code to use def instead. When you remove the print after it's done its debugging-help job, will you restructure once again to take the def away in favor of lambda... and again NEXT time you need to have a statement there too, etc, etc...? What a lot of purposeless code churning...! Use def and avoid all of this silly self-imposed useless work. Alex From pyth at devel.trillke.net Tue Jul 2 04:00:46 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 2 Jul 2002 10:00:46 +0200 Subject: I'd give up Perl tomorrow if only... In-Reply-To: ; from brueckd@tbye.com on Tue, Jul 02, 2002 at 12:48:24AM -0700 References: <20020701124340.G10625@prim.han.de> Message-ID: <20020702100046.K10625@prim.han.de> brueckd at tbye.com wrote: > On Mon, 1 Jul 2002, holger krekel wrote: > > IMO the standard-lib approach doesn't scale very well. > > Python seems to get to a stage where the google-path doesn't cut it, either. > > I don't think it scales that well, either, and I agree that it's not > the best long-term solution, but for now it seems to be an > important-but-not-urgent type of problem. That's why I think it's a good > idea to keep working on a solution. IOW, if one's focus is on the present > and they say, "we need CPYN" I say, "nah", but if one's focus is on the > future I say, "yeah". :) > > > >From Guidos keynote at EuroPython i recall some statistics about python's > > growth. A Comprehensive Python Network (CPYN) could accomodate and support > > this growth. Better sooner than later, not? > > Sure... I'm just musing that (1) when it becomes urgent (or a little > sooner) I'm fully confident it'll get built and that (2) not being too > urgent is why it hasn't happened yet. So we almost agree (for an approriate definition of almost :-) IMO building such a system requires a lot of motiviation for people to actually do it. Saying "not urgent" is slightly discouraging ... I don't think that's your intention, though. In fact, i have noticed people getting stuck in improving python standard lib because it requires a lot of buerocracy to get it distributed. Lowering the barrier for improvements is very important right now. holger From renzo.tomaselli at tecnotp.it Thu Jul 4 12:05:52 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: Thu, 4 Jul 2002 18:05:52 +0200 Subject: Embedding: how to extend a C++ instance by Python methods Message-ID: Hi all, my current goal is to extend a C++ instance behavior by a Python method, so that an explicit "execute(scriptName, args)" method on such instance will end up into running a Python method defined by scriptName. Such script should be entered having "self " as pointing to a C object wrapping the above instance, so that a number of predefined methods (implemented in C++) are available from within the script. While I know how to extend Python by C++ objects, what I miss here is about binding script execution to the calling C++ object. This is done for the purpose of avoiding script definers to take care of walking from some module-level functions down to actual class methods, which is pretty straightforward to implement. In short, only method body should be Python; class definition should be C++. Any help will be appreciated, Renzo Tomaselli From jepler at unpythonic.net Fri Jul 5 14:27:33 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 5 Jul 2002 13:27:33 -0500 Subject: replacing instance __setattr__ In-Reply-To: References: Message-ID: <20020705182727.GA2269@unpythonic.net> On Fri, Jul 05, 2002 at 04:45:45PM +0000, Alex Martelli wrote: > This doesn't impede your abilities to customize an instance, without > affecting other instances of the same class: > > def changeSpecial(inst, name, function): > class Customized(inst.__class__): pass > setattr(customized, name, function) > inst.__class__ = Customized why not def changeSpecial(inst, name, function): method = new.instancemethod(function, inst, inst.__class__) setattr(inst, name, method) >>> def f(self, x): print x ... >>> class C: pass ... >>> c = C() >>> changeSpecial(c, 'f', f) >>> c.f(3) 3 No setting of the __class__ attribute here, which is something that gives me more willies than calling new.instancemethod and doing a setattr on the instance... Jeff From tl_news at nexgo.de Wed Jul 24 00:51:59 2002 From: tl_news at nexgo.de (Tino Lange) Date: Wed, 24 Jul 2002 06:51:59 +0200 Subject: ANNOUNCE: proctitle - manipulate 'argv[]' (process listing) of the Python process References: Message-ID: On Mon, 22 Jul 2002 20:00:55 -0400, Dave Cinege wrote: > I produced a [module] that allow[s] >changing the raw argv[] of the python process. Great! That's what I was looking for! Thanks a lot! Tino From cliechti at gmx.net Sat Jul 27 11:16:52 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jul 2002 17:16:52 +0200 Subject: xrange questioin References: Message-ID: Uwe Schmitt wrote in news:ahubfn$hj80t$1 at hades.rz.uni-sb.de: > as xrange() comsumes less memory than range() I ask why > I should use range() at all.... is there any benifit > from using range() ??? with range you get a true list which you can manipulate, sort, reverse, etc ... you can't do that with xrange. chris -- Chris From logiplexsoftware at earthlink.net Wed Jul 3 14:33:23 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 11:33:23 -0700 Subject: HT clear some wxPython fram? In-Reply-To: <461DRL43N61JI74JFGC71HG43FEJG.3d233f7a@FRITZweb> References: <20020703110607.00c02458.logiplexsoftware@earthlink.net> <461DRL43N61JI74JFGC71HG43FEJG.3d233f7a@FRITZweb> Message-ID: <20020703113323.5e7fb74d.logiplexsoftware@earthlink.net> On Wed, 03 Jul 2002 20:16:26 +0200 Klaus Reinhardt wrote: > Am 03.07.02 20:06:07, schrieb Cliff Wells : > > >On Wed, 03 Jul 2002 19:39:04 +0200 > >Klaus Reinhardt wrote: > > > >> >> HOW I CAN CLEAR SOME FRAME? > >What do you want to clear from the frame? You've put nothing into it. I think > >you are confusing the stdout window with the frame. If you notice, when you > >run your program, two windows open. The first one with the title "Close me" is > >the frame. The second window titled "wxPython stdout/stderr" is not the frame. > > I could be wrong, but I don't think there's any way to control the > >stdout/stderr window. It's mostly for debugging purposes. > > > >What you will want to do instead is something more like this: > > --------------------------------------------------------------------- > Hi > I will try this (here cut). > BUT: > > Aktive Verbindungen > > Proto Lokale Adresse Remote-Adresse Status > TCP 0.0.0.0:1117 0.0.0.0:0 LISTENING > TCP 127.0.0.1:4711 0.0.0.0:0 LISTENING > TCP 217.81.119.164:1117 130.149.5.227:22 ESTABLISHED > > This is shown in the "wxPython stdout/stderr"-frame. > (I'm a completely newby to python and OOP) What you will want to do is modify the source I sent you to display your text rather than "hello": def OnTimer(self, evt): self.panel.write("hello") # <- change this line to display your text Here is a modified example that adds an additional method writelines() to MyPanel and will perhaps make it clearer: from wxPython.wx import * import os class MyPanel(wxPanel): def __init__(self, parent): wxPanel.__init__(self, parent, -1) self.SetBackgroundColour(wxWHITE) self.text = [] EVT_PAINT(self, self.OnPaint) def OnPaint(self, event): dc = wxPaintDC(self) self.draw(dc) def write(self, text): self.text.append(text) if len(self.text) > 10: del self.text[0] dc = wxClientDC(self) self.draw(dc) def writelines(self, lines): self.text = lines dc = wxClientDC(self) self.draw(dc) def draw(self, dc): dc.Clear() y = 0 for t in self.text: dc.DrawText(t, 0, y) y += 15 class MyFrame(wxFrame): def __init__(self): wxFrame.__init__(self, None, -1, "MyFrame") self.panel = MyPanel(self) self.timer = wxTimer(self, -1) self.timer.Start(100) EVT_TIMER(self, -1, self.OnTimer) def OnTimer(self, evt): lines = os.popen('netstat -a -n','r').readlines() # do some filtering/formatting here lines = filter(lambda l: l.split()[0] == 'tcp', lines) self.panel.writelines(lines) def OnClose(self,event): self.timer.Stop() self.Destroy() class MyApp(wxApp): def OnInit(self): frame = MyFrame() frame.Show(true) return true app = MyApp() app.MainLoop() -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From jonathan at onegoodidea.com Tue Jul 16 07:43:06 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 16 Jul 2002 12:43:06 +0100 Subject: Python's Lisp heritage References: Message-ID: On 15/7/2002 21:35, in article agvbln$ouqal$2 at ID-125932.news.dfncis.de, "Christopher Browne" wrote: > If all you have is lexical scoping, parameters have to get explicitly > passed down the chain in order to get from function A to function C. > That means introducing additional parameters to function B, which > didn't actually care about those extra values. > > Most of the time, lexical scope is likely to be more useful. But > there are places where dynamic scope is to be preferred. I don't have an opinion either way really, but I just thought I'd throw another reference into the discussion. There is an extension to Haskell which is implemented by GHC (at least) to solve just this problem: Implicit Parameters Functions may take implicit parameters due to a statically-typed extension that gives the advantages of dynamic scope without its worst excesses (see the POPL paper for the details). So you don't need to read the paper to get an example. It looks something like this: > sort :: (?cmp :: a -> a -> Bool) => [a] -> [a] is a type definition of a 'sort' function that takes an implicit 'cmp' parameter for the comparison function. Any function that uses 'sort' inherits 'cmp' as an implicit parameter, e.g.: the type of > least xs = fst (sort xs) is > least :: (?cmp :: a -> a -> Bool) => [a] -> a At some point, you can bind the implicit parameter with: > min :: [a] -> a > min = let ?cmp = (<=) in least Of course this is all statically-typed, but it's an interesting way to "tunnel" parameters through existing code. Jonathan From fakeaddress at nowhere.org Sun Jul 28 02:00:43 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 28 Jul 2002 06:00:43 GMT Subject: How to detect the last element in a for loop References: Message-ID: <3D4388C8.6040005@nowhere.org> Tom Verbeure wrote: [...] > I am not familiar with iterators as objects in Python. I understand that > > for a in myList: > ... > > will result in an implicit iterator on myList. For a simple solution, how about: for a in myList[:-1]: do_stuff(a) special_stuff(myList[-1]) [...] > Given that you have an explicit iterator, wouldn't it be trivial to add an > 'end()' method to this iterator to indicate the end of the sequence (just > like C++ iterators) ? > > This would result in: > > for item in iterator: > if iterator.next().end(): > do_something_special > > do_something_for_all I think you've misunderstood the end() value in C++ STL iterators. It is not the last item, but one past the last item. The iterator can take the end value, but dereferencing the end value is illegal. --Bryan From michael.grabietz at img-online.de Thu Jul 18 13:44:30 2002 From: michael.grabietz at img-online.de (Michael Grabietz) Date: Thu, 18 Jul 2002 19:44:30 +0200 Subject: Link problem embedding Python, gcc, Python 2.1, Suse7.3 Message-ID: <3D36FE7E.3020707@img-online.de> Hi, OS: Linux SuSe 7.3 gcc: V2.95.3 Python: 2.1 Numeric: V21 I have a problem while linking a small test application which embeds Python via high level embedding in a C program. I am rather new to C and Python. Under Windows I could link the program with Python using MS C++ without problems. Under Linux some references could not be resolved. Hope anybody out there can help me or has an idea how to go on. Regards, Michael ----------------------------------------------------------------------- C-Code: #include #include extern void sub2_c(void) { printf("Hallo von sub2_c !\n"); PyRun_SimpleString("from Numeric import *\n" "from type3000_script_test01 import *\n" "inpt=zeros((3),Float)\n" ); // Funktionierte noch nicht ! 17.07.2002 // PyRun_SimpleFile("main__type3000_script_test01.py"); } ----------------------------------------------------------------------- Command line: gcc main1_c.c sub1_c.c libpython2.1.a -I/usr/include/python ----------------------------------------------------------------------- Error message: libpython2.1.a(posixmodule.o): In function `posix_tmpnam': posixmodule.o(.text+0x3206): the use of `tmpnam_r' is dangerous, better use `mkstemp' libpython2.1.a(posixmodule.o): In function `posix_tempnam': posixmodule.o(.text+0x3122): the use of `tempnam' is dangerous, better use `mkstemp' libpython2.1.a(floatobject.o): In function `float_pow': floatobject.o(.text+0xe4e): undefined reference to `pow' libpython2.1.a(dynload_shlib.o): In function `_PyImport_GetDynLoadFunc': dynload_shlib.o(.text+0x18a): undefined reference to `dlopen' dynload_shlib.o(.text+0x19b): undefined reference to `dlerror' dynload_shlib.o(.text+0x1f5): undefined reference to `dlsym' libpython2.1.a(thread.o): In function `PyThread_start_new_thread': thread.o(.text+0x71): undefined reference to `pthread_create' thread.o(.text+0x86): undefined reference to `pthread_detach' libpython2.1.a(posixmodule.o): In function `posix_openpty': posixmodule.o(.text+0x15c3): undefined reference to `openpty' libpython2.1.a(posixmodule.o): In function `posix_forkpty': posixmodule.o(.text+0x163d): undefined reference to `forkpty' libpython2.1.a(complexobject.o): In function `_Py_c_pow': complexobject.o(.text+0x33d): undefined reference to `pow' complexobject.o(.text+0x37a): undefined reference to `exp' complexobject.o(.text+0x38e): undefined reference to `log' complexobject.o(.text+0x3ae): undefined reference to `cos' complexobject.o(.text+0x3c4): undefined reference to `sin' collect2: ld returned 1 exit status From dale at riverhall.NOTHANKS.co.uk Wed Jul 31 16:35:05 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Wed, 31 Jul 2002 21:35:05 +0100 Subject: urlparse isn't working? Message-ID: <51igkuo7u1ab6s9270svf7pbakusvjr2vj@4ax.com> This doesn't seem right to me: >>> import urlparse >>> urlparse.urlparse('www.wibble.com/wibble/wibble.jpg', 'http:') ('http:', '', 'www.wibble.com/wibble/wibble.jpg', '', '', '') According to the help file: === Example: urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') yields the tuple ('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '') === it should split the host from the path. I've tried different values for the second parameter (called 'default_scheme') with the same result. However, if you add "http://" to the url, it starts to behave: >>> urlparse.urlparse('http://www.wibble.com/wibble/wibble.jpg') ('http', 'www.wibble.com', '/wibble/wibble.jpg', '', '', '') So what is the point of the 'default_scheme' if it needs to be on the url to work properly? Or have I got confused? -- Dale Strickland-Clark Riverhall Systems Ltd From tim.one at comcast.net Tue Jul 9 00:23:55 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 09 Jul 2002 00:23:55 -0400 Subject: replacing instance __setattr__ In-Reply-To: Message-ID: [Aahz] > Your argument appears to be failing my duck test: > > import new > > class C: > def __init__(self, val): > self.val = val > > def __str__(self): > return str(self.val).upper() > > x = C('foo') > x.__str__ = new.instancemethod(__str__, x, C) > print str(x) > > What am I missing? Try deriving C from object and see what it prints. This is an area where new-style classes behave more rationally. x.__str__ ends up being a bound method object in either case (which, despite the "method" in the name, is not a method -- it's just a callable function at that point, and is a data attribute of x). Old-style classes do look at data attributes first; new-style classes don't; and I do believe I was unclear about that distinction. BTW, bound method objects aren't methods because they're bound : the OO part of "a method" is the part that figures out where to dispatch to, and in a bound method object that part has already been computed and frozen (cached in the BMO). At the point it's just a flavor of ordinary function. From cliechti at gmx.net Wed Jul 3 17:28:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 3 Jul 2002 23:28:01 +0200 Subject: PythonWin + other GUIs = CRASH! References: <3D232FEE.3010606@gmx.de> Message-ID: Ingo Linkweiler wrote in news:3D232FEE.3010606 at gmx.de: > Hi, > > when using the PythonWin IDE with other GUI-Toolkits (Qt, wxPython, > Pygame), the application crashes or freezes when running them with > "file->run". > > Is it possible to avoid this? yes! with my PythonWin patch that runs the script in a separate process. watch this space for an annoucement, when i put it on my homepage. chris -- Chris From raimo-news at mail.com Wed Jul 31 18:51:59 2002 From: raimo-news at mail.com (Raimo Tuisku) Date: Thu, 01 Aug 2002 01:51:59 +0300 Subject: Tkinter.Text: prevent user modifications Message-ID: What is the best way to prevent user from editing the contents of Tkinter.Text wiget but editing from the code would be possible. config(state) changes this, but then Tkinter.Text.insert won't work. Do I have to change the behavior of the widget every time I insert text or is there another way? Is it possible that the user can edit it when the state configuration is temporarily changed?-) -- Raimo Tuisku From marklists at mceahern.com Mon Jul 15 15:31:22 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 15 Jul 2002 14:31:22 -0500 Subject: switch recipe? In-Reply-To: Message-ID: [Emile van Sebille] > doesn't this do it? > > generated = [color_item(x, alternator) for x in iterator] > > (BTW, I nominate cycler as a name for alternator ;-) I like cycler, too. I'm going to post a summary of solutions shortly. The above works if you say alternator.next(). // m - From tim at zope.com Thu Jul 25 18:37:00 2002 From: tim at zope.com (Tim Peters) Date: Thu, 25 Jul 2002 18:37:00 -0400 Subject: random 64-bit int In-Reply-To: Message-ID: [Tim] > A Python float is a C double, which on most boxes has 53 bits of > precision. That means, e.g., that there are 2**53 distinct Python floats > in the range [0.5, 1.0) alone. ... [Bengt Richter] > It's a lot of floats, but I think your number should be 52, for > bits representing the fraction bits below the single implicit bit that > represents 0.5 or 0.25 etc. Right you are! If you exhaust those 2**52, feel free to sue me for the other 2**52 I claimed were there . From bobx at linuxmail.org Sat Jul 13 11:01:29 2002 From: bobx at linuxmail.org (Bob X) Date: Sat, 13 Jul 2002 15:01:29 GMT Subject: Guido van Rossum Tutorial - .PDF or other format? References: <3D2F58A7.4080304@linuxmail.org> Message-ID: <3D3040F3.8010500@linuxmail.org> David Wright wrote: >>The PDF version *used* to have problems printing with Acrobat Reader. >>Don't know if that is fixed yet. >> > > > Hi Bob, > > Just so you know...I printed the .pdf version. It emerged from the printer > in a beautiful font, despite the rather 'awful' fuzzy veneer in the Acrobat > Reader interface. > > Thanks everyone Cool...I will have to go get the latest and try again! From aahz at pythoncraft.com Sun Jul 21 09:31:58 2002 From: aahz at pythoncraft.com (Aahz) Date: 21 Jul 2002 09:31:58 -0400 Subject: maximum recursion depth References: Message-ID: In article , Paul wrote: > >My question to you: Is there a way to change the limit of the recursion >depth? http://www.stackless.com/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From chicken7373 at yahoo.com Mon Jul 15 17:04:28 2002 From: chicken7373 at yahoo.com (Becky Hehn) Date: Mon, 15 Jul 2002 14:04:28 -0700 (PDT) Subject: Newbie: Capture output of compile_dir Message-ID: <20020715210428.52622.qmail@web13001.mail.yahoo.com> In-Reply-To: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Thanks for the response. I tried the code you gave me, but it didn't quite work like I wanted. I created a syntax error in my python file (left out a quotation mark) and tried the code. Below is the information from my interpreter session: >>> import sys >>> from cStringIO import StringIO >>> from compileall import compile_dir >>> path='/home/hehn/test' >>> orig_so = sys.stdout >>> sys.stdout = captured = StringIO() >>> compile_dir(path,force=1) File "/home/hehn/test/me.py", line 2 Write('status) Syntax Error: invalid token >>> sys.stdout = orig_so >>> output = captured.getvalue() >>> output 'Listing /home/hehn/test . . . Compiling /home/hehn/test/me.py' If an the prompt I just type the compile command, I get all the output at once(see below). I would like the output variable to contain all this feedback from the compile_dir command. Not just the initial two lines. Any thoughts on what I did wrong? Thank you in advance. >>> compile_dir(path,force=1) Listing /home/hehn/test . . . Compiling /home/hehn/test/me.py . . . File /home/hehn/test/me.py, line 2 Write('status) Syntax Error: invalid token 1 --- "Denis S. Otkidach" wrote: > On Mon, 15 Jul 2002, Becky Hehn wrote: > > BH> > BH> I want to be able to capture the output of > compile_dir > BH> because I want to further process the output of > this > BH> command. It appears that compile_dir prints > output to > BH> the screen rather than returning it to the > caller. > BH> How do I capture the output of this command? If > I do > BH> something like: > BH> output=compile_dir(path) > BH> the output of compile_dir gets printed to the > screen > BH> and the variable output just hold an integer. > > import sys > from cStringIO import StringIO > orig_so = sys.stdout > sys.stdout = captured = StringIO() > compile_dir(path) > sys.stdout = orig_so > output = captured.getvalue() > > -- > Denis S. Otkidach > http://www.python.ru/ [ru] > http://diveinto.python.ru/ [ru] > __________________________________________________ Do You Yahoo!? Yahoo! Autos - Get free new car price quotes http://autos.yahoo.com From pecora at anvil.nrl.navy.mil Sat Jul 20 11:33:24 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Sat, 20 Jul 2002 11:33:24 -0400 Subject: A better self References: Message-ID: <200720021133247545%pecora@anvil.nrl.navy.mil> In article , wrote: > > I learn something every day. We should have a collection of speedup > > tricks listed somewhere. > > We do, but we keep it fairly hidden because consulting the list too early > or too often is worse than not having a list. <0.5 wink> So, only the Python secret brotherhood gets to see The List? :-) -- Lou Pecora - My views are my own. From phr-n2002b at NOSPAMnightsong.com Mon Jul 8 03:46:40 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 08 Jul 2002 00:46:40 -0700 Subject: Linux clock-setting script References: <7x7kk691g0.fsf@ruckus.brouhaha.com> Message-ID: <7xr8ieu0f3.fsf@ruckus.brouhaha.com> Dmitri I GOULIAEV writes: > Or you can have just one line of shell command, like > > # ntpdate host > > which is (most probably) already in your distribution. > Do you have it in your distribution ? (just curious) No, not in Red Hat 7.2 or 7.3. It's probably in the big NTP package that's downloadable/installable, but as I said, I didn't feel like figuring all that stuff out. From phsdv.remove at earthlink.net Sun Jul 21 18:02:47 2002 From: phsdv.remove at earthlink.net (Paul) Date: Sun, 21 Jul 2002 22:02:47 GMT Subject: maximum recursion depth References: Message-ID: I think I will rewrite my code using loops. This will be possible, I just have to put my braincells back in active mode :-) I found that a too deep recursion will slow down executing to much. For now my program works with the recursion limit set at 3000. However I can think of situations where this will not be enough. For the statistics, I am using win2000 + cygwin (i686-pc-cygwin) Python 2.2 (#1, Dec 31 2001, 15:21:18) [GCC 2.95.3-5 (cygwin special)] on cygwin Paul "Tim Peters" wrote in message news:mailman.1027283309.29075.python-list at python.org... > [Paul, recursing very deeply] > > unfortunately it is not just memory... > > it will (did) crash when the stack size is full, which is only a > > fraction of the total memory space... right? > > The size of the stack you get depends on your operating system, and perhaps > also your platform C runtime implementation -- it's not Python's decision. > If you tell us which OS you're using, someone may be able to tell you how to > tell your OS that you want a larger stack. If you're using threads too, > life can get more complicated in a hurry, because most OS thread > implementations give threads relatively tiny stacks by default. > > > python used less than 6MByte (less than 1% of total) when it > > crashed with a much higher limit set for the recursion depth. > > It took an awful lot of processing time as well... Have to rethink my > > strategy here. > > Function calls in Python aren't cheap either. Keeping a stack or queue of > "work to do" in an iterative algorithm ("a loop") is often much faster. > > > > From joconnor at cybermesa.com Tue Jul 23 20:17:14 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 24 Jul 2002 07:17:14 +0700 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> <3D3EA54C.3EF009A@lfpt.rwth-aachen.de> Message-ID: <3D3DF209.17923D28@cybermesa.com> "Martin v. L?wis" wrote: > Lars von Wedel writes: > > > Sure, there's many applications using distributed functionality. > > However, you should consider that technologies like CORBA or > > Web Services have similar goals, so check out these before > > duplicating work! > > > > omniORB (http://omniorb.sourceforge.net) and fnorb (don't know where) > > are CORBA implementations with Python support. For web services in > > Python, have a look at http://pywebsvcs.sourceforge.net/ > > In addition, a number of Python-specific frameworks for that have been > developed over time as well; one of the oldest of those is Dopy > (http://www.users.cloud9.net/~proteus/dopy/welcome.html). That was my other thought., wondering if someone else had already done what I was toying with. It appears so :) -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From huaiyu at gauss.almadan.ibm.com Thu Jul 18 14:10:40 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 18 Jul 2002 18:10:40 +0000 (UTC) Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: Clark C . Evans wrote: >On Tue, Jul 16, 2002 at 10:14:51PM +0000, Huaiyu Zhu wrote: >| Thanks a lot for this link. The basic idea is very similar, but apparently >| they have done a lot more of formal specification than I have ever >| attempted. There are several differences in the details, so neither is >| superset of the other. I'll comment on the differences once I have time to >| read through their docs. > >I look forward to the commentary, could you do it or cc the >YAML discussion list? That'll be after I get time to read through YAML docs and review my old code and docs. >| The emphasis is on using indentation and leading markers to denote >| structure, in contrast to markups, puctuations, quotes and escapes in the >| markup languages. > >Exactly. We started with leading markers (% and @ initially) and >eventually found ways that allowed us to skip these... How like minds think alike. :-) Perl opened my mind to the possibility of heterogeneous hierarchical data structures. >I'd love to hear about the overlap; I'm sure we don't do everything. >But if you found something important that we don't have, I'd love to >know since we'd like to start finalizing the spec at this time so that >implementations can start emerging. > >I'd love to hear more about your thoughts on YAML, and if possible, >we'd really welcome your participation! I'll try to find time to participate, but time is always in short supply. Here are some comments at first glance. I don't see a description of the semantics of the structures independent of any syntax. It is possible to define all the canonical transforms among the structures [1] without concerning any particular representation. I'd also like to emphasize that all the indentations, markers etc should be configurable in a document[2][3]. [1] Canonical transforms, such as {a, b, c} -> [a, b, c] -> {(1:a), (3:c), (2:b)}. There are a few dozens of them among set, seq, dict, seqdict. Some have partial inverse. None of them are one-one correspondence. That's why I let all these four as basic structures. These four are the combination of keyd/nonkeyed ordered/unordered. Additional kinds of structures, such as bags (whether keyed and whether ordered), may be added later on. [4] [2] I tried the following kinds of indentations (where n is level) '(%s)' % n ' ' * n ' ' * n + '|' Obviously there can be a lot of other variations. Such flexibility would allow many common document formats to be transformed into conforming format with minimum effort, sometimes by just adding a metacomment at the beginning of the document. For example, the formats of the current paragraphs should be accommodated. [3] I would allow encoding and encryption to be allowed at a per node basis, not just at the file level. In reality how to break up a tree into subtrees to fit in files is largely arbitrary. This calls for meta comments on each node with a simple syntax for describing them. [4] One thing I have not solved is whether the keys can only be strings. If keys can be substructures themselves, there are further correspondence between sets, dicts and bags, such as {a, b} -> {a:1, b:1}. This leads to the issue of the identity of structures. Example: {a, b}=={a} if a==b. This complicates things and that's perhaps where I stopped. (Over-generalization perhaps?) So my overall comment is that this approach can be made more 'meta' than any particular syntax or structure would allow. The worst thing about xml is that one has to conform to its (mostly arbitrary) syntax conventions instead of thinking about the underlying data structure that's pertinent for the task at hand. I do believe that the good thing about standards is there are so many to choose from. A meta syntax would open up the possibility of interoperability on a much larger scale than xml could handle comfortably. It is often easier to define a particular syntax by fixing some parameters in a meta syntax. Perhaps these are already in yaml since I had only a half hour reading of its docs. Huaiyu From glingl at aon.at Sat Jul 13 11:35:07 2002 From: glingl at aon.at (Gregor Lingl) Date: Sat, 13 Jul 2002 17:35:07 +0200 Subject: dir() shows strange behaviour with VPython References: <3d2fe41e$0$25552$91cee783@newsreader02.highway.telekom.at> Message-ID: <3d3048bc$0$21424$91cee783@newsreader02.highway.telekom.at> What a surprise to come into contact with martellibot just after having read your interview on the Euro Python website. I'm working with Python 2.2.1 on a Windows2000 machine. Curious if something similar would happen on my machine I just deinstalled Visual-2002-06-14 and replaced it by Visual-2002-07-07 and I obtain exactly the same results as before - the session remaining alive... Let's see, if somebody else will give us more information on this ... Gregor "Alex Martelli" wrote in message news:j9SX8.62350$Jj7.1617175 at news1.tin.it... > Gregor Lingl wrote: > > > I thought to understand the dir() function, but... > > dir() is somewhat in transition between Python 2.1 and 2.2. > Not sure what Python level should be installed with Visual-06-14. > It does matter which exact level you did install, and on which > platform, though. > > I just downloaded and installed Visual-2002-07-07 on top of > my Python 2.2.1 but the s.__members__ access, and thus also > dir(s), just kills the Python interactive session stone dead > with 'Aborted' as the only message. Maybe the 06-14 version > had its own problems -- not quite as serious as 07-07's (at > least with Python 2.2.1 on Mandrake Linux 8.2:-) but enough > to give the anomalies you observe. > > (It's also possible that I made some mistake in installation, > of course, but I closely followed the specific instructions > for Mandrake on the "additional info" page of Visual). > > > Alex > From tim at bladerman.com Sat Jul 27 09:19:46 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sat, 27 Jul 2002 13:19:46 GMT Subject: Guide to the python interp. source? References: Message-ID: "Edward K. Ream" > I am writing this post on the theory that teaching something is the > best way to learn it myself. Any reason for helping me out is a good reason :-) > If I have made any blunders I'm sure the wizards will let me know gently :-) Well... Don't look at me, I wouldnt smell a blunder if you pushed them down my throat :-) > Section 18, Python Language Services, of the Python Library Reference > contains information related to the interpreter and the compiler. > http://python.org/doc/current/lib/language.html > Reference: http://python.org/doc/current/lib/bytecodes.html I had missed both those completley, thanks for pointing them out. > Although it seems very low level, I agree that looking at disassemblies is > actually very useful because you'll see what gets pushed and pulled from the > interpreter's stack by various constructs. That in turn makes the > interpreter code much easier to figure out. It won't be fun, but I keep telling myself that I do this for education :-) > However, "internal" C API routines (routines not meant to be used by the > general public) are not documented in the index. For these, you must go to > the source. The Include, Object, Modules and Python directories are the > first places to look for sources. It's usually not too difficult to guess > where code is. It is quite understandable that none have bothered to make a particulary big documentation to the internals that is not even intendet to be looked at by more then a handfull of people. Thanks alot for all the links, python.org seems to be down now but I will look in there a little later. > An earlier draft of this posting actually went step-by-step through the > interpreter code for the import cases. I've eliminated it because it was > loooooong. But that's where you might start: just dive into the code and > figure out what every line does for some case you are interested in. Don't > take shortcuts: really understand every line of code--where it is defined, > where it is documented and what it really does. As you get more experience, > you might be able to shortcut this step-by-step process, but at first I > recommend absolute thoroughness. Anyway, that's what I am doing :-) but that is sooo tiresome!... It takes alot of time and it gets frustrating :-) But I guess I will end up doing that in time. Now atleast I have alot of pointers to good startingplaces. Thanks for taking time to answer me! Tim From amuys at shortech.com.au Wed Jul 24 01:10:20 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 23 Jul 2002 22:10:20 -0700 Subject: Mastering Regular Expressions 2nd Ed. References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> <7xn0si9o2o.fsf@ruckus.brouhaha.com> Message-ID: <7934d084.0207232110.635049a7@posting.google.com> Paul Rubin wrote in message news:<7xn0si9o2o.fsf at ruckus.brouhaha.com>... > Tim Roberts writes: > > The multi-thousand byte full expression to match a valid RFC822 e-mail > > address was practically worth the price all by itself! > > Argggh! That sounds like regular expressions aren't really the best > way to match RFC822 addresses. More like matching RFC822 addresses isn't worth the price of admission. Still you missed the point, 822 addresses are complex beasts, not all valid emails are of the form \S+@\w(\.\w)*. The point of the RFC822 regex is that, assuming the address points to a valid MX record, the only practical way to test if an email address is valid is to try sending email to it. Andrae Muys From sandipb at bigfoot.com Wed Jul 3 07:41:05 2002 From: sandipb at bigfoot.com (Sandip Bhattacharya) Date: Wed, 3 Jul 2002 17:11:05 +0530 Subject: curses-based menu module? In-Reply-To: <3D218499.38153895@anansispaceworks.com> References: <3D218499.38153895@anansispaceworks.com> Message-ID: <20020703114105.GA2762@bigfoot.com> On Tue, Jul 02, 2002 at 03:46:49AM -0700, Terry Hancock was caught saying: > #1: > Am I reinventing the wheel? Is there already > a high-level interface available (this seems rather > likely, though I haven't found one). Take a look at the snack module. Implements a really basic but sufficient set of text widgets. To give you an idea of it's capabilities,the Redhat Linux text based installer is completely based on snack. - Sandip -- Sandip Bhattacharya sandipb @ bigfoot.com http://www.sandipb.net --------------------------- Got some news from/for the Free(tm) world in India? Get to be a journo at http://opennews.indianissues.org From martapython at yahoo.es Wed Jul 31 05:18:58 2002 From: martapython at yahoo.es (=?iso-8859-1?q?Marta=20Gutierre?=) Date: Wed, 31 Jul 2002 11:18:58 +0200 (CEST) Subject: Python Questionnaire Message-ID: <20020731091858.48784.qmail@web40301.mail.yahoo.com> Does any body know of any code in python for questionnaires ??? Tipicall web-forms with questions and storing results in files or things like that Thanks --------------------------------- Yahoo! Messenger Nueva versi?n: Webcam, voz, y mucho m?s ?Gratis! -------------- next part -------------- An HTML attachment was scrubbed... URL: From pinard at iro.umontreal.ca Tue Jul 9 18:51:21 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 09 Jul 2002 18:51:21 -0400 Subject: File size error in os.stat with large files. In-Reply-To: References: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: [John Hunter] > >>> fd = open('somefile.dat', 'rw') > >>> fd.tell() > 0L > If it returns '0', LFS is not enabled. if it returns '0L', LFS is enabled. Clever. Yet it seems that, in the long run, Python evoluation plan is to abolish user-visible distinction between usual integers and long integers. So I wonder if, despite the trick above might work for some while, it is really safe relying on it for programs meant to live a looong life :-). I do not know, but am wondering. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From jonathan at onegoodidea.com Wed Jul 3 05:02:32 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 03 Jul 2002 10:02:32 +0100 Subject: Splitting Text files References: Message-ID: On 2/7/2002 21:01, in article aft0r5$go61b$3 at ID-99293.news.dfncis.de, "William Park" wrote: > Ken Seergobin wrote: >> X-No-Archive:Yes >> [...] > > Perhaps, you should remove 'X-No-Archive'. Most people won't give answers, > let alone reply, to such posts. Given that the header was given in the body of the message, I hardly see that it will make any difference - it won't get honoured. The actual header contained: X-No-Archvie:Yes which the astute will notice also wouldn't have worked ;-) Still, if you post to usenet news, you should expect your words to live on in perpetuity. In years to come you'll find it fantastic fun to search Google for things you said when you were younger . -ah-them-were-the-days-ly y'rs, Jonathan From ods at fep.ru Mon Jul 1 11:49:38 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Mon, 1 Jul 2002 19:49:38 +0400 (MSD) Subject: New style classes as exceptions (Was: exception handing) In-Reply-To: Message-ID: On Mon, 1 Jul 2002, Mark McEahern wrote: MM> > New style classes don't work when used as exceptions. I MM> guess it MM> > should be considered as a bug. MM> MM> Just out of curiousity: How come you aren't subclassing MM> from Exception? This doesn't matter: >>> class o(Exception, object): pass ... >>> try: ... raise o('spam') ... except o: ... print 'OK' ... Traceback (most recent call last): File "", line 2, in ? TypeError: exceptions must be strings, classes, or instances, not o From gyromagnetic at excite.com Wed Jul 17 17:49:18 2002 From: gyromagnetic at excite.com (gyromagnetic) Date: 17 Jul 2002 14:49:18 -0700 Subject: better 'splice' function References: Message-ID: <4620daca.0207171349.787dea08@posting.google.com> Thanks John and Sean for the pointer. I guess I didn't follow that particular thread. My problem is slightly different in that instead of a mapping of a single tuple to a value, I will have a list of tuples, and want to enumerate all of the possibilities. So, for your example posting x = ( 'John', 'Hunter', 'where' ) map: m = { 'where': [('was', 'here'),('was not', 'there')], 'somekey': 'someval' } I'd like y = [('John', 'Hunter', 'was', 'here'), ('John', 'Hunter','was not', 'there')] I'll take a look at the many clever solutions that were proposed and try to modify them accordingly. -Brad John Hunter wrote in message news:... > >>>>> "Sean" == Sean 'Shaleh' Perry writes: > > Sean> something A LOT like this was discussed within the last two > Sean> months at length. Many, many, many implementations were > Sean> presented. Have a search through the archives. > > Yep, check > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&frame=right&th=fb73946e707ff1da&seekm=mailman.1019594863.1719.python-list%40python.org#link1 > > John Hunter From whisper at oz.net Wed Jul 10 15:50:41 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 12:50:41 -0700 Subject: Why self? In-Reply-To: <100720021526477293%pecora@anvil.nrl.navy.mil> Message-ID: Louis; I think he was proposing an idea. I don't believe you can import from self, and i'm almost positive that "to ... export" isn't part of Python. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Louis M. Pecora > Sent: Wednesday, July 10, 2002 12:27 > To: python-list at python.org > Subject: Re: Why self? > > > In article , Huaiyu Zhu > wrote: > > > The Pythonic way to use namespace is :-) > > > > from self import x, y, z, a, tseries > > y= x**2 * t/z + a * FFT(tseries) > > to self export y > > Hmmmm....never thought that way. Very interesting. > > > Any change that persists beyond local namespace is mentioned explicitly. > > Does it solve all the problems mentioned below? > > Don't know. > > -- > Lou Pecora > - My views are my own. > -- > http://mail.python.org/mailman/listinfo/python-list From whenisittime at your.house Wed Jul 31 00:13:35 2002 From: whenisittime at your.house (John) Date: 31 Jul 2002 04:13:35 GMT Subject: Hey Group! Message-ID: <925c.497e.192@YHBT> Hi! nice newsgroup. any rules I should know before I start posting? is there an faq? Thanks! From phr-n2002b at NOSPAMnightsong.com Sat Jul 6 05:16:55 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 06 Jul 2002 02:16:55 -0700 Subject: Linux clock-setting script Message-ID: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> I found Simon Foster's nice little SNTP client on the ASPN Cookbook site and adapted it to set the hardware clock under Linux: http://www.nightsong.com/phr/python/setclock.py I find it pretty useful for adjusting my computer clock every now and then, without the hassle of setting up a real NTP system. From mgerrans at mindspring.com Sun Jul 21 15:56:04 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sun, 21 Jul 2002 12:56:04 -0700 Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? References: <8d3e714e.0207210836.7f8a51c8@posting.google.com> <0BC_8.112265$vm5.3832285@news2.tin.it> Message-ID: > (Bias warning: working with David on the Python Cookbook has made > us friends -- but I liked Learning Python even before then!-). Just so you have an unbiased opinion, too: I agree with Alex! Learning Python is one of the best books I've read on *any* programming language; it is well-written, engaging and keeps a very brisk pace, unlike a lot of the huge tomes swaying my bookshelves. I also hope they have plans to update it for 2.2 (and beyond), but I would still recommend the current edition as a great way to get started in Python. From brian_l at yahoo.com Thu Jul 18 02:03:52 2002 From: brian_l at yahoo.com (Brian Lenihan) Date: 17 Jul 2002 23:03:52 -0700 Subject: ANN: Pyrex 0.3.4 References: Message-ID: Robin Becker wrote in message news:... > > I'm probably being stupid, but I get this with the Demos\setup.py using > win32 2.2.1 after doing the base setup.py install > > primes.c(141) : error C2375: 'initprimes' : redefinition; different > linkage > primes.c(139) : see declaration of 'initprimes' > error: command '"C:\Program Files\Microsoft Visual > Studio\VC98\BIN\cl.exe"' failed with exit status 2 It's not you. MSVC doesn't like the void initprimes prototype above the __declspec(dllexport) void initprimes(void) { You can work around it by inverting the order in Pyrex/Compiler/Nodes.py like so: header = "void init%s(void)" % env.module_name if sys.platform == "win32": code.putln("__declspec(dllexport)") else: code.putln("%s; /*proto*/" % header) From dbasch at yahoo.com Tue Jul 16 16:37:11 2002 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 16 Jul 2002 13:37:11 -0700 (PDT) Subject: Simple Pickle Question! Message-ID: <20020716203711.99600.qmail@web20805.mail.yahoo.com> Hello All, If I open a file object in 'w+' mode and then try a simple pickle.dump() and pickle.load() such as: self.foofile = open('foofile', 'w+') self.foo = 'fudgesticks' pickle.dump(self.foo, self.foofile) self.returned = pickle.load(self.foofile) foofile.close() print self.returned I get this error: File "C:\DOCUME~1\User\DESKTOP\tempers.py", line 259, in __init__ self.returned = pickle.load(self.foofile) File "C:\Python21\lib\pickle.py", line 947, in load return Unpickler(file).load() File "C:\Python21\lib\pickle.py", line 567, in load dispatch[key](self) KeyError: Pickling works fine if I open the file object in 'w' mode for the dump and again in 'r' for the load. Any ideas?? if reply > 0: print 'thanks' Derek T Basch __________________________________________________ Do You Yahoo!? Yahoo! Autos - Get free new car price quotes http://autos.yahoo.com From fredrik at pythonware.com Mon Jul 29 12:03:58 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Jul 2002 16:03:58 GMT Subject: how to count lines in a file ? References: <7aU%8.139472$vm5.4528856@news2.tin.it><1027656130.63094@yasure> Message-ID: Christopher A. Craig wrote: > So if Guido decides today that reference counts were a dumb idea and > he would be better off with a simple mark-and-sweep GC, he can > implement one and not lose too much sleep over the weeping and > gnashing of teeth from those that depended on the behavior of the > current compiler. <.8 wink> luckily, that's not how things are done in the Python universe... From raims at dot.com Sat Jul 20 10:24:57 2002 From: raims at dot.com (Rhymes) Date: Sat, 20 Jul 2002 16:24:57 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: On Fri, 19 Jul 2002 14:53:28 -0700 (PDT), "Sean 'Shaleh' Perry" wrote: >from __future__ import generators I know...but it's not a built-in feature :) -- Rhymes rhymes at myself.com " ride or die " From null at obscure.dk.X Sat Jul 6 12:05:00 2002 From: null at obscure.dk.X (Thomas Jensen) Date: Sat, 06 Jul 2002 18:05:00 +0200 Subject: Using Python for processing of large datasets (convincing managment) Message-ID: <3D27152C.8020108@obscure.dk.X> Hello group (and list :-), I've used Python for several years (and followed this group until about 6 months ago). I work in a small company which specialises in collecting and procesing financial data. Most of our production environment is based on Microsoft stuff like ASP/VBScript, VB6, WinNT, MS SQL Server, etc. One of the next development tasks is rewriting the nightly processing job which is having problems with our ~100mb database (it it written in Borland C++, but absolutely not optimized for speed!). The goals of the rewritten piece of software would be: * Improved speed * Improved scalability - parallel processing on multiple machines/CPUs * Improved scalability - ability to handle greater databases (>1gb) * Ability to calculate only a subset of the data Now, instead of rewriting the job in C++, I'd (of course) like to use Python. However the CEO (small company, told you :-), made a couple of somewhat valid points against it. 1) He was worried about getting a replacement devlopper in case I left. 2) He said, "Name 3 companies using Python for key functions" 3) He was worried about the stability/reliability of python in our production environment (you know, 99.999 % and all that) I was hoping someone in this group could help with some really compelling arguments, as I'd really to use Python for this job. Best regards Thomas Jensen From marklists at mceahern.com Fri Jul 5 12:21:16 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 5 Jul 2002 11:21:16 -0500 Subject: Why self? In-Reply-To: Message-ID: > Roy Smith wrote: > > > Other than in an obfuscated python contest, I can't think of any reason > > why anybody would *ever* use any variable name other than "self" as the > > first formal parameter of a method. > > > > Have you ever seen an example that does? [Christian Tanzer] > Here's an example that should use another name than `self`: [snip example of __new__ and discussion of metaclasses] staticmethod is another example of a type of method whose first parameter should not be self. Of course, I don't doubt Roy implicitly meant first formal parameter of normal instance methods. That was the context of the original message, anyway. // mark - From anton.wilson at camotion.com Mon Jul 1 16:59:15 2002 From: anton.wilson at camotion.com (anton wilson) Date: Mon, 1 Jul 2002 16:59:15 -0400 Subject: python threads and the linuxthread pthread library In-Reply-To: References: Message-ID: <200207012045.QAA05707@test-area.com> Re: python threads and the linuxthread pthread library From: anton wilson To: Tim Peters Date: Mon, 1 Jul 2002 16:52:12 -0400 >?> How do threads aquire the global interpreter lock once they are awoken? > >?I'm not sure what you mean by "awoken". ?Python doesn't normally put >?threads to sleep . ?Threads that don't hold the GIL are normally >?blocked trying to acquire the GIL. ?If by "awoken" you mean "become >?unblocked", then awakening and acquiring the GIL are exactly the same thing >?-- one doesn't precede the other. ?The details of how the GIL gets acquired >?live inside your platform thread implementation. ?On Linux, Python may use >?either pthread condition variables, or POSIX semaphores, to implement the >?GIL. I think the reason why I'm confused here is that when the PyThread_release_lock call ias executed, it simply locks the global int lock, changes the locked variable to 0, unlocks the global interpreter lock, and then signals a thread waiting on the unlocked mutex condition to wake up. I can't find where a thread that gets swapped out by the interpreter blocks when it tries to require the lock again. Where does a swapped out thread block? >From thread_pthread.h: ? ? ? ?status = pthread_mutex_lock( &thelock->mut ); ? ? ? ? CHECK_STATUS("pthread_mutex_lock[3]"); ? ? ? ? thelock->locked = 0; ? ? ? ? status = pthread_mutex_unlock( &thelock->mut ); ? ? ? ? CHECK_STATUS("pthread_mutex_unlock[3]"); ? ? ? ? /* wake up someone (anyone, if any) waiting on the lock */ ? ? ? ? status = pthread_cond_signal( &thelock->lock_released ); ? ? ? ? CHECK_STATUS("pthread_cond_signal"); From pinard at iro.umontreal.ca Sun Jul 7 08:57:15 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 07 Jul 2002 08:57:15 -0400 Subject: signal.alarm() for less than one second? In-Reply-To: References: Message-ID: [Jarkko Torppa] > In article , Andrei Kulakov wrote: > > It looks like signal.alarm takes 1+ seconds as argument. I need > > something lower, like 0.5 second or so. > Usual way to do input timeouts on unix is to use select. There is also > setitimer syscall but it does not seem to be wrapped into anything. Here is `msleep.c', what I've been using in some packages, but this was before my Python times, and it probably misses some "newer" features like `setitimer'. I always used `msleep.c' within Autoconf context, as you can guess by the number of embedded `#if' lines. :-) Currently, indeed, it seems that `select' might be the only handy avenue for Python programs. -------------- next part -------------- /* Sleep a given number of milliseconds. Copyright (C) 1992, 1993, 1994, 1997, 2000 Free Software Foundation, Inc. Fran?ois Pinard , 1992. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if HAVE_CONFIG_H # include #endif /* This code is heavily borrowed from Taylor UUCP 1.03. Ian picks one of usleep, nap, napms, poll, select and sleep, in decreasing order of preference. The sleep function is always available. */ /* In many cases, we will sleep if the wanted number of milliseconds is higher than this value. */ #define THRESHOLD_FOR_SLEEP 30000 /* Include some header files. */ #if HAVE_UNISTD_H # include #endif #if !HAVE_USLEEP # if !HAVE_NAP # if !HAVE_NAPMS # if HAVE_POLL # if HAVE_STROPTS_H # include # endif # if HAVE_POLL_H # include # include # endif # if !HAVE_STROPTS_H && !HAVE_POLL_H /* We need a definition for struct pollfd, although it doesn't matter what it contains. */ struct pollfd { int idummy; }; # endif # else /* !HAVE_POLL */ # if HAVE_SELECT # include # endif # endif /* !HAVE_POLL */ # endif # endif #endif /*---------------------------------------. | Sleep a given number of milliseconds. | `---------------------------------------*/ void msleep (milliseconds) int milliseconds; { #if HAVE_USLEEP if (milliseconds > 0) usleep (milliseconds * (long) 1000); #else # if HAVE_NAP if (milliseconds > 0) nap ((long) milliseconds); # else # if HAVE_NAPMS if (milliseconds >= THRESHOLD_FOR_SLEEP) { sleep (milliseconds / 1000); milliseconds %= 1000; } if (milliseconds > 0) napms (milliseconds); # else # if HAVE_POLL struct pollfd sdummy; /* poll(2) checks this address */ if (milliseconds >= THRESHOLD_FOR_SLEEP) { sleep (milliseconds / 1000); milliseconds %= 1000; } if (milliseconds > 0) poll (&sdummy, 0, milliseconds); # else # if HAVE_SELECT struct timeval s; if (milliseconds >= THRESHOLD_FOR_SLEEP) { sleep (milliseconds / 1000); milliseconds %= 1000; } if (milliseconds > 0) { s.tv_sec = milliseconds / 1000; s.tv_usec = (milliseconds % 1000) * (long) 1000; select (0, NULL, NULL, NULL, &s); } # else /* Round the time up to the next full second. */ if (milliseconds > 0) sleep ((milliseconds + 999) / 1000); # endif # endif # endif # endif #endif } -------------- next part -------------- -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From nospam at nonesuch.com Wed Jul 31 17:40:50 2002 From: nospam at nonesuch.com (David Smith) Date: Wed, 31 Jul 2002 14:40:50 -0700 Subject: C++/Python version problems? References: <3D484ACD.7030503@nonesuch.com> Message-ID: <3D485962.4060506@nonesuch.com> Chris Liechti wrote: > python is written is C anyway, so you should not have any problems with it, > but maybe you're using an interface library like Boost or CXX. that one > should(must?) be compiled with the same compiler as your extension. I'm just using STL - in particular, vector, fill, max, min. > so, yes i do think you thoughts were right, have a look at the libraries > you link with. > > chris > -- David Smith drs at labs dot agilent dot com <- hopefully doesn't trigger spambots From peter at engcorp.com Fri Jul 12 04:23:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Jul 2002 04:23:09 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> <3D2E8F10.B9B4EFD2@alcyone.com> Message-ID: <3D2E91ED.B061D0EB@engcorp.com> Erik Max Francis wrote: > > Peter Hansen wrote: > > > Since you post without smileys, I can only assume you are serious? > > Yes, that's right. Any post that doesn't contain a smiley is always > absolutely dead serious. It always helps when the smileyless posts contain actual humour, no matter how subtle. Like yours, unlike the other. > > To which my response is: you can't be serious. :-) > > :-) :-| (The best attempt I can manage with my current keyboard at a straight-faced stare, daring you to smile.) -Peter From bellman at lysator.liu.se Fri Jul 5 16:47:17 2002 From: bellman at lysator.liu.se (Thomas Bellman) Date: Fri, 5 Jul 2002 20:47:17 +0000 (UTC) Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <3D2487CB.9000102@gmx.de> <3D24FAC5.3050406@something.invalid> Message-ID: Greg Ewing wrote: > On the other hand, a situation that *is* very common is > a loop-and-a-half, with the exit condition in the middle. > So far, I've never seen *any* really good loop-and-a-half > structure in any language, and I think Python has a chance > to be truly innovative here. As others have already said, iterators can sometimes alleviate this problem. And there is *one* language where I think the structure for loop-and-a-half *is* good: Forth. The syntax goes something like BEGIN spam spam spam eggs? WHILE norwegian blue REPEAT The call to 'eggs?' is the predicate for checking whether the loop should continue or not; it should put zero (0) on the stack if it should break, and non-zero if it should continue. 'WHILE' pops the top number off the stack, and if that number was zero, it jumps to after 'REPEAT', but if it is non-zero, the loop continues with the words after 'WHILE'. The 'REPEAT' word unconditionally jumps back to 'BEGIN'. Some dialects of Forth allow several calls to WHILE within the loop, so it could look like BEGIN part-1 test-1 WHILE part-2 test-2 WHILE part-3 test-3 WHILE part-4 REPEAT I *would* have liked that to be repeat: part_1() while test_1(): part_2() while test_2(): part_3() while test_3(): part_4() in Python, but that is unfortunately not compatible with the current Python syntax. :-( -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "You cannot achieve the impossible without ! bellman @ lysator.liu.se attempting the absurd." ! Make Love -- Nicht Wahr! From cliechti at gmx.net Fri Jul 12 16:49:26 2002 From: cliechti at gmx.net (Chris Liechti) Date: 12 Jul 2002 22:49:26 +0200 Subject: Debugging Embedded Python References: Message-ID: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote in news:memo.20020712144413.1996A at a.a: > We've got a (win32) C++ program that has an embedded python > interpreter that runs a bunch of scripts. We've been asked to enable > it's users to run the python scripts under a debugger, allowing the > users to put in breakpoints, examine/alter values etc. this is in the sys module: settrace(tracefunc) Set the system's trace function, which allows you to implement a Python source code debugger in Python. See section 9.2, ``How It Works,'' in the chapter on the Python debugger. The function is thread-specific; for a debugger to support multiple threads, it must be registered using settrace() for each thread being debugged. so you could write the trace function in your c/c++ extension and register it in the embedded python interpreter. that means that you write your own debugger but its one way. an other is that you could (maybe) use a remote debugger like HAP (somewhere on sf.net). chris -- Chris From tim at remove_if_not_spam.digitig.cix.co.uk Mon Jul 1 08:45:04 2002 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Mon, 01 Jul 2002 12:45:04 GMT Subject: Problems configuring 4suite References: <3d1c4f89.1205192@usenet.plus.net> Message-ID: <3d204ec8.15859807@usenet.plus.net> Nobody? From just at xs4all.nl Tue Jul 30 03:52:52 2002 From: just at xs4all.nl (Just) Date: Tue, 30 Jul 2002 09:52:52 +0200 Subject: global interpreter lock not working as it should References: <200207292348.TAA31011@test-area.com> Message-ID: In article , martin at v.loewis.de (Martin v. Loewis) wrote: > anton wilson writes: > > > The reason your code works is because you explicitly give up the CPU > > with the sleep calls. If you remove both time.sleep calls the results will > > look like: > > I see. Now, I take the modified script > > import threading, time > > def func1(): > for i in range(10): > for k in range(10): > pass > print "FUNC1" > > def func2(): > for i in range(10): > for k in range(10): > pass > print "FUNC2" > > t = threading.Thread(target=func1) > t.start() > func2() > > This has no explicitly-blocking calls, and prints > > FUNC2 > FUNC2 > FUNC1 > FUNC2 > FUNC1 > FUNC2 > FUNC1 > FUNC2 > FUNC1 > FUNC2 > FUNC2 > FUNC2 > FUNC2 > FUNC2 > FUNC1 > FUNC1 > FUNC1 > FUNC1 > FUNC1 > FUNC1 > > So I still can't see your problem. I can see it on MacOSX, three different Linux boxes and a FreeBSD box. Various Python versions. The output is always sequential. Just From bsb at winnegan.de Thu Jul 18 17:23:18 2002 From: bsb at winnegan.de (Siggy Brentrup) Date: 18 Jul 2002 23:23:18 +0200 Subject: replacing a part of a string using a regexp In-Reply-To: References: Message-ID: <87bs9491dl.fsf@winnegan.de> Rajarshi Guha writes: > Hi, > I'm trying to parse some HTML tags and I have the following situation: > > a line contains: > > > > And I want to replace the url and make the line: > > > > Using re.sub I can substitute the whole string bewteen quotes, but the > substituion needs to use the string that is *found* in the quotes. > > How can I access the matched portion in a re.sub() expression? How about (tested w/ python2.2.1) >>> re.sub('="(?P[^"]*)"', ... '="http://myserver.com/prog.py?\g"', ... '') '' HTH Siggy -- Siggy Brentrup - bsb at winnegan.de - http://oss.winnegan.de/ ****** ceterum censeo javascriptum esse restrictam ******* From jc2astro at hotmail.com Wed Jul 17 19:42:35 2002 From: jc2astro at hotmail.com (Jim Cerra) Date: Wed, 17 Jul 2002 19:42:35 -0400 Subject: Installing XMLProc??? Message-ID: How do I "install" XMLProc (Lars Marius Garshol's XML Processor)? Do I have to add it to a path in my python-install directory? Or am I just mixed up (quite possible)? -- Jimmy Cerra "my mind is slipping away ... day by glorious day" - RG From hemkond at hotmail.com Wed Jul 17 12:27:21 2002 From: hemkond at hotmail.com (mike k) Date: 17 Jul 2002 09:27:21 -0700 Subject: Automating MSDEV studio build process References: Message-ID: <6d2d7a01.0207170827.6d49d66@posting.google.com> "Bjorn Pettersen" wrote in message news:... > Does anyone have any experience automating a nightly build process using > Python in combination with MSDevStudio? I remember some discussion here > about it a while ago, but I couldn't find any reference to it through > Google... > > We have three major classes of libraries we need to build (each class > has its own dsw with about a dozen dsp's inside for individual > sub-libraries). Would it be best to generate makefiles from the dsw's > and proceed on the command line from there (is there a way e.g. through > COM to have VS generate the makefiles since we normally don't use > makefiles?) -- or should we try to automate it all through controlling > VS through COM? > > The engineer who is working on this is pretty new to Python, so this > would be a good way to show him how to get rid of five hours of manual > build processes (especially since I just got mandated that we install > Python on all machines :-) > > -- bjorn Actually I have started implementing a python nightly-build system that does just that, it gets sources from VSS, assigns a build number, starts a build, emails build results and so on, all of this using an xml file that describes the whole process. We have a nightly build system that envolved some python and a lot of old batch files, but it is too complicated to maintain. The new xml describes the process in a more build oriented language. It is currently in early testing, I will gladly share it, once it can be used in production. Mike. From tjreedy at udel.edu Thu Jul 25 10:31:59 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Jul 2002 14:31:59 GMT Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> <3D40066E.2090809@mxm.dk> Message-ID: "Max M" wrote in message news:3D40066E.2090809 at mxm.dk... > The message "Argument must be a string", while not technically correct, > is far easier to understand and in line with the Docs where argument 's' > is defined as a string. If the requirement is that the arg have a replace method -- as indicated by the error message and which seems quite sensible if you are asking that dangerous chars be replaced with escapes -- then the doc should be corrected. Someone could file a doc bug report. TJR From erno-news at erno.iki.fi Wed Jul 10 09:33:42 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 10 Jul 2002 16:33:42 +0300 Subject: try/finally question References: <7xd6twow3x.fsf_-_@ruckus.brouhaha.com> Message-ID: In article <7xd6twow3x.fsf_-_ at ruckus.brouhaha.com>, Paul Rubin writes: | So the obvious way to use it is: | try: | db.begin() | x = db.do_action(first_thing) | y = db.do_action(second_thing) | db.commit() | finally: | db.cancel() | The trouble is db.cancel() is an ordinary method call--it's not atomic | in the interpreter. It can be interrupted and blast out of the | finally block before finishing, and then control returns to some | higher level with the database still locked. would it be different from the an interrupt coming at any point between the begin and the commit? if you want to do database transactions in the signal handler, you will probably get an error if you try to begin() before closing the previous transaction, but that same problem would be in the try block too. if you never call neither commit or cancel but just exit, the effect in all the systems i have seen is effectively the same as calling cancel. -- erno From martin at v.loewis.de Sun Jul 14 17:07:50 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 14 Jul 2002 23:07:50 +0200 Subject: python2 import trouble (linux - redhat) References: Message-ID: Mike Mellor writes: > I am having trouble importing modules with python2 (Python 2.2) that > I think should be there, for example, _gtk and GTK. What do I need > to do to get python (actually python2) to import these modules? You need to recompile all packages, preferably updating the spec files in the source RPMs to give different package names and install locations. If that is too much effort, moving to a different Linux distribution might be easier. Regards, Martin From mf at mrinfo.de Thu Jul 25 07:57:22 2002 From: mf at mrinfo.de (Marko Faldix) Date: Thu, 25 Jul 2002 13:57:22 +0200 Subject: Anybody using 4suite for xslt processing? References: <5b4785ee.0207221346.4311877a@posting.google.com> Message-ID: Now this worked: First of all, we didn't have pyxml installed. So I uninstalled python and 4suite. Then I installed python22, then pyxml for python22 and then 4suite for python22 on Win 2000 Server. Then I have a file called exslt.xml with xml data from an older documentation somewhere: Mark Wilson
911 Somewhere Circle, Canberra, Australia
(++612) 12345 (++612) 12345 markwilson at somewhere.com
Tracey Wilson
121 Zootle Road, Cape Town, South Africa
(++2721) 531 9090 (++2721) 531 9090 Tracey Wilson at somewhere.com
Jodie Foster
30 Animal Road, New York, USA
(++1) 3000 12345 (++1) 3000 12345 Jodie Foster at somewhere.com
Lorrin Maughan
1143 Winners Lane, London, UK
(++94) 17 12345 (++94) 17 12345 Lorrin Maughan at somewhere.com
Steve Rachel
90210 Beverly Hills, California, USA
(++1) 2000 12345 (++1) 2000 12345 Steve Rachel at somewhere.com
Further a file called exslt.xsl:
Name Address Tel Fax Email
And finally the file exslt.py: ----- from Ft.Xml.Xslt import Processor from Ft.Xml import InputSource processor = Processor.Processor() transform = InputSource.DefaultFactory.fromUri("http://marko.ourhost/python/exslt.xsl") processor.appendStylesheet(transform) source = InputSource.DefaultFactory.fromUri("http://marko.ourhost/python/exslt.xml") result = processor.run(source) print "Content-Type: text/html\n" print result ----- Then I called last one through webbrowser and it returns correct table of persons. Now there is one problem left. Every output is enhanced with ::: Using minidom What's going wrong here? If I want to go in production state, such message may not appear and isn't it a sort of warning? -- Marko Faldix M+R Infosysteme Hubert-Wienen-Str. 24 52070 Aachen Tel.: 0241-93878-16 Fax.:0241-875095 E-Mail: marko.faldix at mplusr.de From shalehperry at attbi.com Wed Jul 24 15:32:47 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 24 Jul 2002 12:32:47 -0700 (PDT) Subject: syntax questions In-Reply-To: Message-ID: > > for some reason, people doing internationalization (i18n) and > localization (l10n) stuff seem to prefer to use functions called > "_", probably only to confuse people like you and me. > 1) it is guaranteed not to clash with the local namespace and in languages like C that is all you have. Once this became common in C it moved to other languages because that way the coder need only learn one style. 2) it is short and so remains inconspicuous and does not hurt people trying to fit code onto 78 char screens. For the jerks fighting the l10n effort it was much harder to fight _() than say translate(). One of the projects I work on uses i18n(string) which I like. From syver-en+usenet at online.no Tue Jul 16 14:58:34 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 16 Jul 2002 18:58:34 GMT Subject: there's no DefaultHandler References: Message-ID: "a64bs4$1oo$1 at newsreader.mailgate.org" writes: > hi. i'm trying to run my first python program > i'm using python 2.2 > > [eugene at eugene python]$ python firstxml.py > Traceback (most recent call last): > File "firstxml.py", line 6, in ? > class FindIssue(xml.sax.DefaultHandler): > AttributeError: 'module' object has no attribute 'DefaultHandler' > I think that the tutorial is outdated, use xml.sax.ContentHandler instead -- Vennlig hilsen Syver Enstad From marklists at mceahern.com Mon Jul 8 16:10:21 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 8 Jul 2002 15:10:21 -0500 Subject: subclassing int and accessing the value In-Reply-To: <200207081936.g68JaSe25466@localhost.localdomain> Message-ID: > Now my question is, how do I access the actual value 5 internally so I > can write my own __repr__ method that returns '$0.05'. I'm guessing it's > using __getattribute__, but what attribute do I want to access? Short answer: Look no farther than self. ;-) E.g., class money(int): def __init__(self, *args): super(int, self).__init__(*args) def __str__(self): return "$%1.2f" % (float(self) / 100) x = money(5) print x If you're looking for a way to represent money, you may want to use a fixed decimal class. I'm using Tim Peter's FixedPoint class. Cheers, // mark - From cliechti at gmx.net Thu Jul 25 11:18:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jul 2002 17:18:11 +0200 Subject: how to get a return value from an exception ? References: Message-ID: "Shagshag13" wrote in news:ahp28b$uccl1$1 at ID-146704.news.dfncis.de: > i had another questions : > > * if exceptionB and exceptionC subclass from exceptionA, if i raise > exceptionB i could still catch it as it was ExceptionA ? you mean that: try: raise exceptionC() except exceptionA, ex: print "gotcha" gets the exception, yes. > * is it a > correct statement ? : > try: > #do > except exceptionB: > #do 1 > except exceptionC: > #do 2 > except exceptionA: > #do else yes. and you have the correct order: subclasses first, and below the baseclass. (otherwise the baseclass would catch everything) chris PS: i would start class names, like ExceptionB with capital letters. coding style conventions - you know. -- Chris From gerhard.haering at gmx.de Tue Jul 16 04:07:54 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 16 Jul 2002 10:07:54 +0200 Subject: uniform interface for MySQL & MSSQL In-Reply-To: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> References: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> Message-ID: <20020716080754.GA3565@lilith.my-fqdn.de> * Johann [2002-07-16 09:31 +0200]: > On Mon, 15 Jul 2002 19:38:28 GMT, Alex Martelli > wrote: > > >Have you tried: > >http://www.object-craft.com.au/projects/mssql/ > > It does not work. I tried to compile it under Cygwin but some files > (*.h) are missing :-( > > In file included from mssqldb.c:25: > mssqldb.h:37: sybfront.h: No such file or directory > mssqldb.h:38: sybdb.h: No such file or directory > error: command 'gcc' failed with exit status 1 > > I found this module have no cursor.seek(nr) method. :( It's probably not difficult to implement. I planned to suggest you use mxODBC, as this is a commercially supported module and does support both databases. Then I discovered that it doesn't currently support cursor.seek either, and asked on the DB-SIG mailing list. Marc-Andre Lemburg, its author, said that mxODBC 2.1 will support most of the optional DB-API extensions of PEP 0249, which includes cursor.seek. You might want to ask him if he'll support cursor.seek and if this will work with both MS SQL and MySQL. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From donn at drizzle.com Tue Jul 16 00:59:02 2002 From: donn at drizzle.com (Donn Cave) Date: Tue, 16 Jul 2002 04:59:02 -0000 Subject: curses, multiplexing, select / poll, and resizing References: None Message-ID: <1026795540.363395@yasure> Quoth frob1 at archerlabs.net (frobenius): | preface: i'm new to python, semi-new to curses, but an otherwise | experienced programmer. I don't know beans about curses. | i'm writing a telnet client using curses to separate input and output | into different windows. to multiplex the I/O from the user and the | host i'm using poll(). when i resize the terminal window (i'm using | win32 PuTTY to connect to FreeBSD, running Python 2.2) i generate an | exception which kills poll(): | | Select Error: 4, Interrupted system call ... | signal.signal(signal.SIGWINCH, self.handler_resize) Right, that's your culprit. I believe you will conclude it's more or less necessary, so you'll just have to trap the error around poll(). ... | - how to i capture and ignore this w/out accidentally capturing a real | poll() error? EINTR (4) means a "slow" system I/O was interrupted by signal delivery, so I would check for err.args[0] == 4 Donn Cave, donn at drizzle.com From peter at engcorp.com Wed Jul 17 08:43:53 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Jul 2002 08:43:53 -0400 Subject: get a list printed in hexadecimal notation References: Message-ID: <3D356689.23937EFE@engcorp.com> Oliver Eichler wrote: > > Is it possible to print a mixed list with strings and numbers and having the > numbers printed as hexadecimal notation? > > something like: > > >>>l = ('spam',10,15,'more spam') > >>>print l > ('spam',0xA,0xF,'more spam') > > or similar... > > The only way I could think of is to write my own print function. Is there an > easy way? Maybe, if you don't mind copying the list, some hack like this? (Using Python 2.2... not sure it works in earlier versions.) >>> class HexRepInt(int): ... def __repr__(self): ... return self.__hex__() ... >>> l = ['spam', 10, 15, 'more spam'] >>> m = [type(x) == type(0) and HexRepInt(x) or x for x in l] >>> print m ['spam', 0xa, 0xf, 'more spam'] -Peter From kseergobin at sympatico.ca Tue Jul 2 19:25:34 2002 From: kseergobin at sympatico.ca (Ken Seergobin) Date: Tue, 2 Jul 2002 16:25:34 -0700 Subject: Splitting Text files References: Message-ID: <%XnU8.4057$aJ4.853781@news20.bellglobal.com> "William Park" wrote in message news:aft0r5$go61b$3 at ID-99293.news.dfncis.de... > Perhaps, you should remove 'X-No-Archive'. Most people won't give answers, > let alone reply, to such posts. Personally, I'm not thrilled by every scrap of information being recorded. However, if the no-archive option makes getting information easier the content of the original post will be repeated in this message. (That said, I do understand why posts like these should be archived.) Original Post: I've looked around, but have been unable to locate a good example of how to split a text file. Specifically, I have datafiles with an identification line marked with the name of a BMP file followed by many lines of data. This repeats a number of times for each datafile. Within the data lines I'm only interested in extracting the those with a specific keyword. Ultimately, I'd like to have a datafile for each BMP listed in the original file. Suggestions would be appreciated. I really couldn't make sense of the regular expression notes I found. Thanks, Ken From martin at v.loewis.de Sun Jul 7 04:08:17 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Jul 2002 10:08:17 +0200 Subject: Chinese language support of Python? References: <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl> <3d27de14$0$94898$e4fe514c@dreader3.news.xs4all.nl> Message-ID: Boudewijn Rempt writes: > I don't think that's going to work (caveat: I use PyQt which has different > conventions). If you absolutely want to have Chinese characters in your > source files*, you can do something like the following**: > > root.title(unicode('???', 'utf-8') The problem is that this won't work in IDLE. > * Actually I still think it would be great to be able to have sourcefiles > in utf-8, not limited to unicode strings. I want to type: This can only happen after PEP 263 is adopted, otherwise, it will be difficult to find out which bytes denote letters. Even then, it will be difficult to find out when two identifiers are equal - __dict__ dictionaries would need to allow Unicode strings as keys. Notice that this only a step towards what ChinesePython is doing, http://www.python.org/doc/NonEnglish.html#chinese which changes all the keywords to allow you to type Chinese-based keywords instead of the traditional English-based keywords. > That this would make my source code unreadable for a lot other people, tant > pis, I still would like the power. Just as I want the power to do a quick > sys.setAppDefaultEncoding('utf-8') to make sure this application sees all > its strings as encoded in utf-8. It could not guarantee this. If you read a byte string from some external source, it might well not be UTF-8, and Python had no way to find out. Regards, Martin From fredrik at pythonware.com Mon Jul 1 10:42:02 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 14:42:02 GMT Subject: Problems with Python CGI under Windows References: Message-ID: <_SZT8.14079$p56.4584922@newsb.telia.net> Domingo L?pez L?pez wrote: > I am trying to read -from the standard input- a binary (JPEG) file > in a Windows web server with a CGI. The problem is that python does > not seem to support binary reading from standard input, because > the reading stops when a 0x1A character (CTRL-Z) end of file arrives. make sure you run the python interpreter with the -u option; see e.g. http://starship.python.net/crew/davem/cgifaq/faqw.cgi?req=show&file=faq01.003.htp http://www.python.org/topics/web/windows.html (googling for something like "python CGI windows" would have told you this in a fraction of the time it took you to write your message, of course... ;-) From aleax at aleax.it Sat Jul 27 04:05:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 08:05:17 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <38j09.146115$vm5.4761453@news2.tin.it> <7x3cu6f8sv.fsf@ruckus.brouhaha.com> Message-ID: <1vs09.126786$Jj7.2916015@news1.tin.it> Michael Gilfix wrote: > If it were the case that 'arbitrary code' could be truly > 'lambdafied', wouldn't it be safe to say that arbitrary code could > then be pickled as well? I don't see any connection between the two issues. lambda form vs a def statement is strictly a syntax issue. You cannot pickle a lambda any more than you can pickle a function built by def. Alex From aahz at pythoncraft.com Mon Jul 15 14:15:54 2002 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2002 14:15:54 -0400 Subject: OSCON: Community dinner Weds 7/24 6pm Message-ID: [posted to c.l.py with cc to c.l.py.announce and python-dev] I'm proposing a Python community dinner at OSCON next week, for Weds 7/24 at 6pm. Is there anyone familiar with the San Diego area who wants to suggest a location near the Sheraton? If I don't get any recommendations, we'll probably just have the dinner at the Sheraton. If you're interested, please send me an e-mail so I have some idea of the number of people. Also, please include a way of getting in touch with you at OSCON in case plans change (phone numbers accepted, but e-mail addresses preferred). (There's a meeting for PSF members at 8pm, so some of us will likely have to skip out early.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jjjccc222 at earthlink.net Sun Jul 21 12:38:22 2002 From: jjjccc222 at earthlink.net (TMinSF) Date: 21 Jul 2002 09:38:22 -0700 Subject: Setting the right border in PythonWin IDE References: <817kjqi8wo.fsf@darwin.lan.kassube.de> Message-ID: <1e2446ac.0207210838.75013e54@posting.google.com> Nils Kassube wrote in message news:<817kjqi8wo.fsf at darwin.lan.kassube.de>... > Guten Abend. > > How do I set the right text border/margin in the PythonWin IDE shell > from ActivePython 2.2.1? > > If I try e.g. dir(sys) the resulting list is annoyingly displayed on a > single line. I've tried playing with the settings like e.g. right edge > mode in View/Options... but nothing seems to wrap text on a new line > after a certain number of characters. > > Danke im voraus, > Nils Same problem, but even worse. When I try to scroll right with the hor. scrollbar thumb, that doesn't work correctly either (W2K, Python 2.2.1, PythonWin 2.2.0.146). When the scroller thumb is all the way to the right, I should be at the end of the single line but I'm not. To see more of the line, I have to hold down the hor. scrollbar right arrow button. Aside from this _really_ annoying feature, I love PythonWin. If this is just a config issue, I hope someone out there will help us out. I've looked everywhere I can think of and can't find the answer. TM From franke at ableton.com Thu Jul 4 06:26:42 2002 From: franke at ableton.com (Stefan Franke) Date: Thu, 04 Jul 2002 12:26:42 +0200 Subject: Web templating/db tool with best designer/coder separation? References: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> <23891c90.0207021228.6809cf9b@posting.google.com> Message-ID: On 2 Jul 2002 13:28:53 -0700, paul at boddie.net (Paul Boddie) wrote: [...] >I think that this is really the way to go for anyone interested in >investigating the subject area further, rather than inventing yet >another "source code in HTML" solution and hoping to find out new ways >of working from that. > >Paul What makes we wonder is, that XMLC was at least mentioned on zope-dev along with the abandonment of Hiperdom in favour of the upcoming ZPT about two years ago - as a quick archive search yielded. Nevertheless it didn't have influence any influence on the design of ZPT. Or were there any deliberate design decisions against this approach? From claird at starbase.neosoft.com Mon Jul 8 19:01:58 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 8 Jul 2002 18:01:58 -0500 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7xwus7n5q4.fsf@ruckus.brouhaha.com> <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> <3D2A078A.7040502@ob_scure.dk> Message-ID: <06F2E275AA053281.30FCDA468DD949D2.9ED8D7E798995448@lp.airnews.net> In article <3D2A078A.7040502 at ob_scure.dk>, Thomas Jensen wrote: . . . >I have, on purpose, not described the workings of this program in very >great detail, since my original post was more about the general idea of >using Python for this kind of job. Having easy access to distributed >computations is merely a bonus and, if nothing else, a buzz-word to >mention to managment *hint*. >Furthermore, the ability to scale the application simply gives a good >feeling, even if it is *never* needed. . . . >Satisfying, perhaps, but could you elaborate on scalable? > >I simply fail to see how it is that distributed computing is so bad? >Everybody seems to think that once you make something distributed, every >other optimization posibility simply disapear? >I never said distributed computing was a priority or even would be a >part of the first version. I *is* a design goal however, that should we >one day, after all other optimizations in the world, using SQL, need >more speed, we can do so by adding machines/CPUs (be it DB servers or >application servers). . . . I call SQL noodling "scalable" in the sense that good SQL queries can be hosted on bigger and bigger servers. We know how to do that--it's a commercial reality. I *like* distributed computing. I've spent much of the last eighteen months promoting SOAP, XML-RPC, and CORBA. Your mention of Linda and its descendants, including T-Spaces, thrilled me. HOWEVER, I rarely recommend distribution for performance objectives, for reasons that have mostly appeared already in this thread. Com- mercial applications (as opposed to scientific ones) just don't find success that way. Your situation might be an exception. It's hard to know. The computations you describe--DB retrievals, elementary statistics, ...--sound to me like ones that I've seen most successfully hosted on conventional architectures. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From cliechti at gmx.net Tue Jul 23 09:42:44 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 15:42:44 +0200 Subject: Adding Modules to precompiled installation of Python References: Message-ID: "Jayant Kulkarni" wrote in news:ahiii8$4u2$1 at news01.cit.cornell.edu: > My problem I guess is very specific so I doubt if somebody has run into > it before but any general help would be appreciated. > > I am using the finite-element package Abaqus which comes with > precompiled Python (ver 1.5). I want to interface this with Matlab using > Pymat. (PyMat utility by Sterian). The problem is that as the python is > precompiled I do not know how to import new modules.. > > Additional info: > The PyMat utility comes with PyMat.cpp and Pymat.pyd. > I am on a Windows OS. (Though I have access to Linux, and I can work on > that system as well.. So solution to the problem in any OS should be of > help) have you tried to copy those file to the current directory an type (or make a script with): import PyMat either it works or you'll get an exception from python. if you get an exception, add it to you next msg. note that pyd must be compiled for a specific python (major) version (i.e. 1.5/2.0/2.1 etc.). so you'll need Pymat.pyd for 1.5 chris -- Chris From jadedlime at hotmail.com Tue Jul 30 15:13:05 2002 From: jadedlime at hotmail.com (jadedlime) Date: Tue, 30 Jul 2002 15:13:05 -0400 Subject: comparing strings Message-ID: <3d46ffa7$1_9@news.teranews.com> Hi, I am very new to Python and very new to programming in general. I need to take a particular string of data and compare it to a dictionary which will put all matching records in a specific file and all the records from the string that do not match in another to be dealt with on an individual basis. I appreciate any and all help on this problem, part of the code is included. this seems to produce the matches, but not the mismatches. import string, re, codecs # create inputs and outputs input = codecs.open("/home/jadedlime/Julio/julio.work", "r", encoding="ISO-8859-1") output = codecs.open("sec_try", "w", encoding="ISO-8859-1") output2 = codecs.open("sec_trynotfound", "w", encoding="ISO-8859-1") # read and split the lines of the main julio records whole = input.read() lines = string.split(whole, "\n") # create the dictionary with regular expressions built in dictionary = {"^aarl australian academic & research libraries$" : "10735", "^acimed$" : "11225", "^adbs: l'association des professionnels de l'information et de la documentation$" : "11715", "^alpha 94. strat\351gies d\222alphab\351tisation et de d\351veloppement culturel en milieu rural\ $" : "12205", "^american archivists$" : "13185", "^anales de documentaci\363n$" : "14165", "^annual review of information science and technology (arist)$" : "14655", "^aproximaciones a la traducci\363n$" : "15145", "^apuntes$" : "15635", "^architectural records conference report$" : "16125", "^archivaria$" : "16615", } # take the desired field (journal titles) and put it in a list format journallist = [] for line in lines: field = string.split(line, '"') journalitems = string.strip(string.lower(field[23])) journallist.append(journalitems) # compile the dictionary and make it into a list format dictionarykeys = dictionary.keys() dictionarylist=[] for dictionaryexp in dictionarykeys: regular = re.compile(dictionaryexp) dictionarylist.append(regular) # run a search that should match all the journal titles in the julio file to the ones in # the dictionary, if they match send them to a specific file, if they do not, send them # to another file so ajustments can be made. for key in dictionarylist: for item in journallist: if re.search(key, item): output.write("found\t" + item + "\n") else: output2.write("not found\t" + item + "\n") From codeapocalypse at msn.com Tue Jul 9 11:51:24 2002 From: codeapocalypse at msn.com (Brian) Date: 9 Jul 2002 08:51:24 -0700 Subject: How can I retrieve the ID of the last record I added? References: Message-ID: Oops. I just realized you're accessing both MySQL as well as MSSQL. My comment about @@IDENTITY applies to MSSQL. I haven't been exposed to MySQL yet. :) From timr at probo.com Tue Jul 23 01:23:02 2002 From: timr at probo.com (Tim Roberts) Date: Mon, 22 Jul 2002 22:23:02 -0700 Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> "David LeBlanc" wrote: >Book. It's out. From O'Reilly. See >http://www.oreillynet.com/pub/a/network/2002/07/15/regexp.html > >Claims extensive Python re coverage. In addition to the other usual >suspects, also covers Java, Ruby, php and .net. > >Hope it's as good as the first one was/is! Hear, hear. My colleagues scoffed when I bought it, thinking that the subject surely couldn't be worthy of an entire book. They were wrong. It is a valuable reference that I keep close by. The multi-thousand byte full expression to match a valid RFC822 e-mail address was practically worth the price all by itself! -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 20:37:33 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 17:37:33 -0700 Subject: performance problem in python 2.2 References: <7xn0sedslz.fsf@ruckus.brouhaha.com> Message-ID: <7xlm7yj99u.fsf@ruckus.brouhaha.com> Jeff Davis writes: > > $p = 2**64; > > $c = $ARGV[0]; > > $n = exp(-($c*$c) / (2*$p)); > > print 1-$n, "\n"; > > > I learned to never underestimate the usefulness of mathematics in > programming. Lucky for me, I had a teacher to ask and he gave me a lot of > good info as well. After giving me some advice (including CS related tips > that mostly boiled down to "Use assembly, or maybe C if you can about > getting an answer"), he pointed me to Sterling's Theorem, which seems > similar to what you did. Stirling's approximation is pretty complicated to prove. The formula I gave for hash collisions is a lot simpler and you should be able to discover it with basic calculus. I'll leave the details as an exercise for you ;-). From torrance at mondenet.com Sat Jul 27 10:11:33 2002 From: torrance at mondenet.com (George Torrance) Date: Sat, 27 Jul 2002 10:11:33 -0400 Subject: Beginner problems importing module Message-ID: <3D42AA15.DCB73E25@mondenet.com> Hi: I am a beginner and am trying to use the module winioport by Dincer Aydin. I put the files for this in the main c:\python22 directory. When I try to import winioport I get the following error message >>> import winioport Traceback (most recent call last): File "", line 1, in ? import winioport File "C:\PYTHON22\winioport.py", line 63, in ? import windll # import windll module File "C:\Python22\Lib\site-packages\winio\windll.py", line 20, in ? import calldll ImportError: DLL load failed: One of the library files needed to run this application cannot be found. >>> Does this mean that it cant find calldll (which I put in c:\python22), or that calldll can't find some library file it is looking for? Any help appreciated! G Torrance From ng at LarryCurlyMolingo.com Tue Jul 2 02:56:06 2002 From: ng at LarryCurlyMolingo.com (Kevin Chambers) Date: Mon, 01 Jul 2002 23:56:06 -0700 Subject: Newbie: Zope Formulator TALES question Message-ID: <3D214E86.6070908@LarryCurlyMolingo.com> Hi there-- I'm trying to use the Formulator TALES functionality to change the default value of a field object for every record in an sql result set that I'm looping through with tal:repeat. Just putting in this_record/FirstName, as I would do in tal:attributes="default this_record/FirstName", doesn't work. I've also tried variations on python:here['FirstName'] with no luck. Is there any way to get this to work, or should I just make my own fields to get this kind of functionality? Thanks in advance, KC (remove Larry & Curly for email) From t.gawantka at freenet.de Tue Jul 30 05:16:18 2002 From: t.gawantka at freenet.de (Thorsten Gawantka) Date: Tue, 30 Jul 2002 11:16:18 +0200 Subject: wxTextCtrl + wxGrid Message-ID: Hi Group, how can I get the Value of wxTextCtrl into a Cell of wxGrid? my actual code is -- ## Copy the textCtrl.Value into gridCell self.grid.SetCellValue(i, 0, self.edit_p1.GetValue) ## -- this is not functional, because the python interpreter want to have a string. How can I get this solved? -- mfg Thorsten Gawantka From a-steinhoff at web.de Thu Jul 11 05:03:50 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 11 Jul 2002 02:03:50 -0700 Subject: Python in the enterprise: Pros and cons References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: sarah.fraser at cnet.com (builder) wrote in message news:<33e8a47f.0207101302.1bd3d902 at posting.google.com>... > Python has many fans in the open source community, but is it ready for > the enterprise? Here are the advantages and disadvantages of using > Python in the corporate environment. > http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm There are not mentioned the GUI tools wxPython and PyQt ! We are buidling industrial applications with PyQt (and the Qt Designer) and the embedded SQL databases 'gadfly' and 'PySQLite'. These applications are system independent and are working under QNX6.2, Linux and Windows. From ld at nospam.com Sun Jul 14 16:39:26 2002 From: ld at nospam.com (Larry) Date: Sun, 14 Jul 2002 20:39:26 GMT Subject: List to STR to List References: <2glY8.79177$vm5.2885629@news2.tin.it> Message-ID: <2klY8.358075$R61.347878@rwcrnsc52.ops.asp.att.net> "Alex Martelli" wrote in message news:2glY8.79177$vm5.2885629 at news2.tin.it... > Larry wrote: > > > I can convert a list to a string as follows: > > > > List1 = [1,2,3] > > String1 = str(L1) > > > > Is there now a way to convert my String1 variable back into a list??? > > There are several ways, but probably the most reasonable one is: > > import rexec > > alist = rexec.RExec().r_eval(String1) > > > All those 'r' stand for Restricted -- you want Restricted > execution (evaluation, in this case) to make sure no disaster > can happen, just in case the string may have been hacked > by some clever fellow. > > If you must perform many such evaluations, it's speedier to: > > > import rexec > > rr = rexec.RExec() > > alist1 = rr.r_eval(String1) > alist2 = rr.r_eval(String2) > alist3 = rr.r_eval(String3) > Thank you so much for the speedy response! Larry From cliechti at gmx.net Sat Jul 27 19:49:34 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Jul 2002 01:49:34 +0200 Subject: xrange questioin References: <3d43234e$1@duster.adelaide.on.net> Message-ID: "Gerald Squelart" wrote in news:3d43234e$1 at duster.adelaide.on.net: > "Chris Liechti" wrote: >> Uwe Schmitt wrote: >> > as xrange() comsumes less memory than range() I ask why >> > I should use range() at all.... is there any benifit >> > from using range() ??? >> >> with range you get a true list which you can manipulate, sort, >> reverse, etc ... you can't do that with xrange. >> >> chris >> >> -- >> Chris > > Ok, let me rephrase Chris' question for a simpler case: it wasn't my question... but i'll try to answer yours > What is better: for x in range(n) or for x in xrange(n)? > (with n is relatively small, like 10 or 100) that depends on your definition of "better" ;-) considering speed, "range" is slightly faster for small n chris -- Chris From robert_kuzelj at yahoo.com Wed Jul 3 02:41:55 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 2 Jul 2002 23:41:55 -0700 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: hallo walter, thanks for the reply. >> class metatype(type): pass >> >> class A1: pass >> class B1(object): pass >> class C1: __metaclass__ = metatype >> >This is not a bug, it's one of the main features of new style >classes. what is a feature of 2.2? that you cant distinguish between a class and an instance? hardly! >> of what type are B1() and C1()? > B1 and C1. i am very well aware of this. but it doesnt solve my problem. because C1.__class__ =~ metatype C1().__class__ =~ C1 there is no _direct_ possebility to find out if a given object is an instance or a class (new style one that is). well there is a workaround: if not isinstance(obj, types.ClassType) and \ not isinstance(obj, types.TypeType): print "its an instance!" but isn't explicit better than implicit? i think i have read this somewhere on the python pages? didnt i? ;-) imo it should be very clear that there is a difference between the following two statements: class A(object): #defines a class which is an object of type type. A() # creates an instance and the information on how the object was created should be explictly accessibly. ciao robertj From mdehoon at ims.u-tokyo.ac.jp Thu Jul 25 09:20:03 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Thu, 25 Jul 2002 22:20:03 +0900 Subject: distutils gcc unix Message-ID: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> I am trying to compile a python extension with python setup.py install on a unix system. Distutils takes the cc compiler instead of the gcc compiler, which is also available on the system. Unfortunately, my extension doesn't compile with cc, it needs gcc. Is there some way to tell distutils to use the gcc compiler? I have tried things like python setup.py build --compiler=gcc but it didn't know 'gcc'. When I try python setup.py build --compiler=cygwin it uses the gcc compiler, but of course not with the right options to the compiler. It is possible to specify which compiler distutils should use? Many thanks in advance, Michiel de Hoon University of Tokyo, Human Genome Center From cce at clarkevans.com Wed Jul 3 20:47:58 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Wed, 3 Jul 2002 20:47:58 -0400 Subject: tzset() In-Reply-To: <20020703133510.A22032@doublegemini.com>; from cce@clarkevans.com on Wed, Jul 03, 2002 at 01:35:10PM -0400 References: <20020703133510.A22032@doublegemini.com> Message-ID: <20020703204758.A28239@doublegemini.com> On Wed, Jul 03, 2002 at 01:35:10PM -0400, Clark C . Evans wrote: | On Thu, 16 Jun 1994 at 13:01:14 +0200 Guido van Rossum wrote: | | The most pragmatic way to solve this is probably to add a function | | tzset("string") to the time module which forces TZ="string" in the | | process's current environment and then calls the C tzset() again (and | | reinitializes the Python variables that describe the timezone). | | | | This is a great idea; was it ever done? Here is a snippet module which does the above, only it returns a tuple (timezone_abbrev, gmt offset ) share & enjoy, clark ... #include #include #include #include #include PyObject * offset(PyObject *self,PyObject *args) { time_t now; struct tm a; char *tznm; PyObject *pyobj; if(1 != PyTuple_Size(args)) { PyErr_BadArgument(); return NULL; } pyobj = PyTuple_GetItem(args,0); if(!pyobj) return NULL; if(!PyString_Check(pyobj)) { PyErr_BadArgument(); return NULL; } (void) setenv("TZ",PyString_AsString(pyobj),1); tzset(); now = time( NULL ); (void)localtime_r( &now, &a ); tznm = tzname[a.tm_isdst]; pyobj = Py_BuildValue("(sl)",tznm,a.tm_gmtoff/60); return pyobj; } PyMethodDef methods[] = {{"offset",offset,METH_VARARGS},{NULL, NULL}}; void inittztool(void) { (void) Py_InitModule("tztool", methods); } From cappy2112 at yahoo.com Mon Jul 22 01:43:24 2002 From: cappy2112 at yahoo.com (Tony C) Date: 21 Jul 2002 22:43:24 -0700 Subject: Command history (up arrow) in IDLE on Windows 2000 Message-ID: <8d3e714e.0207212143.3b692496@posting.google.com> Is it possible to enable command history in IDLE ? I'm using version .8 on Windows 2000. It's really irritating not to have command history, like in BASH or Cshell. thanks Tony cappy2112 at yahoo.com From b.maryniuk at forbis.lt Thu Jul 11 05:30:23 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 11:30:23 +0200 Subject: Python in the enterprise: Pros and cons In-Reply-To: References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: <200207111130.23638.b.maryniuk@forbis.lt> On Thursday 11 July 2002 11:03, Armin Steinhoff wrote: > These applications are system independent and are working under > QNX6.2, Linux and Windows. BTW, can You explain how to use QT/Python under Windows for non-commertial soft? I've tried and I've fault... What I should download from TrollTech to make my hello_world.py run QT widgets on Bill's platform? :/ Note, that I have only Windows OS (no VisualBasic, no VC++, no Borland stuff etc). Only notepad.exe :) In other hand, I successfully use wxWindows on M$ Windows and Linux OS. And no problem tu run Python / QT 3.0 on Linux box. So seems that QT is quite hard to install on Windows. :| -- Sincerely yours, Bogdan M. Maryniuck "World domination. Fast" (By Linus Torvalds) From fredrik at pythonware.com Sun Jul 14 06:53:05 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Jul 2002 10:53:05 GMT Subject: structs in python References: Message-ID: Paul Magwene wrote: > > What if a syntax like the following were permitted: > >>>> p = ( .x = 10, .y = 11, .color = 'blue') > > I often find myself doing something similar to the following (usually > when I want to return multiple things from a function) > > >>> class Struct: > ... pass > ... > >>> p = Struct() > >>> p.x = 10 > >>> p.y = 11 > >>> p.color = 'blue' > > That's slightly more verbose than you're proposed syntax but doesn't > usually feel to onerous (especially since you only have to declare the > Struct class once). the more reason to "do the right thing", right? ;-) class Struct: def __init__(self, **kw): self.__dict__.update(kw) > If you like everything on one line you could do: > > >>> p = Struct(); p.x = 10; p.y = 11; p.color = 'blue' p = Struct(x=10, y=11, color='blue') From jkrahn at nc.rr.com Sat Jul 20 09:38:49 2002 From: jkrahn at nc.rr.com (Joe Krahn) Date: 20 Jul 2002 06:38:49 -0700 Subject: Using pointers Message-ID: <4210d7a2.0207200538.44a91c0f@posting.google.com> Can I make a pointer to an object in Python? I know that all objects/variables are references, but not in the same sense as in C. How do I get multiple pointers to reference and modify one variable? From spenrose at well.com Fri Jul 12 12:50:42 2002 From: spenrose at well.com (Sam Penrose) Date: Fri, 12 Jul 2002 09:50:42 -0700 Subject: XML overuse? (was Re: Python to XML to Python conversion) Message-ID: <80D162F5-95B7-11D6-8EA2-003065B33450@well.com> Elliote Rusty Harold's XML News site Cafe Con Leche at features pithy commentary on this topic. See especially . Harold is also a big Java guy; his Java news site Cafe au Lait occasionally contains positive mentions of Python. From fpm at u.washington.edu Wed Jul 24 11:21:13 2002 From: fpm at u.washington.edu (Frank Miles) Date: 24 Jul 2002 15:21:13 GMT Subject: GUI toolkits References: Message-ID: In article , Stefano Vedovelli wrote: >Hello all > >in my spare time I am writing a tool in python, with the intention of >deliver it under GPL. > >I am now starting to approach the GUI part. I have read a lot about Tkinter, >PyQT and wxWindows, but I am now actually even more confused. > >As the interface will be "quite" rich, I'd like to know the opinions of >people who already faced this decision, which tool they have chosen and >why. You might want to investigate pyGTK as well. With glade to help creating the graphical part, its easy and quite compatible with GPL. -frank -- From simon at uggs.demon.co.uk Sun Jul 7 18:19:43 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Sun, 07 Jul 2002 22:19:43 GMT Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> Message-ID: <3d28bdb0.71631360@news.dsl.pipex.com> On 8 Jul 2002 00:07:47 +0200, Chris Liechti wrote: >'cause split() drops the empty part at the end: >>>> '1\n2\n3\n'.split() >['1', '2', '3'] >>>> '1\n2\n3\n'.split('\n') >['1', '2', '3', ''] > I see it, but I don't see why? What is the explanation for this? It seems at odds with the documentation. From mertz at gnosis.cx Thu Jul 4 01:35:34 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 04 Jul 2002 01:35:34 -0400 Subject: [OT] What is Open Source? References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: "Clark C . Evans" wrote previously: |I don't. I firmly believe that copyright and patent are |fundamentally good ideas (trademark is the best of the three). |They are a contract between the public as a whole to a inventor/author. The only problem with this belief is that it is completely, totally, 100% wrong. A copyright is, quite simply, a legally enforced artificial monopoly--not a contract. These are quite different things. A contract involves an agreement between or among two or more parties concerning the exchange of goods or services. Any time I contract for something, I give up something in my "natural" possession. It could be some bills of currency, it could be some bushels of corn, or it could be some hours of my labor-time. But in fulfilling my end of the contract, I give up the right to use a consideration. In fact, I could contract to sell you a physical copy of my forthcoming book... thereby parting with the object for some amount of money (or a trade for something else). Copyright has nothing to do with this contract I have made, except in the sense of artificially inflating prices, in some contexts. I can deliver the physical book as a contractual matter, copyright is a restriction on what you can do with the book once it is in your possession--specifically, it is a state mandated prohibition on you entering into contracts with other people to deliver other objects that are "abstractly similar" to the object I delivered to you. Of course, quite unlike a contract, you are subject to this restriction whether or not you have bought the physical book from me, entered into any contract with me, or even ever met or heard of me. On the other hand, a contract to sell you bushels of corn cannot legally contain the same restriction on the use to which you put the corn... once you buy it, it's yours to do with as you wish. One could imagine that copyright was like some odd sort of covenant: I "sell" you the corn, but with the covenant that it be made only into corn muffins, not polenta. A covenant like this is -conceivably- enforceable, and does have a superficial similarity. But for a covenant to be binding, you (the "buyer") have to actually enter into it. Copyright restrictions require no such entry; a copyright restriction is much more similar to a prohibition on murder or drug-possession. The state decides (rightly or wrongly) that its citizens should do certain things rather than others, and mandates such. Contracting parties have nothing to do with the legality of murder--and any contract requiring it is void on its face. Likewise, copyright. -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From mgilfix at eecs.tufts.edu Fri Jul 26 16:41:05 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 26 Jul 2002 16:41:05 -0400 Subject: __call__ bad style? (was Re: Callable modules?) In-Reply-To: ; from aleax@aleax.it on Fri, Jul 26, 2002 at 01:57:12PM +0000 References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: <20020726164104.A10773@eecs.tufts.edu> That's interesting because I went into EE in school precisely because I wanted to learn to build stuff, even though I knew I was always going to do CS when I graduated. And then of course, when looking for a job, I said I wanted a pure software job but could do hardware if I had to :) But then again, I start my first real industry job in 3 weeks. -- Mike On Fri, Jul 26 @ 13:57, Alex Martelli wrote: > Me neither: I wanted to design hardware. I chose electronic engineering, > then hardware design specialties within that, a thesis in the HW field, and > jobs with Texas Instruments, then with IBM Research, each meant to be > about hw design. Each and every time the "hw" job turned out to be about > designing, coding and/or maintaining programs to test, design, simulate > and/or exercise hardware. At which point I resigned myself to the fact > that the universe wanted me to do software, not hardware, and learned > to like it. Haven't even _pretended_ to design a chip in 20 years now. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From hst at empolis.co.uk Mon Jul 15 12:12:56 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Mon, 15 Jul 2002 17:12:56 +0100 Subject: Problem using py2exe Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F3FB@hendrix.empolisuk.com> I've got a program that works fine, when run using the Python interpreter, but when I convert it to a Windows exe using py2exe, I get the following traceback: File "", line 96, in ? File "", line 77, in main File "apex.pyc", line 219, in apexopen File "codecs.pyc", line 499, in open Line 219 of apex.pyc is: return codecs.open(fn, mde, 'utf8') I guess I need to force py2exe to read something it can't pick up automatically, but I can't work out what the something is. Any help appreciated Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From K.Rdt at TU-Berlin.DE Mon Jul 1 03:27:19 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Mon, 01 Jul 2002 09:27:19 +0200 Subject: wxPython-questions (netstat) Message-ID: --------------------------------------------------------------------- Hi I have a wxPython-script which is monitoring netstat, but there are some questions: 1.) Is there a clearscreen option? 2.) Is there a gotoxy option? 3.) Why I have to have 2 windows? 4.) Can I have direct access to net-information? tia K at Rdt --------------------------------------------------------------------- # vim:tw=78:ts=3:sw=3: #********* So 30.06.02 17:45-1 ************** . . . . . . . . r 2 . p y w */ from wxPython.wx import * from wxPython.lib.infoframe import * import sys,os,thread #============================================ . . . . . . . . . . . . . . */ class MyFrame(wxFrame): def __init__(self,output): wxFrame.__init__(self,None,-1,"Close me...",pos=(0,110),size=(300,100)) output.SetParent(self) EVT_CLOSE(self,self.OnClose) EVT_TIMER(self, -1, self.OnTimer) self.timer = wxTimer(self, -1) self.timer.Start(3000) self.save_stdout = sys.stdout sys.stdout = self.output = output self.icon = wxIcon('1_ast.ico', wxBITMAP_TYPE_ICO) self.SetIcon(self.icon) def OnClose(self,event): sys.stdout = self.save_stdout self.output.close() self.timer.Stop() self.timer = None self.Destroy() def OnTimer(self, evt): y=os.popen( 'netstat -a -n','r').read() print y #============================================ . . . . . . . . . . . . . . */ class MyApp(wxApp): outputWindowClass = wxPyInformationalMessagesFrame def OnInit(self): frame = MyFrame(self.stdioWin) frame.Show(TRUE) self.SetTopWindow(frame) return true #-------------------------------------------- . . . . . . . . . . . . . . */ app = MyApp(1) app.MainLoop() #********* So 30.06.02 17:45-1 ************** . . . . . . . . r 2 . p y w */ From bokr at oz.net Mon Jul 1 15:05:22 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2002 19:05:22 GMT Subject: arguments to functions References: Message-ID: On Mon, 01 Jul 2002 11:10:44 GMT, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> >>> test(10, 11, 12, expected=5) >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: test() got multiple values for keyword argument 'expected' >> >> I'd be inclined to call that a bug, actually. > >only if you're ignoring the language reference, which tells >you how this really works. > Yes, my "inclination" to call it a bug was wrt how-I-think-maybe-it-should-work, so I was only inclined to, not actually doing it ;-) What would break by allowing keyword parameter names to duplicate ordinary parameter names? IWT probably nothing at this point, since it's not allowed. New code would presumably either be written to use the feature, or at worst have a new way to make a programming error without the current error message. Regards, Bengt Richter From artemio at .ic.kharkov.ua Sun Jul 14 14:39:42 2002 From: artemio at .ic.kharkov.ua (artemio) Date: Sun, 14 Jul 2002 21:39:42 +0300 Subject: web hosting with python cgi References: <20020714120559.46e0a1f2.wilk-spamout@flibuste.net> Message-ID: <1026671972.789324@console.ic.kharkov.ua> Ian Bicking wrote: > If Python is installed, it will be available to you for CGI unless the > host goes to efforts to keep people from using it -- which would just be > mean (not that there aren't mean hosters). If a provider already has > Python installed, even unadvertised, it's very unlikely to disappear. > > Ian yes, i agree python is a standard package which is required by a number of other applications, so it is very ulikely to be unsupported on almost any unix/linux machine just write a script, run it from a server and you will surely know :-) From marklists at mceahern.com Fri Jul 26 14:07:31 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 26 Jul 2002 13:07:31 -0500 Subject: extract elements of n char from a list In-Reply-To: Message-ID: for what it's worth, on my system, it's not until you get 1,000,000 elements in the list that the difference between list comprehensions and filter begins to show--so i'd say flip a coin and pick one. // m #! /usr/bin/env python from time import clock def time_it(f, *args, **kwargs): time_in = clock() result = f(*args, **kwargs) time_out = clock() return time_out - time_in, result def filter_with_lc(list_to_filter, predicate): return [x for x in list_to_filter if predicate(x)] def filter_with_filter(list_to_filter, predicate): return filter(predicate, list_to_filter) def odd(n): return n % 2 != 0 def show(func, results, delta): print "%s: %1.3f" % (func.func_name, delta) if __name__ == "__main__": import sys default = 1000 try: size = int(sys.argv[1]) except IndexError: size = default original = range(size) t1, r1 = time_it(filter_with_lc, original, odd) t2, r2 = time_it(filter_with_filter, original, odd) assert r1 == r2 show(filter_with_lc, r1, t1) show(filter_with_filter, r2, t2) From see_reply_address at something.invalid Thu Jul 4 21:16:27 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 13:16:27 +1200 Subject: multiple inheritance & __init__ References: Message-ID: <3D24F36B.3010307@something.invalid> Stephane Ninin wrote: > is there any reason to choose this order: > > Observer.__init__(self) > Tkinter.Listbox(self) > > or this order: > > Tkinter.Listbox(self) > Observer.__init__(self) If the classes Observer and Tkinter.Listbox don't know anything about each other, then the order shouldn't matter. It would only matter if, for example, Observer expected to be mixed in with a Tkinter widget and required the widget to be initialised first. If there are no such dependencies, the order is up to you. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From als at usenet.thangorodrim.de Wed Jul 24 10:26:16 2002 From: als at usenet.thangorodrim.de (Alexander Schreiber) Date: 24 Jul 2002 14:26:16 GMT Subject: accessing a file's creation time References: Message-ID: hejduk wrote: >i'm running 2.2 on linux 2.4.5 (slak 8.0.) my question is whether >there is any way to access a file's creation time . os.stat provides Not possible since this information is simply not available. >access to constants that represent a file's last access time, last >modification time, and last inode change time, but seemingly no way to >get it's actual time of creation. i know the os stores this >information somewhere (a simple "ls -l" demonstrates this), but i just >can't seem to find a way to access it. UNIX doesn't usually. And the regular VFS layer simply has no provisions for dealing with this information, even if a filesystem _did_ store it somewhere. Have a look a struct stat as described in stat(2). Regards, Alex. -- Those who desire to give up Freedom in order to gain Security, will not have, nor do they deserve, either one. -- Benjamin Franklin From list-python at ccraig.org Tue Jul 2 14:07:05 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 02 Jul 2002 14:07:05 -0400 Subject: private In-Reply-To: References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "James Kew" writes: > Is there any good newbie documentation for docstrings? http://www.python.org/doc/current/tut/node6.html#SECTION006750000000000000000 I don't know what's shipped with ActiveState, so that may or may not be something you've already read. You'ld have to establish your own conventions for saying how docstrings indicate what is public. -- Christopher A. Craig "The absolute value of the TA was less than epsilon" - MIT Course Evaluation From karczma at info.unicaen.fr Tue Jul 9 12:04:03 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Tue, 09 Jul 2002 18:04:03 +0200 Subject: sorting many arrays from one... References: <%KCW8.60416$vm5.2194409@news2.tin.it> Message-ID: <3D2B0973.B553A25F@info.unicaen.fr> Alex Martelli wrote: > ... ABSOLUTELY forget the idea of passing a compare function to aux.sort!!! > This would drag the sorting down to a HORRIBLE crawl. COnsider (python > 2.2.1, -O, on 1.4 GHz Athlon with DDR RAM to burn): ... > >>> a=time.clock(); xx.sort(); b=time.clock(); print b-a > 0.81 > ... > >>> a=time.clock(); xx.sort(f); b=time.clock(); print b-a > 10.97 > even for this super-simplified case where the sequence to sort is so > clean and the comparison function does nothing more than delegate to > the same cmp that would be used anyway, you pay well more than an > order of magnitude for the privilege of passing a compare function > to the sort method!!! This was one of my principal griefs when I began to learn Python. I still don't know why is it so costly. One may suppose that an interpreted user function f which calls cmp may be the main reason, but xx.sort(cmp) is also slow [in my rudimentary test about twice as fast as sort(f)]. Somebody cares about explaining this behaviour? Dynamic dispatching, while sort() does not any dereferencing? Or what? For people coming from the Functional Programming Realm such slowdown of parameterized functionals is hard to accept... > Don't do it. Use D-S-U, as AMPLY explained in the searching and > sorting chapter of the Python Cookbook I don't want to depreciate your helpful attitude addressed to a person in need, nor say anything bad about something considered a "common idiom", but the idea of Decorate-Sort-Undecorate, which begins by constructing an additional list with fast-sortable keys is also something hard to digest. The author of the original question had 300 000 items. I had once five times more, and I found it a bit ridiculous to pollute the memory with an ephemeric sequence just because there is something lousy with parametrized sort (and possibly other H. O. functions?) What do you think? Jerzy Karczmarczuk Caen, France From sethtoday at hotmail.com Fri Jul 12 12:36:41 2002 From: sethtoday at hotmail.com (Seth Ainsley) Date: Fri, 12 Jul 2002 16:36:41 +0000 Subject: Input again (!!@#&#$^@#$) Message-ID: An HTML attachment was scrubbed... URL: From paul at boddie.net Fri Jul 12 10:25:00 2002 From: paul at boddie.net (Paul Boddie) Date: 12 Jul 2002 07:25:00 -0700 Subject: ANN: Python Web Programming Wiki References: Message-ID: <23891c90.0207120624.3418464c@posting.google.com> "Daniel Dittmar" wrote in message news:... > As part of the relaunch of the Python Wiki > (http://www.python.org/cgi-bin/moinmoin/), I've copied Paul Boddie's work on > Web Programming Frameworks into the Wiki > (http://www.python.org/cgi-bin/moinmoin/WebProgramming) and added a few more > entries. > > Feel free to add more information, comparisons, recipes etc. To continue my endorsement of Daniel's reworking and enhancement of the original document, I've added some notes about presentation technologies and Enterprise JavaBeans. I also encourage framework authors to add their frameworks' details to the Wiki, rather than contacting me to update my document - I'll shortly be replacing my document with a link to the Wiki, so that it can become the definitive source of information on this topic. Thanks once again for the initiative, Daniel! Paul From gerhard.haering at gmx.de Wed Jul 24 14:19:42 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 24 Jul 2002 18:19:42 GMT Subject: Simple HTML classes References: <47ptjushoni8bfqurttm86sgt8bm6tge84@4ax.com> Message-ID: In article , Fernando Perez wrote: > Dale Strickland-Clark wrote: > >> We need a bunch of light-weight HTML classes to build web pages - >> especially forms. These will work with the CGI module so that the forms >> related classes are bi-directional. >> >> Before we start writing them them, I was wondering if anyone had done >> anything similar or there was a module I'd overlooked. >> >> I can't believe this hasn't been tackled before. > > Random, quite possibly wrong shot: have you looked at HTMLgen? AFAIK it only implements HTML 3.2. > I've used it for simple stuff and seems quite nice, but there may well be > a million reasons why it doesn't fit your problem. This looks cool, btw.: http://www.nextapp.com/products/echo/ It's a higher-level library for creating HTML, using the paradigms of traditional GUI programming. It'd be cool if there was something similar in Python, so I could check it out without touching Java at all ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From erno-news at erno.iki.fi Thu Jul 11 12:57:03 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 11 Jul 2002 19:57:03 +0300 Subject: struct unpack help? References: Message-ID: In article , "Scherer, Bill" writes: | Here's a sample string of the struct: | sampleStructString = "_782c1a08_p_void" | I know that the struct defines only two unsigned shorts. That | would imply (to me, anyway) a format of 'HH'. But calcsize of | that is 4, while my string is 16 bytes. So it appears you have a different definition of a struct than the struct module. if struct.calcsize('HH') returns 2, then it means that on your platforms shorts are 2 bytes each. the "p_void" in your string makes me think it might encode a c pointer (void *). the characters "782c1a08" might be a machine address, interpreted as an ascii string containing a hexadecimal number. -- erno From anton.wilson at camotion.com Wed Jul 31 12:33:36 2002 From: anton.wilson at camotion.com (anton wilson) Date: Wed, 31 Jul 2002 12:33:36 -0400 Subject: a soft real-time system using pythonm In-Reply-To: <20020731145848.GC1800@unpythonic.net> References: <200207311359.JAA15020@test-area.com> <20020731145848.GC1800@unpythonic.net> Message-ID: <200207311632.MAA01291@test-area.com> O > A realtime system places an upper bound on all operations, but the very > nature of Python makes this impractical if not impossible. > > An interaction between Python's handling of the GIL and the platform's > pthread library is going to be the least of your problems if you > actually intend to deliver a system which gives realtime guarantees on > Python programs. > > Jeff If the soft-real-time system we use makes simple function calls and only uses simple datatypes and possibly tuples, what are some of the potential pitfalls we could run into? I understand the deallocation issue and the garbage collection issue. (Does garbage collection have to be enabled?) Can we somehow get an idea on the worse case time delays in python using only simple function calls and assignments with small tuples and simple datatypes? From mgerrans at mindspring.com Tue Jul 9 02:00:10 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 8 Jul 2002 23:00:10 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: Based on the following circumstantial evidence, I think the troll theory mentioned earlier may is worth considering: - The "competitor" was not named. Why? Where is their web site with this propaganda? - The preamble sounds salesy. - There is no "free stuff" at the web site listed. - The rest of the nonsense listed is largely incorrect but invariably inflamatory -- trying to generate a large thread so that lots of people will go to the web site (or at least see the url). From tim.one at comcast.net Mon Jul 8 23:56:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 08 Jul 2002 23:56:56 -0400 Subject: Idle setup install falis on Win2k In-Reply-To: Message-ID: [David LeBlanc, wrestling with Idle on Windows] > BULLSHIT! > > RTFC! > > If you run /python22/tools/idle/setup.py install see what happens!!! Ah, you didn't mention setup.py before. I didn't even know there was such a thing. The PLabs Windows installer installed Idle by itself. There's no need for you to run setup.py for Idle on Windows; I assume it's there for the benefit of the Unix distro, but I don't really know. [various unhappiness snipped] > ... > If /python22/tools/idle/setup.py shouldn't be run on Windows, WHY IS IT > THERE? The Windows installer-builder copies the entire Idle source directory; ditto the entire Lib directory; and so on. I used to try to be more selective, but the way Wise works, copying a whole directory is trivial and fails soft, while trying to filter it leads to masses of hard-to-maintain script that fail hard. It's a "better safe than sorry" tradeoff. > Strange as it might seem to you, some Windows developers use a command > line and, at least in theory, if you install Idle, you should be > able to run it from a command line. (BTW, it did install in the python22 > group of the start menu.) You already know that you can extract the command line needed from the installed shortcut's Properties, if you want to use a command line. I have no axe to grind about that either way -- suit yourself. > AS for things that "only work for me", I have reinstalled C++, Python and > re-built standaloneZODB and it STILL compiles and crashes. I personally > suspect all the weird and funny games that are played by SAZODB when it > loads. Why, for example, does it import things and then delete them? > (site-packages/zodb/__init__.py). As I've told you several times, I don't currently work on SAZODB as such. You should raise your ZODB issues on the ZODB mailing list. I can assure you you'll get a lot of sympathy about the odd import tricks the code plays; there's an ongoing effort to reduce this obscure magicalness in Zope3 and ZODB4. > Just because I'm the only one experiencing a problem DOES NOT mean that > there's not a problem with your (Zope's) code! Sure. > I'm glad you declared the problem solved and then just walked away. That's out of line, David. I gave you a lot of help, and the last communication we had on the subject came from you on Saturday afternoon, where you said you were *going* to try some things ("reinstall VC6sp5 without the AMD extensions ASAP (not today though"). I never heard more about that until now. Now that I hear that it didn't work, I encourage you to send me the code you compiled, as I earlier sent you the code I compiled. The last I heard, the code I sent you worked for you. It would be helpful to learn whether the code you compiled fails for me. Chill out. it's-just-a-computer-ly y'rs - tim From max at malva.com.uaREMOVE.IT Wed Jul 10 07:54:42 2002 From: max at malva.com.uaREMOVE.IT (Max Ischenko) Date: Wed, 10 Jul 2002 14:54:42 +0300 Subject: Announce for Vim users: integration with PyUnit Message-ID: <2a7hga.g92.ln@cvs> See http://vim.sourceforge.net/tips/tip.php?tip_id=280 about how to run PyUnit from inside Vim editor. -- Java: write once -- debug everywhere. From fredrik at pythonware.com Wed Jul 24 12:16:26 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 24 Jul 2002 16:16:26 GMT Subject: xml processing : too slow... References: Message-ID: Alex Martelli wrote: > Actually I hadn't used xml.dom.minidom in AGES (had to refresh my > dim memories to write the XML chapter for the Nutshell) -- SAX is > just TOO much better for typical XML-parsing tasks in my opinion. my second generation XML-RPC implementation is built on top of a light-weight DOM library. the marshaller and unmarshaller implementations are about 15 lines each. the corresponding code in xmlrpclib.py is just under 300 lines... > Clearly not everybody agrees, or Paul Prescod, a great XML as well > as Python expert, wouldn't have developed xml.dom.pulldom, but then > I guess variety is the spice of life. guess Paul, like me, prefers "seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not reams of trivial code that bores the reader to death." ;-) From emile at fenx.com Wed Jul 10 08:31:42 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 10 Jul 2002 12:31:42 GMT Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: Fredrik Lundh > > from what I can tell, nothing happened. > *poof* ;-) -- Emile van Sebille emile at fenx.com --------- From fredrik at pythonware.com Mon Jul 29 12:24:24 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Jul 2002 16:24:24 GMT Subject: Newbie question about dictionaries References: Message-ID: Michael Hudson wrote: > > Is it right then that I have to implement a custom class for key objects if > > I want to use a custom hash function? > > Yes. Why do you ask? Is there some feature of the standard type's > hash functions that you dislike? tinkering with the hash function might be pretty meaningless if you don't know the dictionary implementation... quoting Tim from Objects/dictobject.c: Most hash schemes depend on having a "good" hash function, in the sense of simulating randomness. Python doesn't: its most important hash functions (for strings and ints) are very regular in common cases: >>> map(hash, (0, 1, 2, 3)) [0, 1, 2, 3] >>> map(hash, ("namea", "nameb", "namec", "named")) [-1658398457, -1658398460, -1658398459, -1658398462] >>> This isn't necessarily bad! To the contrary, in a table of size 2**i, taking the low-order i bits as the initial table index is extremely fast, and there are no collisions at all for dicts indexed by a contiguous range of ints. The same is app- roximately true when keys are "consecutive" strings. So this gives better-than-random behavior in common cases, and that's very desirable. OTOH, when collisions occur, the tendency to fill contiguous slices of the hash table makes a good collision resolution strategy crucial. /.../ see the rest of that comment for an extensive discussion of how exactly that strategy works in Python... From pinard at iro.umontreal.ca Wed Jul 31 09:05:54 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 31 Jul 2002 09:05:54 -0400 Subject: lexing nested parenthesis In-Reply-To: References: Message-ID: [Kristian Ovaska] > Perl must be hard to parse, [...] It is a common statement that no one was ever able to wrote a Perl parser recognising exactly the same language as Perl itself. At most, people can achieve good approximations. > PLY has good error reporting, too. I'm a bit ambivalent about PLY. There are undoubtedly very good ideas in there, and this is a good and useful tool. But there are a few negative sides: 1) it looks like not supported anymore, 2) it prohibits more than one grammar per module and forces a specific presentation (because it needs to read back the Python _source_ at run-time), 3) I had to fight it so it accepts a scanner of my choice, yet I do not remember the details as I write. In fact, what saddened me most is that PLY was written after SPARK and was admittedly inspired by SPARK, but failed to recognise and offer some of the most elegant aspects of SPARK. There was no (or at least, I did not see the) real advantage of dropping them. PLY was written to teach parsing, and I guess it wanted to force an overly precise setup on every student. But being outside the class, I do not really want the rigid setup on me. On the other hand, the good error reporting and the ability to generate speedy parsers for complex grammars are overwhelmingly appealing, so I am sometimes happy to use PLY, despite these few things I do not like in it. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From dig.list at telkel.net Mon Jul 29 12:46:00 2002 From: dig.list at telkel.net (Dmitri I GOULIAEV) Date: Mon, 29 Jul 2002 11:46:00 -0500 Subject: biopython, Was: (no subject) In-Reply-To: <20020729122731.6125.qmail@web10102.mail.yahoo.com>; from "biter bilen" on Mon, Jul 29, 2002 at 05:27:31AM References: <20020729122731.6125.qmail@web10102.mail.yahoo.com> Message-ID: <20020729114559.A4976@lifebook> Hi, biter bilen ! On Mon, Jul 29, 2002 at 05:27:31AM -0700, biter bilen wrote: > i will help someone about biopython. i don't have programming experience with it. but i have experience in c, c++, ml ect. i got a tutorial from web but it is for people without programming experience. i looked for a printer friendly version prepared for a little experienced ones. i couldn't find do you have any suggessions or a website recommendation? In my opinion, the best place to ask for this kind of suggestions is the BioPython at biopython.org mailing list. General information about the mailing list is at: http://biopython.org/mailman/listinfo/biopython Some of online tutorials were listed: http://www.pasteur.fr/recherche/unites/sis/formation/python/ http://mcdb.colorado.edu/courses/6440/index.html Common place to start searching for biopython's online tutorial is the biopython documentation page at: http://www.biopython.org/wiki/html/BioPython/BiopythonCode.html Regards, -- DIG (Dmitri I GOULIAEV) From dfackrell at DELETETHIS.linuxmail.org Mon Jul 15 12:24:11 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Mon, 15 Jul 2002 10:24:11 -0600 Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: <3d32f730$1_1@hpb10302.boi.hp.com> "ppcdev" wrote in message news:2fa5f3a9.0207140808.e4d7d38 at posting.google.com... > hi. i used to develop little windows application in python some years > ago. today i come back to this language because i 'd like to test the > security of some ftp servers. it's really easy to connect to a ftp > server with python (for newer newbies here it is ): > > import socket; s=socket.socket(socket.AF_INET, socket.SOCK_STREAM); > vr=s.connect(('127.0.0.1',21)); s.setblocking(0); s.send('user > user1\r\n'); > d=s.recv(1024); print d; > > i was working on an old pentium II and wanted to send a very long > string in the USER parameter but it made my computer bug.. is it > normal??? > > str='a'; r=range(1024); > for x in r[:]: > str=str+str > > but it even bugs with a value of 512 and 256 for r=range(..) > > > thanks As others have already posted, your code will create a string that is much longer than you probably want. If you are wanting 1024 copies of 'str' in a new string (yes, 'str' is a bad name to use as it eclipses the builtin type), then perhaps you want something more like: longString = 1024 * "This is a string" -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From fperez528 at yahoo.com Fri Jul 26 12:42:20 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 10:42:20 -0600 Subject: extract elements of n char from a list References: Message-ID: Alex Martelli wrote: > It's the best Python technique of all to learn to MEASURE rather > than having to ASK.??Set?up?a?little?benchmark?script?and?use?it. > THEN you can ask here if the results aren't convincing to you (it's > quite possible to get things wrong).??Tim?Peters'?introduction > to the Algorithms chapter of "Python Cookbook" (the printed edition > that O'Reilly just launched) is invaluable in showing you exactly > how to perform such little benchmarks for accuracy and solidity. I Haven't had the chance to read the Cookbook yet, so I'm sure my solutions may have holes in them. But coincidentally this morning I just finished writing a benchmarking package for my own use, and since this kind of question seems to come up often, I figured I'd post it for other's benefit. Go to http://windom.colorado.edu/~fperez/python/ and click on the benchmarking link. It's a Linux/Unix package, as it implements clocks to accurately distinguish between system and user time consumed by your process. Some examples taken from the docs: In [1]: from benchmark import timer In [2]: def loop(n): ...: for i in range(n): ...: pass ...: In [3]: timer(loop,100000) Out[3]: 0.10000000000000009 In [4]: timer.report(loop,100000) Timing report ------------- Function tested : Number of calls : 1 Total execution time: 0.1 s In [5]: timer.status() Object: Object's __dict__ : mode : user ncalls : 1 print_args : 0 print_output: 0 stream : ', mode 'w' at 0x8100a50> In [6]: timer.ncalls = 5 In [7]: timer.mode = 'all' In [8]: timer.report(loop,100000) Timing report ------------- Function tested : Number of calls : 5 Total execution time: system: 0.01 s user : 0.52 s Average time per call: system: 0.002 s user : 0.1 s Well, I hope it's useful for some. Cheers, f. From joec at mill.co.uk Mon Jul 22 10:34:42 2002 From: joec at mill.co.uk (Joe Connellan) Date: Mon, 22 Jul 2002 15:34:42 +0100 Subject: unsigned ints and operator.rshift Message-ID: <3D3C1802.948E2D99@mill.co.uk> I'm storing info in an int (32bits) that I'm wanting to shift left and right using operator.[l|r]shift the problem is that because the int is signed rshift fills in 1's rather than 0's on negative numbers - is there any way to store the 32bits as an unsigned int do get around this? thanks Joe From wangzhao_wz at hotmail.com Wed Jul 17 06:11:22 2002 From: wangzhao_wz at hotmail.com (zhao) Date: Wed, 17 Jul 2002 13:11:22 +0300 Subject: Problem with installing PyQt! Message-ID: Hi, I have installed python2.2.1 and Qt Non commercial(evaluation 3.0.4) for windows. And I try to install PyQt3.2.4 in my computer, but just got Example, Tutorial and Documentation, no executed application PyQt in it. Why? And I try to convert .ui file into python code using: pyuic example.ui -o example.py but I got example.py only about 200 bytes, and no python code inside, for example: # Form implementation generated from reading ui file 'richedit.ui' # # Created: Wed Jul 17 13:07:38 2002 # by: The Python User Interface Compiler (pyuic) # # WARNING! All changes made in this file will be lost! from qt import * Can anybody help me? Thanks. Zhao From ianb at colorstudy.com Tue Jul 30 21:48:43 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 30 Jul 2002 20:48:43 -0500 Subject: Searching for email address In-Reply-To: <3D47395B.939CD4E9@engcorp.com> References: <3D47395B.939CD4E9@engcorp.com> Message-ID: <1028080132.578.1232.camel@lothlorien.colorstudy.net> On Tue, 2002-07-30 at 20:11, Peter Hansen wrote: > Graeme Longman wrote: > > "Charl P. Botha" wrote: > > > In article , > > > Graeme Longman wrote: > > > > I'm writing some code which searches html for email addresses. Does > > > > anyone out there have a good regular expression syntax for searching for > > > > the email string, I'm sure this must've been done a few times before. > > > > > > Excuse my curiosity, but what are you going to do with this code? :) > > > > In the process of translating our client's sites. > > > > Just a script to find all the email addresses so that the email addresses > > aren't included for translation. > > Are there really going to be any addresses that don't follow the > format user at host.domain on those web pages? > > With real email (i.e. RFC822 and later ones) there are many options > including parentheses and quotation marks in addresses, but I've never > yet seen such a thing in a simple "mailto:" URL on the web. I have encountered "'" in emails, and it caused a problem when my regex flagged it as invalid (someone by the name of O'Brien, I think). It depends how robust you want your regex to be. For a quick hack to fix up some web pages, it probably doesn't matter -- especially if you know your organization doesn't use silly email addresses. Cheers, Ian From claird at starbase.neosoft.com Thu Jul 18 18:07:58 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 18 Jul 2002 17:07:58 -0500 Subject: Python robot web client? References: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> Message-ID: <60C215D19EB182D3.4B74CCBAAB7C5A11.2070483D2F315625@lp.airnews.net> In article <7x65zdtrv9.fsf_-_ at ruckus.brouhaha.com>, Paul Rubin wrote: >Are there any Python robot web clients around, sort of like Perl LWP? >I mean something fancier than urllib, that parses the HTTP headers and >remembers any cookies. It would also be great if it parsed the HTML >enough to find the form fields, links, and so forth. I guess I can >implement what I need, but thought I'd ask first if something like >it is already available. > >Thanks. Paul, you've received several useful suggestions. More than any of these others, though, I think you'll find Pycurl addresses your range of re- quirements "out of the box". to be co -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From bokr at oz.net Sat Jul 13 16:33:58 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2002 20:33:58 GMT Subject: Is count supposed to still work? References: Message-ID: On Fri, 12 Jul 2002 13:17:56 -0700, "David LeBlanc" wrote: >Whether or not you explicitly import string, > count(mystring, substring) >isn't working ("NameError: global name 'count' is not defined") (N.B. this >statement is in a method of a class), If you want the global name "count" to mean the string.count function, from string import count or import string count = string.count or (not recommended! -- perhaps you got that in previous code and got the impression count was a builtin?) from string import * # name collision risk or bind global count to the count method of str, whose usage looks the same count = str.count Or you could derive your class from str, and access count as your own method: >>> class Foo(str): ... def bar(self, substr): ... return self.count(substr) ... >>> foo = Foo('hi ho hum hip hop hello') >>> foo.bar('hi') 2 >>> foo.bar('h') 6 You could also bind str.count inside a method for local reference, e.g., >>> class Foo: ... def __init__(self, s): self.s = s ... def bar(self, ss, count=str.count): ... return count(self.s, ss) ... >>> foo = Foo('hi ho hum hip hop hello') >>> foo.bar('hi') 2 I (think I ;-) wish there were a way to declare a function variable local, global, or inbetween _explicitly_, as opposed to a global/local binary choice side effect of a first reference's being an "assignment." It could default to the current way, but then you could do something like class Foo: # make-believe example def __init__(self, s): self.s = s def bar(self, ss): set_scope('count') # (not currently implemented. Default scope 0 == local, -1 most global) return count(self.s, ss) # ref to count would _not_ assume global here bar.count=str.count # would initialize the local-to-bar count as it now does the idea being that you could refer to nested scopes by nesting level outward, or from the outermost global scope inward by negative indices, as if referring to a list of directories forming a namespace. Thus the current "global x" would functionally equal "set_scope('x', -1)". And set_scope('var_name', 1) would let you rebind in an enclosing scope (not necessarily immediately enclosing, as with level 1), and the list of nested scopes would allow systematic nested name search. set_scope might be defined with default parameters, e.g., def set_scope(name, level=0, namespace=None): ... where namespace=None would signify current lexical scope, but other specs for a level 0 starting point would be possible, e.g., self might imply [instance, class, ... builtin, global] as the nest search sequence. (For discussion only. Usual OTTOMH caveats apply ;-) >but > mystring.count(substring) >does. However, count is not listed as deprecated in the python 2.2.1 doc. >Even deprecated, it should still work. > >FWIW, I wish none of these where deprecated. Maybe it's incorrect, but I >tend to think of an attribute of something, not something's attribute. Both >ways are useful IMO. Sometimes len|count|int|float(thing) is nice and >sometimes >thing.len|count|int|float() works better. Not a different way to do >something, a different way to express the same thing. > But if built-in functions like that accumulated indefinitely, we'd have a very cluttered name space, so while I agree that some are nice, I'd rather have an efficient way to import and bind what I need than have clutter. Regards, Bengt Richter From mertz at gnosis.cx Fri Jul 26 12:54:32 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Fri, 26 Jul 2002 12:54:32 -0400 Subject: Lives of programmers References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: |"Alex Martelli" wrote: |> (BTW, I've been programming for over _25_ years now -- more than |> half of my life...). Jonathan Hogg wrote previously: |Hmmm... over 18 years, about 2/3rds of my life. Never thought of it that way |before. I don't recall ever intending to be a computer programmer... Hmmm... I guess about 24 years of programming, if you count diddling around in middle school. About 20 years of actually getting paid money to do it. So that's somewhere between 1/2 and 2/3 of my life, either way. And I have these graduate humanities degrees to *prove* that I never wanted to be a computer programmer :-). (Actually, I'm not... I'm an "applied metaphysician"). Yours, David... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From biterbilen at yahoo.com Mon Jul 29 08:27:31 2002 From: biterbilen at yahoo.com (biter bilen) Date: Mon, 29 Jul 2002 05:27:31 -0700 (PDT) Subject: (no subject) Message-ID: <20020729122731.6125.qmail@web10102.mail.yahoo.com> hi, i will help someone about biopython. i don't have programming experience with it. but i have experience in c, c++, ml ect. i got a tutorial from web but it is for people without programming experience. i looked for a printer friendly version prepared for a little experienced ones. i couldn't find do you have any suggessions or a website recommendation? biter --------------------------------- Do You Yahoo!? Yahoo! Health - Feel better, live better -------------- next part -------------- An HTML attachment was scrubbed... URL: From sneavreet+nospam at innocent.com Sun Jul 7 07:29:13 2002 From: sneavreet+nospam at innocent.com (Anders Dahlberg) Date: Sun, 7 Jul 2002 13:29:13 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> Message-ID: "Thomas Jensen" wrote in message news:3D282290.1050101 at ob_scure.dk... > Anders Dahlberg wrote: > > [snip] > > > Considering it's compiling down to java-bytecode which are then run with a > > java-vm - It should scale as well as any java solution (or atleast ~90%). > > Links could be: > > > > http://java.sun.com ;) > > http://www.bea.com/products/weblogic/jrockit/index.shtml - very good server > > vm. (optimised for intel) > > [snip] > > > disclaimer: This is just what I believe - if you want to base your case on > > this I believe you should contact other companies using java with > > multiple-cpus! > > I am quite certain that scaling (well) to multiple CPU requires one to > use threading at least. Yes, this should be quite straigthforward to implement. > Scaling to several physical machines might be > (relativly) easy with Java, but imagine it must require some coding, or? Yes, java is no magic bullet :( I *imagine* it would be "easy" due to java-rmi protocoll and maybe even a technology as javaspaces (distrubted space - "linda"?). E.G. http://www.javaworld.com/javaworld/jw-10-2000/jw-1002-jiniology-p5.html (it's not python - but should be similar to a jython implementation) > -- > Best Regards > Thomas Jensen > (remove underscore in email address to mail me) /Anders From jdhunter at nitace.bsd.uchicago.edu Fri Jul 26 16:31:32 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 26 Jul 2002 15:31:32 -0500 Subject: performance problem in python 2.2 References: Message-ID: >>>>> "Jeff" == Jeff Davis writes: Jeff> for i in range(1,c): ^ whole list in memory for i in xrange(1,c): ^ slurps off the list as necessary Should help quite a bit... John Hunter From jromero at platea.pntic.mec.es Sun Jul 14 21:27:45 2002 From: jromero at platea.pntic.mec.es (Joaquin Romero) Date: Mon, 15 Jul 2002 03:27:45 +0200 Subject: maxlenght in Entry() / Tkinter Message-ID: I can setting a maxlength (max numebers of characters) in a Entry() of Tkinter? How? Thanks From pecora at anvil.nrl.navy.mil Fri Jul 19 10:18:04 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Fri, 19 Jul 2002 10:18:04 -0400 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> Message-ID: <190720021018041866%pecora@anvil.nrl.navy.mil> Yes, I agree with all that's said below (I do almost strictly numerical stuff so I feel the pain of self. -- sheeze, that was almost Zen). But I agree with Tom Loredo that there are good general arguments for self. Many people have suggested doing something like the following (which is reasonable) to eliminate self. from mathematical expressions: t, x, y, z=self.t, self.x, self.y, self.z result=sin(t)*x**y+sqrt(z) # A pretend formula My question is how much overhead is added by the assignments in the top line? I suspect not much at all, but then I do not know how the interpreter handles these things. -- Lou Pecora In article <3D3724C0.F3286A11 at astro.cornell.edu>, Tom Loredo wrote: > Huaiyu Zhu wrote: > > > > However, there are situations, mostly in numerical computations, where it is > > necessary to have, say, a dozen variables in one expression, and a dozen > > statements containing such expressions and some other statements in one > > method. It is far more readable to have them all appear in one screen in a > > form that resembles written equations on paper, than to dogmatically follow > > a convention in a particular programming language. > > Extremely well put. > > I've been using Python almost exclusively for scientific programming in > the past 3 years or so. I've followed threads about many controversial > aspects of Python (additions or long-held characteristics), and I've > been impressed time after time with the choices of the development team. > Even when my first instinct has been to disagree with a choice or policy, > I have always come to see a great deal of wisdom in the final choice. > > But the one thing that continues to irk me about the language is "self," > for just the reasons Huaiyu describes. I think non-numerical programmers > are likely not in a position to appreciate the awkwardness of "self..." > in numerical settings, where in a many-variable expression it serves > to hinder understanding (by making the expression very long, often > broken across multiple lines) rather than to enhance it. Yet I think the > general arguments for "self" are strong and valid. Though I often wish there > were something like a "with" statement in such contexts, Huaiyu's > suggestion seems like a reasonable middle ground. > > But if there were a "with" statement, I'd probably welcome it! > > Cheers, > Tom Loredo From glyph at twistedmatrix.com Mon Jul 8 17:55:52 2002 From: glyph at twistedmatrix.com (Glyph Lefkowitz) Date: Mon, 08 Jul 2002 16:55:52 -0500 (CDT) Subject: openprojects python room is ruled by dangerous people In-Reply-To: <3D29F478.4528312C@alcyone.com> References: <3eeda89d.0207070906.1fa45916@posting.google.com> <3D29F478.4528312C@alcyone.com> Message-ID: <20020708.165552.35007597.glyph@twistedmatrix.com> On Mon, 08 Jul 2002 13:22:16 -0700, Erik Max Francis wrote: > Gerhard H?ring wrote: > > Their twisted worldview? You can safely ignore twisted, if you're not into > > network programming. At least I do and I still feel safe, despite not > > agreeing with dash and moshez on everything :-) And I don't think anybody > > gets kicked there unless (s)he's trolling repeatedly. Well, "safety" is always relative. I hope you remembered to wear your tinfoil hat! ;-) > My impression is that they are a bunch of very young, very idealistic, very > naive folks, most of which who aren't even old enough to be doing programming > professionally and so have a very limited worldview, who are very eager to > prove to the world how smart they are, usually On the contrary, I think it's a spirited discussion group with a lot of different viewpoints represented. Some of those viewpoints have rather vocal advocates :-), however, I've never seen anyone kicked for their opinion, only their attitude. > by getting into pointless quibbling arguments boiling down to, "If you don't > agree with me, you're wrong." See the previous poster's comment about "doing your homework". I have seen some people with little or no knowledge of a topic get quite apoplectic that their ideas are dismissed simply because their debate partner has heard those exact same (wrong) points at least a hundred times in the past. I sadly don't have the time to devote to both #twisted and #python any more, but I still drop by for the occasional Python-related question and to catch up with the regulars. It's a fun group, and I encourage python-list members to drop by and say hello! (Of course, don't forget to stop by #twisted as well... ^_^) The Wiki has a good advertisement which summarizes things nicely: http://twistedmatrix.com/users/jh.twistd/python/moin.cgi/PoundPythonAdvertisement Be sure to note point 2.6... > The point at which I actually saw them kick and ban someone for asking about > someone else's car is when I realized that I had been wasting my time. I > enjoyed helping newbies with their Python questions, but dealing with the > overinflated egos of these kids was like constant fingernails on a > chalkboard. Aah, I remember this incident quite well. I assure you that there was a reason for that, and the car comment was merely the straw that broke the camel's back. It's far from the average day in #python when something like that happens. I would like to respond to the ageist, patronizing tone of this message, and let the enduring and superior maturity of the poster (who was, if I recall correctly, banned under the pseudonym "xihr" for spreading exactly this kind of FUD) speak for itself: http://www.alcyone.com/xihr/ arrr-I'm-a-pirate-ly y'rs, -- | <`'> | Glyph Lefkowitz: Traveling Sorcerer | | < _/ > | Lead Developer, the Twisted project | | < ___/ > | http://www.twistedmatrix.com | -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From wyojustin at hotmail.com Thu Jul 18 01:32:54 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Thu, 18 Jul 2002 05:32:54 GMT Subject: Problem importing in a cgi script References: Message-ID: I printed out the tb info to help troubleshoot: Traceback (most recent call last): File "gnuplot_cgi.py", line 4, in ? import cgi ... ... File "/usr/local/lib/python2.2/socket.py", line 41, in ? from _socket import * Import Error: ld.so.1: /usr/local/bin/python: fatal: libgcc_s.so.1: open failed: I was able to work around the issue by changing the CGIHTTPServer.py so that it routes through the elif self.have_popen2: ... # branch bypassing the if self.have_fork: ... branch of CGIHTTPRequestHandler.run_cgi() I still would like to track down the cause. If you can shed any light I'd appreciate it. Thanks. Justin "Justin Shaw" wrote in message news:De3Z8.138349$Bt1.7336244 at bin5.nnrp.aus1.giganews.com... > After upgrading to Solaris 8 my cgi scripts are unable to import some > modules. The code runs standalone but not when called as a cgi script. I > was able to isolate the problem to these short scripts: > > #!/usr/local/bin/python > # test_cgi.py > import socket > print 'OK!' > > # cgi_server_like.py > import os > os.execve('test_cgi.py', ('',), {}) > > Too bad I don't have the actual traceback. I look like the loader can't > find _socket.so. I've done runs where I print sys.path right before the > import showing that the directory where _socket.so resides is in there. Any > ideas? > > > OS: Solaris 8 > Python version: 2.2 > > From opengeometry at NOSPAM.yahoo.ca Tue Jul 9 22:34:21 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 10 Jul 2002 02:34:21 GMT Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: Chris Gonnerman wrote: > I use chrony for time maintenance. If your computer has intermittent > Internet access (i.e. dialup) it is hands-down the best way to do it > IMHO. > > If this package has already been mentioned, sorry... I haven't followed > this thread closely. > > http://chrony.sunsite.dk/ > > Off-topic since it's C, but I love it. I've seen it, but it's a tarball which you have to download and compile. Whereas, 'netdate', 'ntpdate', and 'telnet 13' are ready to run on all Linux distribution. I have DSL connection, so I run it once a day in Crontab. If you dialup, then you can run it from '/etc/ppp/ip-up'. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From JoeSalmeri at comcast.net Wed Jul 24 12:40:21 2002 From: JoeSalmeri at comcast.net (Joe Salmeri) Date: Wed, 24 Jul 2002 16:40:21 GMT Subject: Python + Win32ALL + ASP = Problems accessing Request/Response/Session/Application objects References: <_ko%8.247434$iB1.13124073@bin4.nnrp.aus1.giganews.com> <3D3E6BCD.4010809@mxm.dk> Message-ID: Max, Thanks for the suggestion. I'm really striving to separate as much as possible HTML and code. I'm working on a framework such that the majority of my pages just have a small block at the top to import and call python modules that do the majority of the work. Also, the framework that I have developed can be used for ASP pages OR for CGI pages. Even when used in ASP mode I don't really use much of ASP as I have my own class that implements Python Server Pages which allows my framework to be independent of the Web server used. When in ASP mode, the only real benfit is that the interpreter is not loaded/unloaded each time. Other than that, all of the rest of the processing is handled via the framework. Currently I either pass in the value of globals() or the individual Request/Response/Application/Session objects when they are needed but it would be nice if I could just import the appropriate ASP components to make those objects available. I'm sure this must be possible, but I have been unable to fully trace those objects to their creation. Joe "Max M" wrote in message news:3D3E6BCD.4010809 at mxm.dk... > Joe Salmeri wrote: > > > How are the ASP Request/Response/Session/Application objects accessed in a > > module that is imported in an ASP file WITHOUT passing them in as paramaters > > to each of the functions defined in that module? I have attempted to track > > down the creation of those objects but have been unable to trace them to the > > source of their creation. > > > You would probably be better of in the long run if you used a facade to > cover your code in. > > You would then only output finished html from the facade object. > > <% > > class PageFacade: > > def __init__(self, message='blah blah'): > self.message = message > > def blah(self): > return self.message > > def update(self, req): > self.message = req.Form('message') > # 'insert message into theTable ' > > f = PageFacade() > save = Request.Form('save') > if save: > f.update(Request) > > %> > > > here is some code that reads <%= f.blah()%> > > > This has a lot of advantages. Especially if you are writing database > driven websites. > > regards Max M > From list-python at ccraig.org Mon Jul 29 00:52:06 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 29 Jul 2002 00:52:06 -0400 Subject: How to detect the last element in a for loop In-Reply-To: References: Message-ID: Tom Verbeure writes: > Given that you have an explicit iterator, wouldn't it be trivial to add an > 'end()' method to this iterator to indicate the end of the sequence (just > like C++ iterators) ? > > This would result in: > > for item in iterator: > if iterator.next().end(): > do_something_special > > do_something_for_all I do not think it means what you think it means: >>> iterator = iter([0,1,2,3]) >>> for i in iterator: ... if iterator.next(): pass ... print i 0 2 As you see, iterator.next() moves iterator to the next item, which means that even if you had a .end() method (which you don't), you couldn't use it like this. One way you could do this (another, better, way to do it is in another post, but only works if you know the length at the beginning) is to always track the next item: next = iterator.next() while next: this=next try: next=iterator.next() except StopIteration: next=False do_something_special do_something_for_all -- Christopher A. Craig "640K ought to be enough for anybody." Bill Gates From bokr at oz.net Thu Jul 18 15:38:50 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2002 19:38:50 GMT Subject: property problem References: <3D36C65A.5040300@mplusr.de> Message-ID: On Thu, 18 Jul 2002 15:44:58 +0200, Peter Maas wrote: >Hi, > >while experimenting with class properties using Python 2.2.1 >I encountered the following weird behaviour: > >This is my testclass: > >class proptest: > > def __init__(self): > self.__data = 0 > > def get_data(self): > return self.__data > > def set_data(self, value): > self.__data = value > > data = property(get_data, set_data) > > def meth(self): > return self.__data > >This is my testcode: > > >>> x = proptest() > >>> x.data=234 > >>> x.data >234 > >>> x.meth() >0 > >>> x.set_data(234) > >>> x.meth() >234 > >Explanation: > >The "data" property works but a change using the property >name doesn't show in meth(). If I use the access function set_data >it works as expected. Is it my fault or Python's? > All will be ok if you make your proptest inherit from object (thus making it a new style class). see http://www.python.org/2.2/descrintro.html#property and scroll down a bit for an explanation of what you're seeing above, starting with "Things to notice about property() (all advanced material except the first one): Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its __dict__ without calling the property's set method, and after that, the property's get method won't be called either. (You could override __setattr__ to fix this, but it would be prohibitively expensive.) ..." There's also other interesting stuff to read about in descrintro.html ;-) Regards, Bengt Richter From b.hall at irl.cri.nz Wed Jul 31 17:34:30 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Thu, 01 Aug 2002 09:34:30 +1200 Subject: A generic question: idiom for a paramterized base class? References: <918bc22f.0207311105.50a33dba@posting.google.com> Message-ID: <3D4857E6.2CB4F9B3@irl.cri.nz> Thanks Donnal, Your idea seems to provide me with the following solution. I have split your code into two modules and added a class: ############### DonnalBase.py class AbstractBase(object): def __iadd__(self,other): return self.TAdd(self,other) def __add__(self,r): return AbstractBase.__iadd__(self,r) def __radd__(self,l): return AbstractBase.__iadd__(l,self) class TAdd(object): pass and ####### Donnal.py from DonnalBase import AbstractBase class MyClass1(object,AbstractBase): # One type of TAdd: class TAdd(AbstractBase): def __init__(self,l,r): print "TAdd instance 1" class TNode(object,MyClass1): def __init__(self): print "TNode instance" ####################### You see that I need 'MyClass' to act as a base for a number of classes (like TNode). This seems to work: >>> x = Donnal.TNode() TNode instance >>> y = Donnal.TNode() TNode instance >>> t = x + y TAdd instance 1 Thanks Blair Donnal Walter wrote: > ...snip... > Does this do what you want? > > ################################################## > class AbstractBase(object): > def __iadd__(self,other): > return self.TAdd(self,other) > def __add__(self,r): > return AbstractBase.__iadd__(self,r) > def __radd__(self,l): > return AbstractBase.__iadd__(l,self) > class TAdd(object): pass > > class MyClass1(AbstractBase): > > # One type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 1" > > class MyClass2(AbstractBase): > > # Another type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 2" > ################################################## > > >>> x = MyClass1() > >>> y = MyClass2() > >>> t = x + y > TAdd instance 1 > >>> u = y + x > TAdd instance 2 > > Donnal Walter > Arkansas Children's Hospital From pecora at anvil.nrl.navy.mil Tue Jul 9 08:20:25 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 08:20:25 -0400 Subject: Why self? References: Message-ID: <090720020820257031%pecora@anvil.nrl.navy.mil> In article , Brian Quinlan wrote: > This would be ugly and slow. The slowness would come from the fact that > locally scoped variables could not be identified during compilation. > Ugly is in the eye of the beholder. I think it's cleaner (a design goal of Python as I recall). Slow is something I cannot comment on. I have no parsing experience so I wasn't aware that the "solution" of "declaring" object variables in __init__ and then using them elsewhere would have lots of overhead. That would be bad if it were so. From Hobbes2176 at yahoo.com Tue Jul 23 23:19:14 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Wed, 24 Jul 2002 03:19:14 GMT Subject: Make me beautiful (code needs help) References: Message-ID: In particular, should I look at the "Numarray" that is supposed to replace "Numeric". Regards, Mark From gmfawcett at operamail.com Wed Jul 10 06:16:49 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 10 Jul 2002 03:16:49 -0700 Subject: Pyrex and Distuils: an enhanced build_ext command References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> Message-ID: <3d799735.0207100216.4eb8a9cd@posting.google.com> I wrote: > I suppose that one could add a distutils.command.pyrexc as a > subcommand of "build_ext" to handle the .pyx compilation. That way the > os.system() call in the build script could be avoided. I've never > written a distutils command, but perhaps I'll give that a try. Okay, I wrote the distutils command. Actually I just added a subpackage to Pyrex that you can import into your setup script: from distutils.core import setup from distutils.extension import Extension import Pyrex.Distutils setup(name='foo', ext_modules=[Extension("foo", ["foo.pyx"])]) Note that the Extension() specifies a .pyx file, not a .c file. You can specify .c files as well, but of course Pyrex will ignore them. Pyrex.Distuils (my subpackage) is a build_ext replacement -- it import-hacks itself into the distutils.command package, so that it gets a first shot at any build_ext calls. Once it's finished, it returns control to the "real" build_ext. I tested on Win32 only, with mingw32 and msvc compilers, but it should run fine on other platforms. I've put a modified distribution of Pyrex 0.3.3 at http://cfl-x.uwindsor.ca/graham/pyrex/ if anyone wants to try it out. Here are the two key source files: ########################################### # Pyrex.Distutils.__init__.py # July 2002, Graham Fawcett # # this hack was inspired by the way Thomas Heller got py2exe # to appear as a distutil command # # we replace distutils.command.build_ext with our own version # and keep the old one under the module name _build_ext, # so that *our* build_ext can make use of it. import sys import distutils.command.build_ext sys.modules['_build_ext'] = distutils.command.build_ext import build_ext sys.modules['distutils.command.build_ext']=build_ext ########################################### # Pyrex.Distutils.build_ext.py """ Subclasses disutils.command.build_ext, replacing it with a Pyrex version that compiles pyx->c before calling the original build_ext command. """ # July 2002, Graham Fawcett # Pyrex is (c) Greg Ewing. import Pyrex.Compiler.Main from Pyrex.Compiler.Errors import PyrexError from distutils.dep_util import newer import os import sys # in Distutils.__init__, the original build_ext # is inserted into sys.modules as _build_ext import _build_ext class build_ext (_build_ext.build_ext): description = "compile Pyrex scripts, then build C/C++ extensions (compile/link to build directory)" def run (self): if not self.extensions: return # collect the names of the source (.pyx) files pyx_sources = [] for e in self.extensions: pyx_sources.extend(e.sources) pyx_sources = [source for source in pyx_sources if source.endswith('.pyx')] for pyx in pyx_sources: # should I raise an exception if it doesn't exist? if os.path.exists(pyx): source = pyx target = source.replace('.pyx', '.c') if newer(source, target) or self.force: self.pyrex_compile(source) # compiling with mingw32 gets an "initializer not a constant" error # http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp # doesn't appear to happen with MSVC # so if we are compiling with mingw32, massage the Pyrex-generated # C files to compile properly if self.compiler=='mingw32': self.fix_c_file(target) # correct the extension sourcefile names in setup script # so that .pyx files are refered to as .c files # then we can call the "real" build_ext on them. for e in self.extensions: e.sources = [src.replace('.pyx', '.c') for src in e.sources] # run the original build_ext. _build_ext.build_ext.run(self) def pyrex_compile(self, source): try: Pyrex.Compiler.Main.compile(source, c_only=1, use_listing_file=0) except PyrexError, e: print e sys.exit(1) def fix_c_file(self, filename): print 'fixing ' + filename HEAD_INIT = 'PyObject_HEAD_INIT(0)' TYPESTART = 'statichere PyTypeObject __pyx_type_' GETATTR = 'PyObject_GenericGetAttr, /*tp_getattro*/' SETATTR = 'PyObject_GenericSetAttr, /*tp_setattro*/' ALLOC = 'PyType_GenericAlloc, /*tp_alloc*/' FREE = '_PyObject_Del, /*tp_free*/' TYPEINIT ='''__pyx_type_%(typename)s.ob_type = &PyType_Type; __pyx_type_%(typename)s.tp_getattro = PyObject_GenericGetAttr; /*tp_getattro*/ __pyx_type_%(typename)s.tp_setattro = PyObject_GenericSetAttr; /*tp_setattro*/ __pyx_type_%(typename)s.tp_alloc = PyType_GenericAlloc; /*tp_alloc*/ __pyx_type_%(typename)s.tp_free = _PyObject_Del; /*tp_free*/ ''' f = open(filename, 'r') lines = f.readlines() f.close() lines = [line.rstrip() for line in lines] types = [] f = open(filename, 'w') for line in lines: if line.startswith(HEAD_INIT): print >> f, 'PyObject_HEAD_INIT(NULL)' elif line.startswith(TYPESTART): typename = line[len(TYPESTART):].split(' ')[0] types.append(typename) print >> f, line elif line.startswith(GETATTR): print >> f, 'NULL,' + GETATTR.split(',')[1] elif line.startswith(SETATTR): print >> f, 'NULL,' + SETATTR.split(',')[1] elif line.startswith(ALLOC): print >> f, 'NULL,' + ALLOC.split(',')[1] elif line.startswith(FREE): print >> f, 'NULL,' + FREE.split(',')[1] elif line.startswith('void init') and line.endswith('(void) {'): print >> f, line for typename in types: print >> f, TYPEINIT % locals() else: pass print >> f, line f.close() ########################################### This was fun to do! I hope that it will be useful to others. Having read through the Distutils source, I have a new and profound respect for its authors. Regards, -- Graham From jepler at unpythonic.net Fri Jul 26 14:25:59 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 26 Jul 2002 13:25:59 -0500 Subject: Mastering Regular Expressions 2nd Ed. In-Reply-To: References: Message-ID: <20020726182558.GC1452@unpythonic.net> Michael Hudson writes: > > Somewhere you can find a (perl) regexp that matches prime but not > > composite numbers, > Michael Hudson continues: > I found it here: > > http://montreal.pm.org/tech/neil_kandalgaonkar.shtml [...] > (you can see I got the above description slightly wrong) > > and think it's sufficiently clever to post a link to. > > Here's it at work in Python: > > >>> def isprime(num, prog=re.compile(r"^1?$|^(11+?)\1+$")): > ... return prog.match('1'*num) is None You can use the zero-length negative lookahead assertion (?!...) to make the RE match on primes (and not match on composites), of course. The expression becomes r"^(?!1?$|^(11+?)\1+$)" This is clearly cooler than the RE that matches multiples of 3 written in binary... I'm not sure this is it, but I think it may be. (0|1(01*0)*1)+ of course, this RE is actually a good old-fashioned RE, so it still has some allure. Jeff From fredrik at pythonware.com Tue Jul 2 18:09:29 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Jul 2002 22:09:29 GMT Subject: Maximum size of list? References: Message-ID: "gollem" wrote: > What is the maximum listsize in python? In characters > or items. Thnx. 2147483647 items, on most platforms. if you have enough memory, that is. From jdhunter at nitace.bsd.uchicago.edu Tue Jul 9 15:43:43 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 09 Jul 2002 14:43:43 -0500 Subject: File size error in os.stat with large files. References: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: >>>>> "Joe" == Joe Woodward writes: Joe> I have a 4.2GB file that os.stat is reporting to be Joe> 164MB. Smaller files seem to work just fine, but I have not Joe> played with it to find out where the cut-off point is. You have to compile python with large file support to handle files over 2GB. To test whether you have this enabled: >>> fd = open('somefile.dat', 'rw') >>> fd.tell() 0L If it returns '0', LFS is not enabled. if it returns '0L', LFS is enabled. If not, you'll need to rebuild python for LFS (or try and find a precompiled binary). I've done the build for linux and not widows, so you'll need to adapt them to your environment/compiler. On linux, to compile python with LFS, unpack the source distribution and run ./configure. Then edit the Makefile and set the OPTs to be: OPT= -ggdb -O2 -Wall -Wstrict-prototypes -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 and 'make install'. Try the 'tell' test again and you should get '0L'. Good luck, John Hunter From pinard at iro.umontreal.ca Sun Jul 7 09:05:33 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 07 Jul 2002 09:05:33 -0400 Subject: procmail replacement in Python In-Reply-To: References: <3u8pea.617.ln@127.0.0.1> Message-ID: [Fran?ois Pinard] > Here is a copy of my copy: Oops, sorry! I should not have Cc:ed python-list with the full archive. On the other hand, as it is rather small, I think I will nevertheless sleep tonight :-). In a word, I apologise, and will try paying more attention in the future. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From maxm at mxm.dk Wed Jul 3 09:40:55 2002 From: maxm at mxm.dk (Max M) Date: Wed, 03 Jul 2002 15:40:55 +0200 Subject: baffling bug in this bit of code! References: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> Message-ID: <3D22FEE7.5000106@mxm.dk> Daniel Jaeggi wrote: > # find maximum dimension > max_x = 0 > max_y = 0 > for node in self.nodes.keys(): > # first x > x = self.nodes[node].location.x > print "for node",node,"x is",x > print "max_x = ",max_x > if (x > max_x): > print "updating max_x" > max_x = x > # then y > y = self.nodes[node].location.y > print "for node",node,"y is",y > print "max_y = ",y Also here above you probably mean:: print "max_y = ",max_y > if (y > max_y): > print "updating max_y" > max_y = y > # and print this out for now > print "Max x dim is",max_x > print "Max y dim is",max_y regards Max M From kendall at monkeyfist.com Thu Jul 11 14:04:27 2002 From: kendall at monkeyfist.com (Kendall Clark) Date: Thu, 11 Jul 2002 13:04:27 -0500 Subject: Good SOAP lib for Python 2.2 In-Reply-To: <20020711102322.A7603@monkeyfist.com>; from kendall@monkeyfist.com on Thu, Jul 11, 2002 at 10:23:22AM -0500 References: <3D2D9B2C.3030606@NOSPAMREMOVETHISxs4all.nl> <20020711102322.A7603@monkeyfist.com> Message-ID: <20020711130427.A8718@monkeyfist.com> On Thu, Jul 11, 2002 at 10:23:22AM -0500, Kendall Clark wrote: > See, for example, > > Generating SOAP > http://admin.xml.com/pub/a/2002/06/12/soap.html > > Examining WSDL > http://admin.xml.com/pub/a/2002/05/15/ends.html Oops! Sorry, here are the correct URLs: Generating SOAP http://www.xml.com/pub/a/2002/06/12/soap.html Examining WSDL http://www.xml.com/pub/a/2002/05/15/ends.html Kendall Clark From daniel.hughes at usa.net Tue Jul 23 13:57:22 2002 From: daniel.hughes at usa.net (Dan) Date: 23 Jul 2002 10:57:22 -0700 Subject: pythoncom from jython References: <46585325.0207080040.1ac2fffd@posting.google.com> <46585325.0207090228.7b5fc9e2@posting.google.com> Message-ID: <155dc67d.0207230957.69ff0ed8@posting.google.com> Check out "Jacob" Java/COM Bridge. It's free. http://danadler.com/jacob/ From vchen at meetingmaker.com Fri Jul 12 10:39:13 2002 From: vchen at meetingmaker.com (Victor Chen) Date: Fri, 12 Jul 2002 10:39:13 -0400 Subject: automating command line program Message-ID: <002401c229b1$e45aa090$e503010a@int.meetingmaker.com> Hi, I'm fairly new to python and I've been trying to automate the usage of a command line prompt program and I'm able to successfully run the application from command line but once the program has launched, I'm unable to enter anymore commands into the program. I've basically just tried using os.system, os.popen, and print statements. Is there other python commands that will allow me to do this? I've looked around the web and I've found a module, Expect, that may be able to help me but I'm unable to find a windows version of this module for python. Any help is appreciated, thank you. Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From LogiplexSoftware at earthlink.net Fri Jul 26 13:47:55 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 26 Jul 2002 10:47:55 -0700 Subject: it's very raw today, I'll kick monthly or Anne will expect the counters In-Reply-To: <24ECE483.DAEC85F4@hepsinen.edu.co> References: <24ECE483.DAEC85F4@hepsinen.edu.co> Message-ID: <1027705675.1296.36.camel@software1.logiplex.internal> On Wed, 2002-07-24 at 14:33, Murad Abbas Al Haji wrote: [snip] > All papers will be dull healthy elbows. I am frantically weak, so I > scold you. Why will we join after Osama explains the new corner's > fork? Charlene fears the dust within hers and rigidly recollects. [snip] Ah. Another autocoding proponent. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From opengeometry at NOSPAM.yahoo.ca Sun Jul 7 19:20:16 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 7 Jul 2002 23:20:16 GMT Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I found Simon Foster's nice little SNTP client on the ASPN Cookbook > site and adapted it to set the hardware clock under Linux: > > http://www.nightsong.com/phr/python/setclock.py > > I find it pretty useful for adjusting my computer clock every > now and then, without the hassle of setting up a real NTP system. Thanks for the pointer, Paul. Exactly what I needed. Do you know any pure shell script that does the same thing? I don't have Python installed on every machine. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From just at xs4all.nl Wed Jul 24 09:49:16 2002 From: just at xs4all.nl (Just) Date: Wed, 24 Jul 2002 15:49:16 +0200 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> Message-ID: In article <3D3EADD1.4020400 at ntlworld.nospam.com>, "Keith S." wrote: > Alex Martelli wrote: > > > QLineEdit handles (and returns) a single line, right? Therefore, how > > can you use it to input a multi-line command? > > True, although you can do this in the Python interactive > shell, so I presume there *is* a way of doing it. > > > Why not use a multiline editing widget instead? > > Because I'd really like it to work just like the interactive > shell if possible... Have a look at code.py in the std library. Just From mdehoon at ims.u-tokyo.ac.jp Tue Jul 23 00:11:39 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Tue, 23 Jul 2002 13:11:39 +0900 Subject: distutils cygwin bdist_wininst Message-ID: <3D3CD77B.1040102@ims.u-tokyo.ac.jp> I am trying to create a windows installer for my extension module using distutils. Before, I have created the setup.py, and this works beautifully on cygwin. I would like to be able to distribute my extension as a Windows installer, so that users don't have to mess around with compilers they might not even have. If I try to make a windows installer on cygwin with python setup.py bdist_wininst I get the following error message: .... distutils.errors.DistutilsPlatformError: distribution contains extensions and/or C libraries; must be compiled on a Windows 32 platform If I try to run the same command with Python under Windows instead of Python on cygwin, then distutils tries to use the cl.exe compiler, which I don't have. Is it possible to create a Windows installer with distutils using the Cygwin/mingw gcc compiler? Thanks in advance. Michiel de Hoon University of Tokyo, Human Genome Center From raimo-news at mail.com Wed Jul 31 08:47:13 2002 From: raimo-news at mail.com (Raimo Tuisku) Date: Wed, 31 Jul 2002 15:47:13 +0300 Subject: small tkinter problem References: Message-ID: On Wed, 31 Jul 2002 15:51:26 +0300, oberon wrote: > File "D:\projects\oberon\mdbapp.py", line 21, in __init__ > self.results = Listbox(frame, > yscrollcommand=self.rescroll.set).grid(row=4,column=0,sticky=W+E,columnspan=2) > AttributeError: 'NoneType' object has no attribute 'set' The error message says it all: > self.rescroll = Scrollbar(frame).grid(row=4,column=2) You set the return value of grid to self.rescroll which is none. -- Raimo Tuisku From cliechti at gmx.net Wed Jul 31 14:51:59 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 20:51:59 +0200 Subject: a soft real-time system using pythonm References: <200207311359.JAA15020@test-area.com> <20020731145848.GC1800@unpythonic.net> Message-ID: anton wilson wrote in news:mailman.1028133225.32205.python-list at python.org: > O >> A realtime system places an upper bound on all operations, but the >> very nature of Python makes this impractical if not impossible. >> >> An interaction between Python's handling of the GIL and the >> platform's pthread library is going to be the least of your problems >> if you actually intend to deliver a system which gives realtime >> guarantees on Python programs. >> >> Jeff > > > If the soft-real-time system we use makes simple function calls and > only uses simple datatypes and possibly tuples, what are some of the > potential pitfalls we could run into? depends on your timing caonstaints. you're speaking of seconds or milliseconds? i don't see a problem if you're talking about seconds or half seconds. > I understand the deallocation > issue and the garbage collection issue. (Does garbage collection have > to be enabled?) garbage collecting in python is only useful when you have data in cycles (self made linked lists etc.) you can avoid that and turn off the gc (it probably won't disturb anyway) > Can we somehow get an idea on the worse case time > delays in python using only simple function calls and assignments with > small tuples and simple datatypes? python is a bit slower than say a C program, so your latency times are likely to be higher due to the slower execution time. but apart from that its more a problem of the OS. as you have seen in the original thread, the threading implementation of the OS can vary. however, i'm using python in soft-realtime applications. one delivers data over the serial port every 250ms and the PC should answer back within 80ms. this works realy great and i'm even running a wxPython GUI in the same process. it runs on win98, NT, 2k, linux. i never had problems with 200MHz pentiums and 64MB RAM. (on an embedded linux board 16MB RAM PPC at 50MHz running only a console version of the same programm is possible, but on the edge) chris -- Chris From aleax at aleax.it Wed Jul 24 11:23:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 15:23:09 GMT Subject: xml processing : too slow... References: Message-ID: Shagshag13 wrote: > hello, > > i need to process *each line* of many huge files (> 2 million lines) with > xml processing, by now i do it with parseString from xml.dom.minidom and > it's work. *shudder* don't use minidom except on SMALL files!!! > i do xml validation, extract attributes and tags. minidom is not validating anyway. You probably just check for well-formedness (validation means adherence to a DTD etc). > that's really slow, how do you think i can speed it up ? i'm thinking of > writing a xml mini wrapper using things like string.find or even regular > expressions, do you this that's a good idea ? No, it's a wretched idea. Use xml.sax or xml.dom.pulldom, the tools meant to be used with large XML files. minidom has to build up in-memory structures, typically several times larger than the input XML file, so your virtual memory is probably thrashing badly -- eep. Actually I hadn't used xml.dom.minidom in AGES (had to refresh my dim memories to write the XML chapter for the Nutshell) -- SAX is just TOO much better for typical XML-parsing tasks in my opinion. Clearly not everybody agrees, or Paul Prescod, a great XML as well as Python expert, wouldn't have developed xml.dom.pulldom, but then I guess variety is the spice of life. I'm very used to thinking in event-driven terms (the only way to go for GUI's, the fastest for networks, the one supported by SGMLParser and HTMLParser too) so SAX feels as comfortable as a pair of Mephisto shoes to me (I'd wear no other brand under any condition I can imagine -- I don't want my feet to hate me, after all). Just one performance tip: if you need to buffer incoming characters, and you typically do since the parser can split them, DON'T use a string attribute doing something like self.data += moredata -- that's a performance disaster too. Use a LIST attribute, do self.data.append(moredata), and ''.join(self.data) if you need the data in string form when you know you have collected all you need for now. Alex From b.hall at irl.cri.nz Wed Jul 31 20:30:03 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Thu, 01 Aug 2002 12:30:03 +1200 Subject: A generic question: idiom for a paramterized base class? References: <918bc22f.0207311105.50a33dba@posting.google.com> Message-ID: <3D48810A.824332A7@irl.cri.nz> Thanks Donnal, Your idea seems to provide me with the following solution. I have split your code into two modules and added a class: ############### DonnalBase.py class AbstractBase(object): def __iadd__(self,other): return self.TAdd(self,other) def __add__(self,r): return AbstractBase.__iadd__(self,r) def __radd__(self,l): return AbstractBase.__iadd__(l,self) class TAdd(object): pass and ####### Donnal.py from DonnalBase import AbstractBase class MyClass1(object,AbstractBase): # One type of TAdd: class TAdd(AbstractBase): def __init__(self,l,r): print "TAdd instance 1" class TNode(object,MyClass1): def __init__(self): print "TNode instance" ####################### You see that I need 'MyClass' to act as a base for a number of classes (like TNode). This seems to work: >>> x = Donnal.TNode() TNode instance >>> y = Donnal.TNode() TNode instance >>> t = x + y TAdd instance 1 Thanks Blair Donnal Walter wrote: > ...snip... > Does this do what you want? > > ################################################## > class AbstractBase(object): > def __iadd__(self,other): > return self.TAdd(self,other) > def __add__(self,r): > return AbstractBase.__iadd__(self,r) > def __radd__(self,l): > return AbstractBase.__iadd__(l,self) > class TAdd(object): pass > > class MyClass1(AbstractBase): > > # One type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 1" > > class MyClass2(AbstractBase): > > # Another type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 2" > ################################################## > > >>> x = MyClass1() > >>> y = MyClass2() > >>> t = x + y > TAdd instance 1 > >>> u = y + x > TAdd instance 2 > > Donnal Walter > Arkansas Children's Hospital From brueckd at tbye.com Wed Jul 17 12:50:44 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 17 Jul 2002 09:50:44 -0700 (PDT) Subject: netCDF in 2.2 In-Reply-To: <57fe7929.0207170732.1a2deeba@posting.google.com> Message-ID: On 17 Jul 2002, Brian wrote: > wadebk at nswc.navy.mil (Brian) wrote in message news:<57fe7929.0207120253.37865e70 at posting.google.com>... > > I'm a relative newbie in Python and I can't get netCDF to work under > > 2.2 on Windows. I found a .pyd file that makes it work under 2.1 > > (scientific_netcdf.pyd), but it doesn't work under 2.2. Does anyone > > have the equivalent version of this file or another easy solution? > > I can't believe that nobody else has run into this before. Please, if > someone knows how to do this tell me. Have you tried the netCDF mailing list? netCDF isn't exactly ubiquitous, so it shouldn't be too surprising that the intersection of c.l.py readers and netCDF users is close to zero. ;-) Where did you get the .pyd that works with 2.1? Maybe whoever built it has or will build you one for 2.2. Or do they at least make available the source code (so that you or some kind soul could build you a new .pyd)? Give us some more details and then maybe we can be of more help. Have fun, Dave From jepler at unpythonic.net Sun Jul 14 21:53:48 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 14 Jul 2002 20:53:48 -0500 Subject: Q: Why does this work??? In-Reply-To: References: Message-ID: <20020714205343.A4698@unpythonic.net> You need only declare a variable "global" when you assign to it in a function scope. Example: def f(): print x The compiler can see that x is not assigned a value inside f, so for 'print x' to be meaningful, it must refer to the global x. def g(): x = 3 print x The compiler can see that x is assigned a value inside g, so it makes x a local variable. def h(): global x x = 3 print x Here, the 'global' statement makes x refer to a global name, even though there is an assignment seen in the function's body. The key here is that x[0] = 3 is not an assignment to x. This is the same as x.__setitem__(0, 3) and mutates (changes) the thing that x names, it does not make x name a new thing. Jeff From tim.one at comcast.net Mon Jul 15 21:38:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 15 Jul 2002 21:38:12 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty In-Reply-To: <61957B071FF421419E567A28A45C7FE514A5C3@MAILBOX.nameconnector.com> Message-ID: [Geoffrey Talvola] > ... suppose that I actually did want the behavior I described above > -- a reliable "if the queue is empty, raise the Empty exception, > otherwise remove and return an item from the queue". If you're also not willing to block, you can't. You could start by trying if the_queue_looks_empty_right_now: raise Empty else: ??? If it takes the "if" branch, the queue may well become non-empty by the time the calling thread sees the exception. OTOH, if it takes the "else" branch, what are you going to do? There's no guarantee that the queue is *still* non-empty by the time you get to the "???" part. You have to grab a lock to say anything for sure, and as soon you try to grab a lock the possibility for blocking comes with it. > How would I write it? Do I need to busy-loop like > this (untested): > > def get_nowait_reliable(self): > while 1: > try: > return self.get_nowait() > except Empty: > # Let's see if it's really empty. If not, > try again. > if self.empty(): > raise > > or is there a better way? Sorry, that it isn't even *a* way. One problem is that it can block forever (unlikely, but possible, for another thread to put something on the queue every time you get to the "if self.empty()", but take it away again every time before you get back to the self.get_nowait()" -- then you spin in an infinite loop). The other problem is that it's quite possible that self.get_nowait() raises Empty, and self.empty() returns True, and that 100 other threads then put things back on the queue between then and the time your thread gets around to doing the "raise". So it's got the same problem you're trying to solve, but worse in that it can block for an arbitrarily long time. The inherent problem is that "empty" makes no sense except with respect to a specific observer at a specific time. Locks let you freeze the state so that the lock-holding observer can know the state for certain while it holds the lock, but getting the lock can block, and without a lock you can't know the state for certain -- you can only know what the state was the last time you looked at it, and "in theory", without *some* sort of hard synch gimmick an unbounded amount of time can pass between when you gather the info and when you're able to act on it. So long as you're working outside a synched area, all you can know is what some state was in the past. From StRanGy at dijana.vest.hr Thu Jul 11 05:26:03 2002 From: StRanGy at dijana.vest.hr (Ivica) Date: 11 Jul 2002 09:26:03 GMT Subject: PyGPG Message-ID: I'm looking for PyGPG wrapper around gpgme ... the URL i found does not work any more. Can any one tell me where to find them. Tnx! From daniel.dittmar at sap.com Fri Jul 12 04:31:12 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 12 Jul 2002 10:31:12 +0200 Subject: Python for data driven website? References: Message-ID: Micah Mayo wrote: > my questions. What can python offer as far as the web goes? How well > does it function and/or integrate with mySql and apache? How does it > compare with php as pertains to the web and dealing with mySql? I'm see http://www.python.org/cgi-bin/moinmoin/WebProgramming for an overview. Daniel From mdehoon at ims.u-tokyo.ac.jp Sun Jul 28 01:46:46 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Sun, 28 Jul 2002 14:46:46 +0900 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> <3D4263E7.3000107@ims.u-tokyo.ac.jp> <3D42D972.2060607@ims.u-tokyo.ac.jp> Message-ID: <3D438546.6010403@ims.u-tokyo.ac.jp> Well my real problem is how to get distutils to use gcc on unix systems. As far as I know, I can only use --compiler='unix' on unix systems, and for some reason my distutils ignores the environment variable CC. So I always end up with the cc compiler, even if I set CC=gcc. Chris Liechti wrote: > Michiel Jan Laurens de Hoon wrote in > news:3D42D972.2060607 at ims.u-tokyo.ac.jp: > > >>Sorry ... it seems that distutils ignores the CC environment variable >>(see below). This was done on cygwin. >> > > there is a note somewhere in the docs that you can use --compiler=mingw32 > (which works with gcc/cygwin) the doc also says how to use the borland > compiler. > i always have trouble to find the respecive note, but i _know_ it's > somewhere in the docs that get installed with python. :-( > > >>On Unix, the CC variable was >>also ignored using setenv CC gcc, and also with set CC=gcc. Here >>distutils defaulted to the standard cc compiler. I am guessing that it >>took the compiler name from the Makefile in /lib/python2.2/config. >>Any ideas? >>Thanks a lot for your help. >> >>--Michiel. From spinwing at inwind.it Wed Jul 24 08:44:00 2002 From: spinwing at inwind.it (Stefano Vedovelli) Date: Wed, 24 Jul 2002 12:44:00 GMT Subject: GUI toolkits References: <3d3e8e2e_4@news.newsgroups.com> <6BD35F86024903BE.21C9C2AF4CD75C43.49FE3231C518DCC1@lp.airnews.net> Message-ID: Hello all well, thanks for the feedbacks. In general I am more confident with PyQT, as there is good documentation available, as I can also read the C/C++ documents, for instance "Programming With Qt" from O'Reilly, which I bought. The question was more oriented to understand how people more experienced with me in GUI programming in Python had the perception of the various libraries, and I think I got the point. Thanks to everybody. Regards Stefano From fredrik at pythonware.com Mon Jul 1 11:27:42 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 15:27:42 GMT Subject: Most efficient way to write data out to a text file? References: <3d1a6993.248534625@netnews.attbi.com> <3d1dc547.468619140@netnews.attbi.com> Message-ID: Bengt Richter wrote: > >yes. Python assigns integer indices to local names, and > >stores the corresponding objects in an array. > > Is this done for built-in keywords also? assuming you meant "built-in functions", no. > ISTM a standard list of indices could be defined for a particular > Python version, and code generated to take advantage. the following PEPs discuss various ways to improve access to globals (not just builtins): http://www.python.org/peps/pep-0266.html (skip) http://www.python.org/peps/pep-0267.html (jeremy) http://www.python.org/peps/pep-0280.html (guido) from what I can tell, jeremy's proposal is pretty much a generalized version of your idea. From aleax at aleax.it Tue Jul 16 11:53:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 16 Jul 2002 15:53:43 GMT Subject: map del efficiency python2.2 and 2.1 References: Message-ID: John Hunter wrote: ... > def pairs(l): > return [(l[i], l[i+1]) for i in range(0, len(l), 2)] In 2.2, with "from __future__ import generators" at the start of your module, you can probably use this almost as fast as the other, less-elegant solution, by recoding it as a generator: def pairs(L): for i in xrange(0, len(L), 2): yield L[i], L[i+1] but that's a minor issue, I guess. Another likely performance boost in 2.2 would be: m = dict(pairs(seq)) with pairs coded as here shown. Regarding del time, you could measure that directly by doing a "del m" and seeing times before and after; also, just in case (shouldn't matter, but...), you could try gc.disable() and see if that makes a difference. Alex From altis at semi-retired.com Fri Jul 12 23:12:53 2002 From: altis at semi-retired.com (Kevin Altis) Date: Fri, 12 Jul 2002 20:12:53 -0700 Subject: pyCard_turtleTimes References: Message-ID: First of all, I'll make the assumption that the original poster is using release 0.6.7 or what is in cvs, so there aren't any "old code" issues. My apologies about the comments embedded in some of the scripts about drawing times. Those comments are mostly over a year old prior to the turtle sample being changed to use an offscreen bitmap for drawing, thus preserving the bits drawn as the screen is refreshed, windows overlapped, etc. That double-buffering becomes expensive during drawing because the present code is forced to blit the entire bitmap to be safe. The problem is that if auto refresh is enabled the entire bitmap is blitted on screen after each turtle call which results in the worst possible performance when drawing a pixel at a time. Depending in changes to the underlying wxWindows wxDC class, the turtle class may get improved to get around this issue, but for now it is better suited for interactive drawing from the shell or by turning off auto refresh. The later releases of PythonCard changed the drawing to support drawing without refreshes on the turtle sample, so if Auto refresh is unchecked under the Commands menu you should dramatically faster times. How dramatic? Well I just ran Hopalong using the default 100,000 points of the hopalong.txt script and got a time of 185 seconds, but if Auto Refresh is unchecked the draw time drops to 5 seconds. Mostly, I haven't bothered to go back and play with this because nobody has ever expressed any interest in the turtle sample, thus there seemed to be little reason to go spend time on it when I could be doing other things in PythonCard that people are asking for. Blitting the entire bitmap on screen is really expensive. That is why plotting should really be done without using a turtle as the hopalong sample shows. The turtle sample predates the hopalong sample which uses a different algorithm for plotting and updating the screen. On the same machine, drawing 100,000 points with refreshes occurring as the color plotted changes, only takes 1.5 seconds. So, 1.5 seconds instead of 185 seconds, which way do you want to draw points? :) All draw times should mostly be limited by the video card, but if your box is low on memory that could have a major negative impact. I have a little evidence that the exact same CPU, memory, and video card is faster on Windows 2K/XP than Linux, which might be due to the quality of nVidia drivers on Windows or might have something to do with GTK; I would like to see more tests in this area. I don't use Linux, so this is based on seeing drawing on other users boxes. I do know that the Mac OS X Quartz engine is dramatically slower with this wxPython/PythonCard drawing stuff, apparently blits are super expensive with the current Quartz engine as of 10.1, so none of the turtle drawing is usable without turning off Auto Refresh and the hopalong sample is pretty darn slow. It might be that all windows are already buffered on OS X and that double-buffering is a waste with Quartz, but I don't know of anyone that has dug into wxWindows wxDC behavior on OS X deep enough to find out. I just know on my OS X box, the drawing is slow. ka "Neil Hodgson" wrote in message news:Q5KX8.434157$o66.1173345 at news-server.bigpond.net.au... > Cousin Stanley: > > > I'd be interested to know how other machines/platforms compare > > for the ones that take the longest here ... > > ChaosScript2and3 ..... 157 > hopalong ...................... 554 > madness ...................... 482 > > Its not a simple multiplier on your results, possibly due to different > CPU:Video performance ratios on the two machines. I see a lot of variation > in times with subsequent runs of ChaosScript2and3 taking 117 and 184 > seconds. > > Cheap locally assembled box > Processor ... AMD Athlon 600 > Memory ...... 384 MB > Video ........... NVIDIA RIVA TNT2 64 > > Software > > Window 2000 > Python 2.2 > > Mmm, performance of these applications is so central to my efficiency > that I must buy a better machine ;-) > > Neil > > > From fredrik at pythonware.com Wed Jul 24 13:15:47 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 24 Jul 2002 17:15:47 GMT Subject: How to get the method/function which called a function? References: <1027524712.2754.10.camel@taz.rv.dlevel.net> Message-ID: <7hB%8.672$HY3.187181@newsc.telia.net> Chris Liechti wrote: > >> a.t() # prints " >> 0x805bb64>> a message" > > >> How can I implement the "GET_CALLER()" function in "log()" ? > > > > You can't. > > sure you can get the name of the calling function. its printed when a > exception is thrown, isn't it? ;-) but he wasn't asking for the name, he was asking for the bound method object. if all you need is the name, you can do: caller = sys._getframe(1).f_code.co_name or perhaps def GET_CALLER(): return sys._getframe(2).f_code.co_name ... caller = GET_CALLER() (this gives the name used in the "def" statement that created the code object, not the name used to access the function or method. they're usually the same, though...) From jcw at equi4.com Wed Jul 10 14:44:18 2002 From: jcw at equi4.com (Jean-Claude Wippler) Date: Wed, 10 Jul 2002 20:44:18 +0200 Subject: Pyrhon language dedicated Wiki References: Message-ID: "David LeBlanc" wrote: > From all I've read on the subject by Ward Cunningham (Wiki inventor) and the > advocacy pages on TWiki.org, it takes time, pages and a willingness to > promote in order to get people to start using a Wiki. Even then, use starts > off gradually and then starts to build. > > One example of promoting is adding (what you hope will be interesting) pages > and then announcing them on c.l.py: "Today I added the start of a great > article on threading - come, take a look and add your comments!" (that one > ought to at least get a comment out of Aahz ;)). It's a mindset issue. Get three people together, then four, then five, and just do it. Fill pages, create lists, set up a page of who's who, of conference info, of little tricks and treats, of companies, whatever. Ignore the naysayers, and don't think about how "important" it is. Oh, and don't fall into the trap of debating how to improve the wiki :) It worked for Tcl, it'd be grand to see it work for Python too. -jcw From jack_diederich at email.com Mon Jul 29 21:49:29 2002 From: jack_diederich at email.com (Jack Diederich) Date: Mon, 29 Jul 2002 20:49:29 -0500 Subject: sort() comparison lambda for floats/longs Message-ID: <20020730014929.8158.qmail@email.com> [sorry if this appears unthreaded, I don't subscribe to the list] > here is a lambda I am using in a list.sort() > delta_cmp = [big lambda with lots of ors and ands] :Brrrrrr. Throw that away before it breeds . good point, already forgotten :def delta_cmp(a, b, delta=0.00001): : if abs(a-b) < delta: : return 0 : else: : return cmp(a, b) : :does the same thing, but without trickery. Note that :there's nothing magical about a lambda expression -- it's :exactly the same as a named :function except for lacking a name , and .sort() :couldn't care less whether you pass it a lambda expression :or the name of a comparison :function. The runtime is the same either way too. True, I just did some benchmarks and the same contents put into a func and a lambda were almost identically fast. The lambda won by a couple percent, but that could be for almost any reason in my make-shift test. But the lambda can't have if/else statements in it, and versions of the delta compare with if/else statements killed the nested 'and' 'or' versions by %33 - %50 So if you need an if else, use a func and not a lambda I did find one please-explain-it-to-me result, this def func1(a,b,delta=0.00001): if (abs(a-b) < delta): return 0 elif(a > b): return 1 else: return -1 is %20 faster than def func2(a, b, delta=0.00001): if abs(a-b) < delta: return 0 else: return cmp(a, b) which is odd. replacing the cmp() call in func2 to float.__cmp__ just makes it a lot worse. replacing the cmp() call to be a variable equal to float.__cmp__ is better than float.__cmp__ but still stinky benchmarks in wall seconds for sorting 0.0 .. 3000.0 in order is func1 : 4.1 sec func2 : 5.5 sec func2b: 8.0 sec (replace cmp w/ float.__cmp__) func2c: 6.7 sec (replace cmp w/ foo, where foo = float.__cmp__) it isn't a great test, the numbers are in a list that is already sorted. I sorted 10 times with each func on a pIII 400MHz. So these numbers are interesting but not scientific. I assume the float.__cmp__ is looking up __cmp__ in float's dict for every comparison, so that being slow makes sense. the if/elif/else version (func1) is still faster even if we do the sort in the other direction, so it isn't just that the more heavilly used branch is earlier. cmp() might be spending some time figuring out what to compare to what, but the elif (a > b) would have to do the same thing. So I have three questions: 1) anyone know why func1 is faster than func2? 2) is there ever a reason to use a lambda other than for run-time generated code (and then why is it better than an eval)? 3) I'll ask in a seperate post why the output of a = [1.0 + 0.1] print a, a[0] --- output --- [1.1000000000000001] 1.1 should[n't] scare the crap out of me thanks again, -jackdied -- __________________________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup Get 4 DVDs for $.49 cents! plus shipping & processing. Click to join. http://adfarm.mediaplex.com/ad/ck/990-1736-3566-59 From pyth at devel.trillke.net Thu Jul 25 07:04:00 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 25 Jul 2002 13:04:00 +0200 Subject: cmd, readline, and /path/filename completion In-Reply-To: <200207250040.58148.dcinege@psychosis.com>; from dcinege@psychosis.com on Thu, Jul 25, 2002 at 12:40:58AM -0400 References: <200207241627.04037.dcinege@psychosis.com> <20020724175117.B3904@eecs.tufts.edu> <200207250040.58148.dcinege@psychosis.com> Message-ID: <20020725130400.M10625@prim.han.de> Dave Cinege wrote: > On Wednesday 24 July 2002 17:51, Michael Gilfix wrote: > > The readline library is sufficiently general such that it's meant > ... > > consider to be the atomic words are. Maybe that makes sense? > > I've generally understood this from the get go. What I'm not clear > on is to what extent readline 'just works' and what need to be coded > explictly. For instance I understand, '/' was removed as a delimiter. > But I don't know where readlines's behavior is defined to know that it > should match a path where '/' is involved...and furthermore how to > altered that behavior should I want to. > > > I once implemented an application where I wanted to complete against > > files in a 'current dir'. My solution was to gobble up a list of files > > in teh current directory (I assume you have that part down), and then > > set an attribute of "completion words". Now I wrote this particular app > > I'm by no means a coding novice, and I already know I (or somewhere in > readline) must walk the path and gather a list of executable files. Where I'm > lost is how to pass this to readline. (Or activate it in readline) Have you looked at the 'rlcompleter' module with the standard python distribution? Basically you hook your own completer function into readline and you get called. It's a bit strange because you have to pass back completion words one-by-one to readline and can't simply pass a list back. Actually i have written a new completion-module which i still haven't gotten around to publish. It is a bit more instructive on how readline works and how to avoid some ugly problems with it. holger From karaatanasov at hotmail.com Fri Jul 19 04:43:35 2002 From: karaatanasov at hotmail.com (Kiril Karaatanasov) Date: 19 Jul 2002 01:43:35 -0700 Subject: Do GUIs for DBs exist? References: Message-ID: <71a1c515.0207190043.7afaa65b@posting.google.com> As I view it there are not many (not say close to none) GUI's for databases. Meaning by tools: -Er design tools (access has something like this but not realy) ErWin for fact is the only good looking and kinda working tool in existance. -GUI query builders (dumb one SQL is always better) -GUI query execution -GUI administration to databases (this is actualy two pieces, one is db specific the other not so it varies from db to db) From mis6 at pitt.edu Tue Jul 23 11:06:18 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 23 Jul 2002 08:06:18 -0700 Subject: re.finditer Message-ID: <2259b0e2.0207230706.41ff60b@posting.google.com> According to the standard library http://www.python.org/doc/current/lib/node99.html : finditer(pattern, string) Return an iterator over all non-overlapping matches for the RE pattern in string. For each match, the iterator returns a match object. Empty matches are included in the result. New in version 2.2. However: $ python Python 2.2.1 (#1, Apr 9 2002, 13:10:27) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.finditer('r+?','library') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'finditer' The command re.finditer is not recognized ! All the other commands work, for instance >>> re.findall('r+?','library') ['r', 'r'] find all the occurences of the letter 'r' in the word library as I want. I can live without finditer; however I would like to know if others have experienced the same problem. I installed the standard RPM packages from http://www.python.org/2.2.1/rpms.html -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ P.S. I discovered later that the same problem is in the Windows version too. From mwarden22 at hotmail.com Thu Jul 11 13:16:57 2002 From: mwarden22 at hotmail.com (nealj) Date: 11 Jul 2002 10:16:57 -0700 Subject: detecting unhandled exceptions within PyTrace_EXCEPTION Message-ID: When my application gets PyTrace_EXCEPTION in its trace function, I would like to be able to tell an unhandled python exception from one that is handled (within python). Everything I've tried results in either unhandled exceptions slipping by or handled exceptions getting flagged. Currently what I'm doing is looking at the frame's f_iblock and f_blockstack members and triggering if the f_iblock is 0 or if the block type at f_iblock-1 is SETUP_EXCEPT or SETUP_LOOP - that works fine in my test cases but in an actual program it triggers on exceptions that are multiple layers beneath the try/except block. From gerhard.haering at gmx.de Sat Jul 6 17:13:24 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 6 Jul 2002 23:13:24 +0200 Subject: Python version of STL multimap? In-Reply-To: References: Message-ID: <20020706211324.GA6796@lilith.my-fqdn.de> * Roy Smith [2002-07-06 16:42 -0400]: > I often want to create a dictionary whose values are lists of items > with the same key. I've got variations on [snip] This is what I use: d[key] = d.get(key, []) + [value] Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dreed at capital.edu Tue Jul 30 16:01:27 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 30 Jul 2002 16:01:27 -0400 Subject: Python Cookbook dict problem Message-ID: <200207302001.g6UK1Rc07994@localhost.localdomain> I'm trying the following Python Cookbook recipe with python2.2 def makedict(**kwargs): return kwargs data = makedict(red=1, green=2, blue=3) def dodict(*args, **kwds): d = {} for k, v in args: d[k] = v d.update(kwds) return d tada = dodict(*data.items(), yellow=2, green=4) but I get an error with the last line: >>> tada = dodict(*data.items(), yellow=2, green=4) File "", line 1 tada = dodict(*data.items(), yellow=2, green=4) ^ SyntaxError: invalid syntax What's wrong? Thanks, Dave From tim.one at comcast.net Mon Jul 15 15:02:15 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 15 Jul 2002 15:02:15 -0400 Subject: Making code 2.1 compatible In-Reply-To: Message-ID: [Donn Cave, on the Python Business Forum] > Interesting, but only in the sense of "tantalizing". It reads > like the author (Michael Hudson?) already knew about the basic > idea, and assumed the reader does too. Laura Creighton wrote the FAQ: http://pbf.nuxeo.org/faq.html > I think it would be great if there was some way to arrive at a > kind of standard milepost release version, where if you couldn't > support every single release from 1.5.2 to 2.Xb2, maybe you could > make this one a priority. "You" means library authors, OS vendors, > application authors. It sounds like that might be what they're > talking about - but since it's already where I'm coming from, I > could easily be reading my thoughts into it. They do aim at designating "Py-in-a-tie" releases, keeping them healthy, and extending their useful lives beyond what volunteers have been historically willing to do. > And the choice of 2.2 doesn't help clarify it, since it's a pretty new > release. What's to clarify? The 2.2 line is the most stable Python there is. They're business people, not Luddites . > The point is frankly to kind of deprecate some new releases, > permanently, so the real test of the idea will be the first new > release to be rejected for stability. Just thinking about whether > these people have the stomache for that, They do. > makes me doubt it's what we're talking about after all. But it is > cheering to read that Laura Creighton is involved. Indeed. The PBF is a wonderful thing, and wouldn't exist without Laura's vision and energy. From bokr at oz.net Mon Jul 1 17:16:44 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2002 21:16:44 GMT Subject: How to get rid the new line References: Message-ID: On Sun, 30 Jun 2002 15:04:52 -0600, "Bjorn Pettersen" wrote: >> From: Frank Tobin [mailto:ftobin at neverending.org]=20 >>=20 >> Fredrik Lundh, on 2002-06-29, wrote: >>=20 >> > or add the single character needed to make chomp a >> > bit more robust: >> >=20 >> > def chomp(line): >> > if line[-1:] =3D=3D '\n': >> > line =3D line[:-1] >> > return line >>=20 >> I think the fact that the first few tries here were *wrong*=20 >> about how to implement a chomp indicates that it really=20 >> should part of Python. Just because it's easy to implement=20 >> doesn't mean it can't be part of the, say, string methods. I=20 >> mean, look at str.{upper,lower,isdigit}, etc. A chomp method=20 >> would be popular; rstrip or implementing your own doesn't cut it. > >I submitted a patch for this (that handled mac, win, and unix line >endings) but it was declined by the BDFL. I suspect one of the reasons >were that I named it chomp... > Try again with .stripEOL() ;-) I think it's a worthy string method. I think it ought to do it based on the EOL of the current platform by default. '\n'.join(line.splitlines()) normalizes internal EOLs to \n and effectively chomps so for a single line it seems to have the functionality, though slow. Regards, Bengt Richter From loewis at informatik.hu-berlin.de Mon Jul 29 10:24:29 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 29 Jul 2002 16:24:29 +0200 Subject: default setting of unicode set References: <3D45000F.5040300@gmx.net> <3d454bc8$0$94895$e4fe514c@dreader3.news.xs4all.nl> Message-ID: Boudewijn Rempt writes: > This question comes up so often that I'm more and more convinced that > the argument for deleting sys.setdefaultencoding() is flawed. Calling > sys.setdefaultencoding("utf-8"), _is_ rather explicit, and beats having to > add .encode()'s to all string handling. The attempt to do so is flawed. It is not *all* string handling that should use .encode, but just the output handling. In many cases, using codecs.open instead of the builtin open will remove the need for many explicit .encode calls. Regards, Martin From eric.brunel at pragmadev.com Tue Jul 23 04:31:57 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 23 Jul 2002 08:31:57 +0000 Subject: Tkinter: Relative positioning of Toplevels References: <3e382ec4.0207221224.1b8d49a0@posting.google.com> Message-ID: Julie Torborg wrote: > Hello. > > I was wondering if anyone can tell me how to position a toplevel > relative to another widget. > > Basically, I want to end up with something that behaves like a > pull-down menu, except that you can't select anything--it just > displays information. I'm not clever enough to hack the OptionMenu > class, so I've been trying to use a button/toplevel combination. I > want the toplevel to appear "anchored" to the button. The problem is, > I can't get the toplevel to show up anywhere near the button. I use > > self.x=nb.winfo_geometry() > > to get the position of the button relative to it's parent, but when I > do: > > self.tl.geometry(self.x) > > it draws the toplevel with these coordinates relative to the screen. AFAIK, there is no way to position a widget relatively to another one, nor any method returning the geometry of a widget relative to the screen. But the last one is quite simple to get: use the winfo_rootx, winfo_rooty and winfo_height methods. If you write your code this way (untested): > class eachModule: > def __init__(self, pf): > self.pf=pf ## Remember the button self.nb=Button(self.pf, text="Popup") self.nb.bind("", self.pr) self.nb.bind("", self.rel) self.nb.pack() > > def pr(self, event): > self.tl=Toplevel(self.pf) > self.tl.overrideredirect(1) ## Geometry is button's bottom left corner g = "+%s+%s" % ( self.nb.winfo_rootx(), self.nb.winfo_rooty() + self.nb.winfo_height() ) self.tl.geometry(g) > label=Label(self.tl, text="info up") > label.pack() > > def rel(self, event): > self.tl.destroy() > > > if __name__=="__main__": > > def die(): > root.quit() > root.destroy() > > root=Tk() > > em=eachModule(root) > > eb=Button(root, text="Exit", command=die) > eb.pack() > root.mainloop() it should work as you want... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jblazi at hotmail.com Sat Jul 13 16:37:44 2002 From: jblazi at hotmail.com (JB) Date: Sat, 13 Jul 2002 22:37:44 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: <3d308dcd_2@news.newsgroups.com> Emile van Sebille wrote: > JB >> I have two lists and . The entries of >> these lists have the format (id,rest), where is a >> natural number. The list are sorted, the key is . > > Your use of the term 'key' here is throwing me. Lists > don't have keys, > dicts do. Dicts aren't sorted. ;-/ The list entries are tuples. The first element of a tuple is the sorting key. It is a natural number n, 0<=n Message-ID: <3D2A2272.17382.1F822B@localhost> Seems to have done its job then. On 8 Jul 2002 at 23:00, Matt Gerrans wrote: > Based on the following circumstantial evidence, I think the troll theory > mentioned earlier may is worth considering: > > - The "competitor" was not named. Why? Where is their web site with this > propaganda? > - The preamble sounds salesy. > - There is no "free stuff" at the web site listed. > - The rest of the nonsense listed is largely incorrect but invariably > inflamatory -- trying to generate a large thread so that lots of people will > go to the web site (or at least see the url). > > > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- The Christian religion has been and still is the principal enemy of moral progress in the world. - Bertrand Russell -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From johnroth at ameritech.net Tue Jul 30 12:05:43 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 30 Jul 2002 12:05:43 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: "Jonathan Hogg" wrote in message news:B96C4374.ECA5%jonathan at onegoodidea.com... > On 30/7/2002 12:29, in article ukcu02su9a7r5b at news.supernews.com, "John > Roth" wrote: > > > Why bother with the restrictions? Fredrik had the right idea when > > he said that we needed something to make it obvious that functions > > are first class objects. That is, allow anonamous functions anywhere > > you can have a function object. > > How far does one go? Classes are first-class objects, should we also have > anonymous classes? > > >>> foo = (class: > ... def __init__( self, x y ): > ... self.x = x > ... self.y = y > ... )( 5, 6 ) > >>> > >>> foo.x > 5 > >>> > > I'm a fan of lambda, but when a function is complex enough that it can't be > done in an in-(one-)line lambda then it should be pulled out and given a > name. I tend to agree with you on that one, but it's a matter of style. I observe that e.g. Smalltalk style does anonymous code blocks all over the place. As far as anonamous classes, again, it's a matter of style. I wouldn't do that simply because I think it complicates the code too much. On the other hand, people who regularly program in languages that let that happen might have examples where it makes sense. There's no reason my proposal couldn't be extended to anonamous classes: the syntactic issues are exactly the same. The difficulty is in extending it to methods, as opposed to functions. The only way to distinguish a method from a function today is to observe that methods are defined at the top level of a class; a def anywhere else is a function (I think.) John Roth > > Jonathan > From tdelaney at avaya.com Mon Jul 22 19:12:06 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 23 Jul 2002 09:12:06 +1000 Subject: A better self Message-ID: > From: Louis M. Pecora [mailto:pecora at anvil.nrl.navy.mil] > > What's the overhead of the function calls versus either > > (1) t, x, y, z=self.t, self.x, self.y, self.z > > or > > (2)t=self.t; x=self.x; y=self.y; z=self.z; > > ?? > > Seems like (1) and (2) have less overhead and someone in this thread > said (1) creates and then destroys a tuple (unnecessarily so) and (2) > is better (no intermediate tuple). > > I still prefer (1) -- most readable, but I like minimum overhead. Do some profiling ... (untested code follows) --- import time class Vars: def __init__(self): self.t = 1 self.x = 2 self.y = 3 self.z = 4 def f (t, x, y, z): pass def bench (f=f, time=time): # to remove global lookups r = range(1000000) # modify as required to get usable times v = Vars() start = time.clock() for i in r: t, x, y, z = v.t, v.x, v.y, v.z end = time.clock() print (end - start) start = time.clock() for i in r: t = v.t x = v.x y = v.y z = v.z end = time.clock() print (end - start) start = time.clock() for i in r: f(v.t, v.x, v.y, v.z) end = time.clock() print (end - start) if __name__ == '__main__': bench() --- On my machine, the results are: 2.30967285289 2.14318686404 2.982054833 This is *purely* the overhead of the various function call, tuple packing and unpacking, etc - once you start doing things with these they start having much less effect (because you're only using local variables in each case). Tim Delaney From cliechti at gmx.net Wed Jul 24 12:54:23 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 18:54:23 +0200 Subject: How to get the method/function which called a function? References: <1027524712.2754.10.camel@taz.rv.dlevel.net> Message-ID: holger krekel wrote in news:mailman.1027527338.25170.python-list at python.org: > Alessandro Iob wrote: >> def log(msg): >> caller = GET_CALLER() >> print repr(caller), msg >> >> class A: >> def t(self): >> log('a message') >> >> a = A() >> a.t() # prints "> 0x805bb64>> a message" >> >> How can I implement the "GET_CALLER()" function in "log()" ? > > You can't. sure you can get the name of the calling function. its printed when a exception is thrown, isn't it? ;-) so one way is so a "try: raise except: ..." and then inspect the traceback using the module of the same name. however i think i saw more elegant soltions a while ago in a thread. maybe a search on groups.google.com brings them up. chris -- Chris From lists at lophty.com Wed Jul 31 14:58:06 2002 From: lists at lophty.com (Brian Donovan) Date: Wed, 31 Jul 2002 18:58:06 GMT Subject: parse_qs ... why dictionarykey : list ? References: Message-ID: <2rW19.32951$cm.1292701@bin3.nnrp.aus1.giganews.com> > (1.) Why does cgi's parse_qs return each of the param:value pairs in a > querystring as a dictionary key and a list? > > (2.) How does one format a query string so that lists can actually be > passed to a Python script via querystring so that parse_qs will "see" > them? [I've futzed around a bit but haven't stumbled on how it's done.] I'll reply to my own posting since someone contacted me via email with the answer and it may benefit someone else searching the archives some day : > It's perfectly legal to have more than one input item on an HTML form > with the same name. parse_qs returns its results as a list so that if > there was more than one item with the same name in a querystring you can > access each value. > > For example, try: > > foo.py?color=Red&color=Blue&color=Green Thanks to Abe fettig (http://www.fettig.net) for the answer. :D - brian -- -------------------------------------------------------------------- Brian Donovan, web programmer / researcher Lophty [projects, snippets] Monokrom [commentary, writing] -------------------------------------------------------------------- Namebrand, Corp -------------------------------------------------------------------- From aleax at aleax.it Wed Jul 10 09:12:30 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 13:12:30 GMT Subject: sorting many arrays from one... References: <3D2B0973.B553A25F@info.unicaen.fr> <15FW8.61099$vm5.2221340@news2.tin.it> <3D2C0117.89BCDC43@info.unicaen.fr> Message-ID: <2pWW8.51629$Jj7.1409458@news1.tin.it> Jerzy Karczmarczuk wrote: > Alex Martelli comments my remarks on the slowdown of the sorting > functional parameterized by a named comparison function: > >> > Somebody cares about explaining this behaviour? Dynamic dispatching, >> > while sort() does not any dereferencing? Or what? > > >> Basically, sort needs to do O(N log N) comparisons -- if each comparison >> requires a function call, the time for those calls dominates sorting >> times even if each call does little -- the overhead is the same. > > Sorry, but this does not explain anything. Each comparison requires a > function call (perhaps inlined in some cases, but I don't believe that > 'compare' may be universally inlined) whether this comparison is passed as Not in Python terms. The underlying engine (written in C, Java, C#, or whatever) may arrange execution however it pleases, but it typically does not need to perform a Python function call per comparison. > a parameter, or called "because the sorting device <> what to > call". So, thank you very much indeed for your nice N log N remainder, but > the issue is not the cost of the *call* (execution), but of "call" > (dereferencing/dispatching). The cost of the call is not the execution: it's the cost of the call. Preparing arguments, putting them on-stack as a tuple, getting and unpacking that tuple from stack in the called function, &c. Not sure what dereferencing and what dispatching you have in mind, but argument passing, which is neither dereferencing nor dispatching, IS part of the cost of the call itself. That's quite separate from the cost of the _comparison_ operations, performed either in the function being called, or more directly in a comparison-method. >> If you pass >> nothing, sort knows to use built-in comparison methods, and its wonderful >> optimizations take hold. > > May I ask somebody WHO KNOWS, what are those "wonderful optimizations", Why, of course -- Tim Peters, their author, explains them well in his preface to the Searching and Sorting chapter in the Python Cookbook that O'Reilly publishes these days -- I would suggest you read that. But of course studying the code in Objects/listobject.c is the ultimate way to learn about them -- samplesort, fallback to cleverly tweaked insertion-sort, etc, etc. > and why are they so brutally desactivated with, say, .sort(cmp)? Nothing is "desactivated", either brutally or otherwise: simply, when you have a different major bottleneck, optimizations to other parts that were crucial when THOSE parts were the bottleneck diminish in their effectiveness on overall performance -- Amdahl's Law. The sort method of list objects still performs the minimum possible number of comparisons, whether or not you call it with a comparison function (assuming that function is perfectly correct, of course -- all bets are off otherwise:-). But how much time it costs to perform each of these comparisons is totally out of the sort method's hands, of course. >> Indeed passing cmp directly >> in my test I see a slowdown of about 5 times, while f which calls cmp >> gives 10 times -- see, it IS all about function-call times. > > Thank you for confirming my test. And for confirming that all IS about > the function call. I believe I made it clear that I am aware of that. > I asked WHY? One of important paradigms of modern programming are higher- > order functions. Sure. Python supports callables of many kinds smoothly and fluently, and higher-order functions are among those many kinds. But each call that is actually performed still takes a given amount of time, period. >> > For people coming from the Functional Programming Realm such slowdown >> > of parameterized functionals is hard to accept... > >> A slowdown of about 3.9 CPU seconds >> on my machine for that many calls works out at about 0.76 microseconds >> per call -- preparing the arguments tuple, unpacking it in the >> called function, etc. Doesn't feel wildly out of control to me -- >> it's just a LOT of function calls, using mechanisms studied for an >> intepreted, dynamic language's needs for flexibility, not to get >> superb performance. > > Aha, preparing argument tuples (you mean: making them physically, or > just stacking arguments, or what?). Yes, it takes some time, but there > are interpreted languages (e.g. ML) where it is very well optimized. > No physical unpacking of any tuples inside a function. I'm not sure what you mean by calling ML "an interpreted language" -- I have used compilers for several ML dialects that made extremely effective machine-code (I'm thinking specifically about O'CAML, but I don't think SML trails behind, or not by much -- and surely there's nothing about the LANGUAGE that impedes it). You may surely have interpreted implementations of whatever language you want, but the possibility of using interpreters for (e.g.) Motorola 68000 machine language (as routinely done in modern Macintosh computers) doesn't mean it's "an interpreted language"... it's still a machine-language no matter what the implementation used at a given time is. ML is designed to allow compile-time type inference, which among other pluses conceptually allows all sort of optimizations (whether a given implementation performs them or not is obviously an issue of the given implementation, not of the language itself). Optimization of function calls, arguments passing, et al, is clearly among those. Python has a very different language design, firmly rooted in run-time type determination. That might theoretically not preclude some level of (maybe JIT) type inference -- scheme's compiler 'stalin' being a good example of the best possibilities -- several applications of type inference to Python have been proposed and/or attempted, one of the most interesting currently alive projects being Psyco, see: http://homepages.ulb.ac.be/~arigo/psyco/ In practice, the standard Python implementation does almost NO optimizations at all -- and definitely none requiring any substantial complication whatsoever. Just about all optimization effort has historically gone to the C-coded internals, sort method and dict behavior being two excellent examples. The philosophy of simplicity as first and foremost has served Python well, yielding a stable, industrial-level, production-ready implementation for a language whose strong point is maximizing programmer productivity in the real world. So, don't hold your breath waiting for advanced, highly complicated optimization techniques to appear in the "production" version of Python. If some such technique is your hobby-horse, joining the Python development community is probably just the only way giving some concrete hope of ever seeing it widely deployed. >> What makes it FEEL huge is sort's own superb performance -- 0.16 >> microseconds per comparison *everything included* when using the >> built-in comparison. >> >> So, it's all Tim Peters' fault, for making sort so incredibly fast -- >> let's all gang up against him!!! > > Now, put 4 more (!) marks and it will be even more funny... But, seriously > again a question for somebody who *knows* the details: concretely WHAT is > optimized, and WHY it cannot be done with parameterized sort. See above. It's pretty useless to repeat questions within a single posts, isn't it? >> Oh, and, a warning when you try to do such measurements: if you >> mistakenly call sort on an already-sorted list, it only does >> 299999 comparisons (for a 300000 items list) and finishes in >> 0.04 seconds -- 0.78 with a comparison function, so the ratio >> gets even worse. If you have just one item out of order at >> the end, 300019 comparisons, and the same performances. This >> is truly intolerable -- we HAVE to slow this darn this down!!! > > I happen to know a little bit about serious sorting, so the warning > is a bit redundant, but thank you anyway, it suggests at least that > the sorting procedure does not use the naive quicksort. Unfortunately, > apart from an attempt to be funny, which I appreciate enormously , > it does not address my questions... Again as said previously: nothing can answer them better than the freely available sources; Tim's essay in the Cookbook can help, but maybe not if you know _more_ than "a little bit about serious sorting". It so happens that Python list's sort method is the best-performing sort I've ever seen deployed in production code for many special cases of enormous practical importance (lists that are close to being ordered or just out of order, lists with many duplicate elements, ...), but I'm sure all of the techniques ARE mentioned somewhere (probably in Mixal code) in the "Sorting and Searching" volume of Knuth's AoCP. >> > ... the idea of Decorate-Sort-Undecorate, which begins by constructing >> > an additional list with fast-sortable keys is also something hard to >> > digest. >> >> May I suggest some Fernet-Branca or other Italian amaro to your liking? >> They do wonders to help you digest rich, too-abundant meals. > > My <> has perhaps some different views on what is a too-abundant > meal, and also some different view of what is an elegant answer to a > technical question. Perhaps even on what IS "a technical question" -- "hard to digest", in the milieux I'm familiar with, is only acceptable as such when discussing gastronomy or gastroenterology; otherwise, it doesn't qualify. That you're unable to understand the performance characteristics of pieces of freely available source code that you choose not to examine is hardly "a technical question", after all. > Further on, you suggest (in a long and explicit way) > that it is a good idea, because the speed of comparison makes you gain > alpha * NlogN, while the cost of decorating/undecorating is linear. > That's OK, I never claimed that it wouldn't work. I used it myself, and > I submitted my query because I am still convinced that it shouldn't be > done. For some people wasting space *is* harmful independently of the > asymptotic complexity issues. Wasting != investing. To waste means to consume without good, useful purpose. To invest a resource is to direct it to a useful desired end. Decorate-Sort-Undecorate is a pattern, or idiom, that shows how to *invest* space (memory -- O(N) amount thereof) for the purpose of speeding up a sort (which remains O(N logN), but gains a better multiplicative constant). DSU is one of a class of patterns, or idioms, regarding time-space tradeoffs in performance optimization. Why shouldn't space-time tradeoffs be appropriately performed to obtain desired ends?! If "for some people" such tradeoffs are unacceptable under any circumstances, then those people should not study optimization techniques of this kind, and should maybe see an analyst about their deep-seated psychological problems (but that's up to them, of course). For the rest of us, the pragmatists that make up this happy band of brothers, "shouldn't be done" is an absurd assertion to make about any programming technique which yields desired results. If it works (and you "never claimed that it won't work"), then *WHY* shouldn't it be done?! Such intolerance smacks of religious sects more than of technical debates, particularly in such a pragmatic field as that of programming. >> What's surprising, at all, about this...? > > Shall I repeat it once more? I think that the call overhead should be > perhaps better optimised, and if it seems difficult, I would like to > know why. What's surprising in my question? I am not a flea on your > nose, Maestro. If you want to understand the Python function call overhead, and perhaps try your hand at optimizing it, there's really no possible substitute for studying the freely available Python sources. If you manage to shave off 10% reliably off function call overheads, without bloating the Python interpreter with huge complexity, your patches will no doubt be warmly accepted. And they'll still leave DSU a MOST desirable technique -- remember the speedup with DSU is a factor of 5 or 10, that is, 500% to 1000%, so optimizing function calls by 10% or even 20% will barely touch it... >> Suppose there was no call overhead at all, just a very >> complicated comparison. The effect would be exactly the same, >> no? Appliying a complicated comparison function must happen >> N logN times; applying an equally complicated transformation >> function that makes the items rapidly comparable only must >> happen N times, and thus becomes irrelevant for large N. > > Nothing to do with my questions. > Moreover, in complicated, interesting cases you won't be > able to find this transformation producing fast comparisons in > linear time anyway, so this speculation is not so interesting. It's not speculation AT ALL -- it's a frequent practical case! Consider the case of strcoll vs strxfrm, for example -- as per ANSI/ISO 9899-1990 standard. Who ever said we have to "find this transformation" at runtime?! In many, frequent cases of huge practical importance, the transformation is given. DSU is about how to use the transormation (in a time-space tradeoff) rather than the comparison. It also works fine in functional programming, BTW, even though I don't think Rabhi and Lapalme mention it (but then, their excellent book IS quite a thin one, not an exhaustive tome of "all there's to possibly know" the way Knuth's thick volumes aim to be) -- there's nothing inherently procedural about it. Since you seem to have something _against_ DSU (claiming that it shouldn't be used, that time/space tradeoffs for optimization are "wastes", etc), I think it's very relevant to defend this technique, no matter how loud you keep shouting it has nothing to do with your "questions" (they're more assertions than questions, of course). > The following paragraph neither, I am still asking about the > function call overhead... The subject mentions sorting. If you want to understand Python's call overhead, and possibly see what might be done to reduce it, you're best advised to open a separate specific thread. You're ALSO best advised to study the sources -- and you'll find plenty of willing helpers if you show that you're equally willing to do your homework, rather than being here for the purpose of flamewars. >> But the same effect will apply in ANY language for the >> appropriate kind of sorting task if the comparison op >> you need grows rich and complicated enough to matter. >> >> Assuming the language's sort has perfect optimization >> and the language makes it very easy to build, handle >> and dismantle sequences of tuples, of course:-). But >> these are hardly DEFECTS, are they?-) > > What does it mean: "language's sort has perfect optimization"? It means: it comprises absolutely no wasted effort, but only the minimal, statistically irreducible amount. > It is no magic. I'm not talking about magic (e.g., "oracles" in the algorithms theory sense), just about perfectly real optimization issues of very substantial practical importance. >> > I found it a bit ridiculous to pollute the >> > memory with an ephemeric sequence just because there is something lousy >> > with parametrized sort > >> I think you're using loaded language, presumably reflecting >> loaded and not-well-considered sentiments. > > Thank you. I am always ready to learn how to behave correctly from > serious, elegant people, full of sparkling humor, and who show invariably > their full respect for all people in this newsgroup they address to. You're welcome. I'm always careful to show respect in exact proportion to what is deserved by the other person's behavior on the group, and it's heartwarming to know I've succeeded so well in this case. >> There's nothing "lousy" with functions in Python -- they just take >> measurable time to call, that's all. Most often one doesn't care all >> that much about performance. > > In the name of *who* you are claiming this? In the name of typical users of Python. Programmers in general are obsessed with micro-optimization issues, but Pythonistas seem, again in general, to have reached a more highly enlightened state, and learned not to "sweat the small stuff". Elegance, maintainability, clarity, programmer productivity, are all considerations that by far dominate issues of performance in, say, at least 9 cases out of 10 (but 8 out of 10 would be quite sufficient to claim "most often"). Sorting large sets of data is a good candidate for an exception, as so often such a sort can become an application's bottleneck, unless some attention is paid to the matter. > Almost all creators of almost all programming languages care a lot about > efficiency, about removing redundancies and optimizing frequent > operations. Creators of *languages*, as opposed to creators of *implementations*, would be rather ill-advised if they gave excessive weight to performance issues. Some languages have been designed (or maybe, have "grown") in just such a mindset -- the result, almost inevitably, is the complexity and occasional inelegance of C++, where implementation issues have often been allowed to dominate language-design decisions. The *implementers* of a language will weigh efficiency (of generated, or interpreted, code) against many other issues, of course -- or else you wouldn't see (e.g.) interpreters for languages that can quite well be compiled down to machine-code, as previously mentioned. > Higher-order functions, and parameterized functionals are > absolutely fundamental in functional programming, and the compiler > optimisations are pushed into extreme there. In OO languages all the > caching mechanisms and some other ways of accelerating the dispatch of > virtual methods are also quite important. Python is no exception. It is > already very good, sure, and still improving, so I see no reason not to > see a place which I think to be fragile (if you prefer that than the word > "lousy"). "fragile" is just totally inappropriate when referring to performance -- I suspect you're not using your mother tongue here (but then again, neither am I, so, we're even). Python is indeed an exception in always having put simplicity very, VERY high up on the scale of values. I like the results a lot. Sure, I don't mind if and when some operation gets optimized, as long as it's done with the prudence that has always characterized Python's development. Do study the Python internals, and find out where the moderate amount of complexity in them is invested. Parsing (for reasons that I don't really understand, to be honest -- I don't know why the parsing, which is hardly a key bottleneck, isn't done in the simplest possible way), dictionaries, sorting, and a very few other major hotspots -- small areas of code that have disproportionate impact on overall performance, just as could be predicted. Do, in particular, look for the complications used to "push into extreme ... the optimizations" for any of the cases you mention. Then, when you're done looking, and I suspect having come up with scant findings, feel free to experiment in inserting whatever complications you believe would make a major difference. I'm pretty confident that nothing will even begin to _scratch_ the 1000% advantages so easily measured for DSU, of course:-). > I appreciate your contribution to the Cookbook and I understand that > you will defend DSU. > >> That's not "polluting the memory with an ephemeric sequence" -- >> it's investing some memory (not much -- O(N) memory, peanuts!) >> to reduce computation. A hallowed, time-honored approach, you know. > > It is your philosophy but there are others. For some people space matters, > you know. It's not a matter of "for some people" -- the way you put it, you do make it seem a psychopathological issue, you know. If you don't have the space to invest, then you don't -- that doesn't depend on "people" as much as on what size of program is running on what size of machine. In a vast majority of cases, O(N) -- typically with a reasonably small multiplicative constant -- is a reasonable and available amount of space to invest to speed up by (say) 10 times an O(N log N) sort. The space is taken only during the sort itself, after all: if it's there at all, it's a good way to use it. When you sort data sets that just push the boundaries of your currently available space, there may be special cases where the sort per se would work -- there is JUST enough space for that -- but the extra O(N) memory is the straw that breaks the camel's back. They're quite special cases because when you need to sort just a bit more data than that again, then you can't fit the data themselves in memory any longer, together with program and working space. Then, you use other sorting techniques -- see my example of external mixed mergesort using generators in the "iterators and generators" tutorial I gave at Europython, http://europython.zope.nl/sessions/presentations/PythonTutorials/EPC2002-Martelli-IteratorsGenerators.pdf (one single long URL -- rejoin if split by news / mail software). I have no special interest in that narrow zone where the data fit but the extra O(N) space isn't available -- if I can't be confident of having the space for a normal DSU, I'll jump right over to some sort approach where most of the data can reside on-disk instead. If for some strange and wondrous reason you need to target exactly that narrow zone, OK, but you can hardly expect special effort from the point of view of a general-purpose language and library to help you target that very special case. Alex From aleax at aleax.it Fri Jul 12 05:12:20 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 09:12:20 GMT Subject: Most pythonic way to format a number with commas? References: Message-ID: Emile van Sebille wrote: > Ned Batchelder >> For dir/ls replacement script, I wanted to format file sizes with >> commas as a thousands separator. I didn't find anything in the >> standard library, > [snip] >> Is there one? > > It's buried in locale... "buried" is a loaded word...:-) >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "") > 'English_United States.1252' >>>> locale.format("%8.2f", 1234.56) > ' 1234.56' >>>> locale.format("%8.2f", 1234.56,3) > '1,234.56' Yes, but this example risks being a BIT misleading...: >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'en_US' >>> for x in range(1, 5): ... print locale.format("%8.2f", 1234.56, x) ... 1,234.56 1,234.56 1,234.56 1,234.56 >>> I.e., the third argument to locale.format is taken as a boolean -- if it's true, then digit grouping is performed as the locale requires, if false or missing, no grouping. There is, unfortunately, no "architected" way to perform digit grouping with simply-specified number of digits and separators -- you have to cheat. Specifically, for example, suppose you need digits to be grouped by-four...: >>> locale.format("%d", 1112345673489, 1) '1,112,345,673,489' >>> def localeconv(): ... d = _real_localeconv() ... d['grouping'] = [4, 4, 0] ... return d ... >>> _real_localeconv = locale.localeconv >>> locale.localeconv = localeconv >>> locale.format("%d", 1112345673489, 1) '1,1123,4567,3489' >>> This works only because locale.format internally calls locale.localeconv at a Python level -- any dependence on internals, such as this one, is too fragile, liable to break on any upgrade to the module involved. Therefore it cannot be recommended. Unfortunately, copy-and-paste and reinvent-the-wheel are the two recommended (sigh) ways to "reuse" the digit-grouping functionality that's buried (ahem) in module locale. Alex From max at alcyone.com Tue Jul 9 01:11:36 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Jul 2002 22:11:36 -0700 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> <3D2A57B9.8EDD2BF0@engcorp.com> <14rkiu8fnp8chiua156k2qm9r1s2vf5trs@4ax.com> Message-ID: <3D2A7088.755DD676@alcyone.com> Lowel Stern wrote: > fp = os.popen('C:\python_scripts\prog %s') % (key) fp = os.popen('C:\python_scripts\prog %s' % key) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From b.maryniuk at forbis.lt Tue Jul 9 10:07:40 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 16:07:40 +0200 Subject: Table Widget (without Installation) In-Reply-To: <20020709134515.GA17563@lilith.my-fqdn.de> References: <3D2A9948.5090304@thomas-guettler.de> <200207091534.21993.b.maryniuk@forbis.lt> <20020709134515.GA17563@lilith.my-fqdn.de> Message-ID: <200207091607.40473.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 15:45, Gerhard H?ring wrote: > But it's all solvable with actually reading INSTALL.txt and BUILD.unix. RTFM. STFW. Gerhard, that's what I'm talking about in this case... :o) -- Sincerely yours, Bogdan M. Maryniuck Running Windows on a Pentium is like having a brand new Porsche but only be able to drive backwards with the handbrake on. (Unknown source) From simon at uggs.demon.co.uk Wed Jul 10 03:29:54 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Wed, 10 Jul 2002 07:29:54 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: <3d2be255.329033@news.dsl.pipex.com> On Tue, 09 Jul 2002 23:17:01 GMT, "Fredrik Lundh" wrote: >Simon Foster wrote: > >> You seem to be mistaking me for an idiot. > >mistaking? > > > > Oh Fredrik, I bought your book too! -- Simon Foster Cheltenham England From jimmy at retzlaff.com Sun Jul 28 06:21:14 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 28 Jul 2002 03:21:14 -0700 Subject: PythonWin ODBC: DSN-less connecting string Message-ID: William Dode wrote: > "Jimmy Retzlaff" ?crivait: >> In the meantime I'd be happy to send a copy of my patched odbc.pyd >> compiled for Python 2.2/2.2.1, or I can also send odbc.cpp if you'd like >> to compile it yourself for another version of Python. > > do you mean you could become the new maintainer of odbc ? :) Uh, uh, uh, I'm not sure about that... my customers and I have been using it extensively in production code for something like 4 years now and we don't plan to change anytime soon. So I do plan to make sure it keeps running in one form or another - don't know if I'd say that makes me the "new maintainer." I don't think I could deal with the fame & fortune that would bring. :) Jimmy From otijim at yahoo.com Tue Jul 16 10:14:48 2002 From: otijim at yahoo.com (Jake R) Date: Tue, 16 Jul 2002 14:14:48 GMT Subject: Common list in distinct objects' References: <3d331fa9.361390031@news.byu.edu> <3d332491.362646438@news.byu.edu> Message-ID: <3d3427bf.428996374@news.byu.edu> I knew I had read that 'Important Warning' somewhere. I only remembered about 5 minutes after my posting. It describes a short snippet to "overcome" this by using None and an IF...ELSE clause. I just wonder what is the preferred result. IMO each call should return a new and distinct list (to me this makes sense since in my case each call creates a new and distinct object. But other than PHP I have never used a language that allows default parameter values so maybe this is an already established standard that I'm not familiar with. On Tue, 16 Jul 2002 08:26:08 +0000 (UTC), Duncan Booth wrote: >otijim at yahoo.com (Jake R) wrote in news:3d332491.362646438 at news.byu.edu: > >> Now that I think about it some more I seem to remember reading >> somewhere in the tutorial that class definition is only processed once >> and being so means that the default list (myList=[]) in my __init__ is >> only created once and thus any objects created all point to the same >> list unless I create a new list (ie pass one in or have the __init__ >> function do it when its called) >> >> Does that sound right? Still....I don't think thats what way it ought >> to behave. > >Please read the FAQ entry number 6.25: > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.025.htp > >It is all extremely logical once you understand what is going on, but >admittedly can be confusing for beginners. > >You might also find it useful to read the eff-bot guide to Python objects >at http://effbot.org/guides/python-objects.htm to make sure you understand >how Python's objects and assignments work. Also the tutorial section 4.7.1 >has the 'important warning' that you half remembered. > >-- >Duncan Booth duncan at rcp.co.uk >int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" >"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From maxm at mxm.dk Thu Jul 18 07:58:01 2002 From: maxm at mxm.dk (Max M) Date: Thu, 18 Jul 2002 13:58:01 +0200 Subject: Sorting list of objects on arbitrary attribute Message-ID: <3D36AD49.2020305@mxm.dk> I often find that I need to sort a list of objects on one or more attributes. So I have written a function which does this. It is listed below. But usually when I think up something clever it is allready included in the standard library, or somebody has a 2 liner which does the same thing. So what is the better solution ;-) If something like it isn't included in the standard library, how come? It is a very common functionality that I have seen used in many places. regards Max M --------------------------------------------------- def objSort(aList, attributes): """ Sorts list on one or more attributes. If attribute is callable it sorts on the result attributes can be a single attribute-name or a sequence of them """ sortableList = [] if type(attributes) == type(''): attributes = [attributes] for item in aList: sortList = [] for attrName in attributes: attr = getattr(item, attrName) if callable(attr): attr = attr() sortList.append(attr) sortList.append(item) sortableList.append(tuple(sortList)) sortableList.sort() return [tup[-1] for tup in sortableList] if __name__ == '__main__': ############################# ## Simple tests from random import choice, randrange class Struct: # simple test object def __init__(self, **kw): self.__dict__ = kw self.rand = randrange(20,25) def __str__(self): result = [] for key, val in self.__dict__.items(): result.append('%s: %s\n' % (key, val)) return ''.join(result) def rndNumber(self): return self.rand randomLikeStrings = [ 'sdf asdf asdf asdf i', 'sdf asdf asdf asdf h', 'sdf asdf asdf asdf g', 'sdf asdf asdf asdf f', 'sdf asdf asdf asdf e', 'sdf asdf asdf asdf d', 'sdf asdf asdf asdf c', 'sdf asdf asdf asdf b', 'sdf asdf asdf asdf a', ] # build up a list of objects to sort. listSize = 30 aList = [] for i in range(listSize): aList.append( Struct( name=choice(randomLikeStrings), age=randrange(1, 5) ) ) # Sort and print out aList = objSort(aList, ('name', 'age', 'rndNumber')) for item in aList: print item From fredrik at pythonware.com Fri Jul 19 04:40:16 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 Jul 2002 08:40:16 GMT Subject: XML::Twig-like module wanted References: <87k7ns9kyg.fsf@pokey.henrik-motakef.de> Message-ID: Henrik Motakef wrote: > Does anybody know about something similar to XML::Twig (see > ) for Python? from your description, it sounds like the "pulldom" standard module is what you want: from xml.dom import pulldom source = pulldom.parse("somefile.xml") for event, node in source: # node is now a dom node without child elements if event == "START_ELEMENT" and node.tagName == "record": # make sure we have all child elements source.expandNode(node) process(node) From tim.one at comcast.net Thu Jul 18 19:17:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 18 Jul 2002 19:17:19 -0400 Subject: Python v.s. huge files PROBLEM!! In-Reply-To: <11e94203.0207181433.1c32f5bc@posting.google.com> Message-ID: [Jose Rivera] > Scenario: > OS : WinNT 4.0 > FileName: RESPALDO_MENSUAL_Data.MDF > Size : 243,386,941,440 bytes > > Problem: > I want to copy this file to another disk. Both disks have 500 GB of > free space. > > Microsoft problem: > You May Not Be Able to Copy Large Files on Computers That Are > Running Windows NT 4.0 or Windows 2000 (Q259837) > > Workaround suggested by Microsoft: > Use Backup / Restore utilities > Result: They didn't work either... using HP OmniBack > > Workaround made by us: > Make a python program that read and writes to the other file in > theother disk. > > Python Code: > > import sys > > if len(sys.argv) != 3: > print 'Format:' > print '\t pyCopy.exe SourceFile EndFile' > else: > fn1=sys.argv[1] > fn2=sys.argv[2] > f1=open(fn1,'rb') > f2=open(fn2,'wb') > data=f1.read(1024*1000) > while data: > f2.write(data) > data=f1.read(1024*1000) > f1.close() > f2.close() > > Result: > IOError: [Errno 22] Invalid argument Tell us which version of Python you're using, and give a complete traceback. It's hopeless unless you're using Python 2.2 (2.1 didn't support large files on Windows). Looks like 2.2 probably won't help either, though; the KB article you referenced: http://support.microsoft.com/default.aspx?scid=kb;EN-US;q259837 makes it quite clear that this is a fundamental flaw in the OS kernel support for buffered I/O. Python also uses buffered I/O. From e.d.andersen at mosek.com Thu Jul 18 06:58:57 2002 From: e.d.andersen at mosek.com (edadk) Date: 18 Jul 2002 03:58:57 -0700 Subject: Fail pyton build. What to do Message-ID: Hi, I am build python 2.1.1 on Solaris/Intel 8 and get the error meassage below. [I do not need the audio stuff at all. Can I shut it off for instace.] What can I do? Thanks. Erling building 'sunaudiodev' extension gcc -g -O2 -Wall -Wstrict-prototypes -fPIC -I. -I/tmp/Python-2.1.1/./Include -I/usr/local/include -IInclude/ -c /tmp/Python-2.1.1/Modules/sunaudiodev.c -o build/temp.solaris-2.8-i86pc-2.1/sunaudiodev.o /tmp/Python-2.1.1/Modules/sunaudiodev.c:24: sun/audioio.h: No such file or directory WARNING: building of extension "sunaudiodev" failed: command 'gcc' failed with exit status 1 running build_scripts not copying /tmp/Python-2.1.1/Tools/scripts/pydoc (up-to-date) bash-2.03# From bsder at mail.allcaps.org Tue Jul 2 02:00:30 2002 From: bsder at mail.allcaps.org (Andrew P. Lentvorski) Date: Mon, 1 Jul 2002 23:00:30 -0700 (PDT) Subject: Performance question about math operations Message-ID: <20020701225939.J747-100000@mail.allcaps.org> I have a VLSI layout editor written in Python. At its core, it has to redraw a lot of polygons. This requires a lot of coordinate conversion mathematics. Essentially the following loop: #! /usr/bin/env python def main(): i = 0 while i < 1000000: i = i + 1 (1-678)*3.589 -((1-456)*3.589) if __name__=="__main__": main() Now, I understand that looping in Python has overhead. It turns out that the loop without the math operations takes about .5 seconds. Fine. However, each line of math operations adds .75 seconds to the total loop time for a total run time of about 2 seconds. This is with -O enabled (even though it doesn't seem to have any effect). This same loop in C++ (with classes, indirection, copy contruction, etc) takes about .05 seconds. That's about a factor of 30 (1.5 / .05) difference even if I cancel out the loop overhead. I could handle factor of 2 or 4, but 30 seems a bit high. What is eating all that time? And can I do anything about it? -a From claird at starbase.neosoft.com Sat Jul 27 11:51:33 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 27 Jul 2002 10:51:33 -0500 Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> Message-ID: <26EB8847BE9C61D9.2AACCE55528CDC81.433FEA3EC5F5A7D2@lp.airnews.net> In article , Chris Liechti wrote: >keilj_33 at yahoo.com (Jeffrey Keil) wrote in >news:67f6bbe5.0207270544.696f6076 at posting.google.com: > >> Greetings: >> >> I'd like to have a Python script open a text file, process the data in >> the text file and then write a report to an Excel file. I'm not sure >> how I would write to an Excel file from a Python script. Is there any >> books that would give me details on doing this? > >you could use COM. but i think its simpler to write the output to a text >file again. use tabs to separate columns and name it .csv - excel will >autodetect the format and load it correctly. . . . Excellent advice--that is, it's the best *I* know. Excel apparently has several formats it's willing to recognize. The CSV you've described is only one, but it's the easiest to recommend. I don't have confidence in any of the others. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From StRanGy at cna2.kav.vest.hr Thu Jul 11 07:23:21 2002 From: StRanGy at cna2.kav.vest.hr (Ivica) Date: 11 Jul 2002 11:23:21 GMT Subject: PyGPG References: Message-ID: On Thu, 11 Jul 2002 12:32:36 +0200, Gillou wrote: > Try searching from www.sourceforge.net > I remember having seen a python gpg wraper there. > > --Gilles Tnx people for the given help. From tim.one at comcast.net Fri Jul 12 16:56:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Jul 2002 16:56:19 -0400 Subject: Is count supposed to still work? In-Reply-To: Message-ID: [David LeBlanc] > Whether or not you explicitly import string, > count(mystring, substring) > isn't working ("NameError: global name 'count' is not defined") (N.B. this > statement is in a method of a class), Python has never had a builtin function named "count", so I don't see how it ever could have worked. The string module did and still does export a function named count, but you have to import it first if you want to use it as a function. From skip at pobox.com Tue Jul 9 18:03:38 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Jul 2002 17:03:38 -0500 Subject: File size error in os.stat with large files. In-Reply-To: References: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: <15659.23994.749181.970029@gargle.gargle.HOWL> >> You have to compile python with large file support to handle files >> over 2GB. To test whether you have this enabled: Matt> Do you know why the binaries are not compiled with large file Matt> support as default? I suspect it allows the same binaries to run on a larger number of Windows versions. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From krzysiek at dgt-lab.com.pl Mon Jul 8 05:44:36 2002 From: krzysiek at dgt-lab.com.pl (Krzysiek Czarnowski) Date: Mon, 8 Jul 2002 11:44:36 +0200 Subject: Is there a re guru out there? Message-ID: <003d01c22664$1294ec50$2706a8c0@dgtlab.com.pl> Hello! And thanks for the prompt answer. Daniel Yoo wrote: > Ah, a LaTeX to TeX converter. Cool! Well, rather a simple tool to reduce the amount of manual work required... > If you can guarantee that there isn't any nested braces within the "frac" groups I would like to accept nested braces (at least to some extent)... Later I will look into your examples closer. > However, if there are groups within the frac groups, like: > > \frac{e^{42}}{\pi} > > then that will cause problems. This kind of pattern is something that > regular expressions alone won't be able to cope with, because the > grammar is recursively defined. That's what I was afraid of... Probably I will have to do with a solution accepting only finite level of nesting... Thanks anyway, Krzysztof From duncan at NOSPAMrcp.co.uk Tue Jul 9 08:50:29 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 12:50:29 +0000 (UTC) Subject: Multi-threading on Multi-CPU machines References: <3D29FC43.C239BD5F@earthlink.net> Message-ID: gtaylor at lowebroadway.com (Garry Taylor) wrote in news:f0fd5987.0207090102.7362dd27 at posting.google.com: > So, am I correct in thinking that there is nothing I can do about > this, and still use standard Python? I understand that Solaris has a > very good threading library, but from the comments above, I assume > that this would make no difference? Do you have any tips/ideas how I > could make use of multiple processors in a Python program? > Can you split your program into several communicating processes? Each process has its own GIL, so if you can run multiple processes they can make better use of CPU. The only other option really is to see if you can isolate CPU intensive sections and rewrite them in C, then you might be able to release the GIL enough to get a useful speedup. Then again it may be possible to get enough speed improvement by modifying existing code. I find it can be quite hard working out exactly where Python is spending all its time. Do you know where in your current code most of the CPU is actually used? -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bobnotbob at byu.edu Wed Jul 31 13:41:25 2002 From: bobnotbob at byu.edu (Bob Roberts) Date: 31 Jul 2002 10:41:25 -0700 Subject: win32: execute a file just like a double-click Message-ID: >From within python, is there any way to "execute" a file just like you double-clicked on it? For example, if you "execute" a .mp3, winamp plays it. If you "execute" a .txt, it opens in notepad. From fperez528 at yahoo.com Wed Jul 24 13:58:46 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 24 Jul 2002 11:58:46 -0600 Subject: Simple HTML classes References: <47ptjushoni8bfqurttm86sgt8bm6tge84@4ax.com> Message-ID: Dale Strickland-Clark wrote: > We need a bunch of light-weight HTML classes to build web pages - > especially forms. These will work with the CGI module so that the > forms related classes are bi-directional. > > Before we start writing them them, I was wondering if anyone had done > anything similar or there was a module I'd overlooked. > > I can't believe this hasn't been tackled before. Random, quite possibly wrong shot: have you looked at HTMLgen? I've used it for simple stuff and seems quite nice, but there may well be a million reasons why it doesn't fit your problem. cheers, f. y From glongman at ilangua.com Tue Jul 30 10:37:49 2002 From: glongman at ilangua.com (Graeme Longman) Date: Tue, 30 Jul 2002 15:37:49 +0100 Subject: Searching for email address References: Message-ID: <3D46A4BD.A894DC59@ilangua.com> In the process of translating our client's sites. Just a script to find all the email addresses so that the email addresses aren't included for translation. No spamming, don't stress. :-) "Charl P. Botha" wrote: > In article , > Graeme Longman wrote: > > I'm writing some code which searches html for email addresses. Does > > anyone out there have a good regular expression syntax for searching for > > the email string, I'm sure this must've been done a few times before. > > Excuse my curiosity, but what are you going to do with this code? :) > > -- > charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ > -- > http://mail.python.org/mailman/listinfo/python-list From renez at lightcon.xs4all.nl Fri Jul 26 17:44:52 2002 From: renez at lightcon.xs4all.nl (renez at lightcon.xs4all.nl) Date: 26 Jul 2002 21:44:52 GMT Subject: Slow program exit on Dec Alpha 4.1 OSF Message-ID: Hi, I'm trying to collect information from a cvs repository. Basically I visit every RCS file in the repository get tags:version with line=file.readline and build up the following dictionaries File[FileId] = name FileIndex[name] = (FileId , (branchetag (Bole, Bole)) ) tag[name] = (tagid,counter) tagindex[tagid] = name filetag[FileId, tagid] = version tagfile[tagid, FileId] = version and i run it on part of the repository for 500 files and it came back with my message (and last statement!) Done 500 file 485 tags Then the program sits for a long time (1 min and more) before it gives me back the shell prompt. If i look at ps it says ... size WCHAN ... ... 25M nxmbloc ... The less files I process the faster the program comes back after the final message. I assume Python is cleaning up the shop like free memory etc, Which probably means I'm very inefficient with variables or other strange conceptions of my own. I cannot make head or tails out of this and probably most of you also not out of this message ;-( too. Anyway this is python 2.2.1 compiled out of the box with > CC=cxx CXX=cxx ./configure --prefix=$HOME/python > make install OS = OSF4.1 dec compiler digital cxx compiler 6.xx Anyone seen this behavior and have an explanation for it. The source code is less than 100 lines but that doesn't say much other then that Python is very compact programming language. Ren? -- From markulus00 at yahoo.com Mon Jul 29 16:35:26 2002 From: markulus00 at yahoo.com (Mark Erikson) Date: 29 Jul 2002 13:35:26 -0700 Subject: Win32 API question - Postmessage and Win2K lock window Message-ID: <4d3df955.0207291235.1a8916b@posting.google.com> Hey, folks. I've got a problem regarding the PyCwnd.PostMessage() function behind the Windows 2000 lock window. I know this is more of an API question than a Python question, but figured it was worth asking here just in case. Basics of the issue: I'm trying to automatically launch the Windows 2000 Defrag utility. While any user can launch it, the defrag function can only be activated by an administrator. By getting the window handle and creating a PyCwnd from the handle, I can do PostMessage() to the window and send WM_KEYUP and WM_KEYDOWN messages. When run as an administrator, I can successfully simulate the keystrokes needed to start the defragmentation. However, this needs to be run on other users computers, most likely during lunch. So, I've been working with Win2K's "runas" utility. It requires that a password actually be typed in, though no input is visible. Again, I can use PostMessage to send simulated keystrokes to the Command Prompt window, runas completes successfully, Defrag launches, and everybody's happy. The problem comes when I try to deal with people using the CTRL-ALT-DEL "Lock Window" function, which absorbs any standard keyboard input (which is why I'm using WM_KEYUP/DOWN instead of a more standard SendKeys type deal). If I'm just running Defrag, I can still successfully use PostMessage() and activate it. *IF*, on the other hand, I launch Runas behind the lock window, *I cannot send the keystrokes*. I've looked at everything from using pipes to replace stdin to using other Runas-type utilities (SU, sfImpersonator, etc) to using WriteConsole() to too much other stuff to remember. Nothing I've experimented with has seemed to work. So... does anyone have any ideas? I just need to be able to simulate keystrokes for a password to a Command Prompt window for which I have a handle, BEHIND the Win2K lock window. I'm open to any suggestions, including stuff that I've looked at already (since it's quite possible I missed something). Thanks in advance! Mark Erikson markulus00 'at' yahoo 'dot' com From anton.wilson at camotion.com Tue Jul 30 18:57:10 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 30 Jul 2002 18:57:10 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207302256.SAA24491@test-area.com> > If you try the current CVS version of Python, the implementation of "the > lock" on Linux has changed to use POSIX semaphores instead. They may or > may not act more like you hope -- I don't know (haven't tried it). It > seems possible that they might, since semaphores came out of the POSIX > realtime extensions, where people feel much freer to make unreasonable > demands. My unreasonable demands have been met by the CVS version! :D Thanks > > > ... > > I have a feeling that there is a hidden race condition between when the > > thread wakes up the other thread and tries to reaquire the lock. > > "The race" would be in the platform implementation of > pthread_cond_signal(), but I expect that's working the way its author > intended. From donn at u.washington.edu Fri Jul 12 13:18:49 2002 From: donn at u.washington.edu (Donn Cave) Date: 12 Jul 2002 17:18:49 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: Quoth eddie at holyrood.ed.ac.uk (Eddie Corns): ... | Basically, when you layout code you need to think about how to convey to the | reader what's going on. In constructions like the above I believe it's much | easier to see that it's only ever looking at the beginning of the line and the | table like structure makes it easy to map what it finds to what gets done. You can do what you want, but if you're thinking of other programmers, please don't do that. Don't try to come up with nifty ways to convey to the reader what's going on. Read the coding standards in PEP 8, and follow them to the letter. You can't do better. I'm not saying the standards were developed by a higher intellect than yours or are informed by some superior rationale, but they're inherently better than anything you can do, just because they're how we're used to reading and writing Python. There's some latitude for circumstances, but the most readable code will still be the stuff that follows the standard. Donn Cave, donn at u.washington.edu From sschwarzer at sschwarzer.net Mon Jul 22 13:41:23 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Mon, 22 Jul 2002 19:41:23 +0200 Subject: correct syntax for db api.. References: Message-ID: <3D3C43C3.6090605@sschwarzer.net> Hi Eugene Kim eugene kim wrote: > import pgdb > > db=pgdb.connect(user='postgres',database='test') > cursor=db.cursor() > > ----------------- > cursor.execute('select url, visits from history where url= %s', (self.url)) > ------------- As a side note, (self.url) is an expression, not a tuple. Both should work. > or > ----------------- > sqlselect = 'select url, visits from history where url = %s ' > cursor.execute(sqlselect % self.url) > ---------------- Perhaps you have to use quotes: sqlselect = "select url, visits from history where url='%s'" cursor.execute(sqlselect % self.url) Stefan From pixie888 at hotmail.com Wed Jul 10 04:50:20 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Wed, 10 Jul 2002 08:50:20 GMT Subject: Deriving from Exception Message-ID: <3d2bf4b6.183387921@news.skynet.be> Hi, I have some classes which derive from Exception, however in the __init__ function I do not call the __init__ function of Exception itself, allthough I think I should. The reason I don't do it is because I see that in all the tutorials about Python the tutors themselves don't do it either. Can anybody tell me why? Thanks, Henk From cliechti at gmx.net Sat Jul 20 17:59:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jul 2002 23:59:09 +0200 Subject: unloading imported modules References: Message-ID: Gerhard H?ring wrote in news:slrnajjfid.5d8.gerhard.haering at lilith.my-fqdn.de: > Chris Liechti wrote in comp.lang.python: >> xeon at dacreations.cjb.net (xeon) wrote: >>> Is it possible in python intepreter to unload imported modules? or are >>> there ways to refresh the loaded functions if ever the module is >>> updated, other than restarting the intepreter? >> [...] maybe autoreloading interests you too. here comes the little >> bit log URL.... (one line, blah balh ;-) >> >> http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf- >> 8&th=2ae8aac3beeb9859&seekm=mailman.1005899002.5050.python- >> list%40python.org&frame=off > > Trick of the day learnt on #python: > > http://tinyurl.com/r22 > http://makeashorterlink.com/?H56C21F41 almost nice, but you hide the target and i like to know where a link is going... and second what do they do with all the site hits they get? i guess they can pull out some interesting statistics out of the link targets and hit count.... chris -- Chris From gtalvola at nameconnector.com Wed Jul 17 17:13:25 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Wed, 17 Jul 2002 17:13:25 -0400 Subject: pickle performance on larger objects Message-ID: <61957B071FF421419E567A28A45C7FE514A5D1@MAILBOX.nameconnector.com> Try using binary pickle format (pass in 1 as an extra third argument to dump()). It's quite a bit faster both dumping and loading. - Geoff > -----Original Message----- > From: Sam Penrose [mailto:spenrose at intersight.com] > Sent: Wednesday, July 17, 2002 5:09 PM > To: python-list at python.org > Subject: pickle performance on larger objects > > > On a recent project we decided to use pickle for some quick-and-dirty > object persistence. The object in question is a list of 3,000 > dictionaries > whose keys and values are short (< 100 character) strings--about 1.5 > megs worth of character data in total. Loading this object > from a pickle > using cPickle took so long we assumed something was broken. > From baptism_of_fire_842 at hotmail.com Fri Jul 5 19:29:48 2002 From: baptism_of_fire_842 at hotmail.com (Mike Johnson) Date: 5 Jul 2002 16:29:48 -0700 Subject: idiots guide to python Message-ID: <626290cd.0207051529.518f4ce7@posting.google.com> I am starting an A-Level course in computing in september, and i will need to learn how to use python. I have no previous experience of programming, but could anyone point me in the direction of an "Idiots Guide"? thanks. Mike Johnson From nospam at any.time Thu Jul 4 20:54:56 2002 From: nospam at any.time (Some One Else) Date: Fri, 05 Jul 2002 00:54:56 GMT Subject: Math irregularity ... is this normal? References: Message-ID: Thank you Richard & Emile for your speedy responses! Still strange that a great book like LP showed a clean calculation ... Thanks! -s.o.e. Richard Jones wrote: > On Fri, 5 Jul 2002 10:10 am, Some One Else wrote: >> Hello! >> >> I just compiled and installed Python 2.2.1 on Linux-Mandrake 8.0. When I >> >> do the following: >> >>> 2/5.0 >> >> 0.40000000000000002 >> >> In 'Learning Python', a similar example says I should get the more >> logical >> answer of 0.4. Did I install something wrong? I can see where this could >> result in creeping math errors. > > Yes, this is normal :) > > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp > > > Richard From aleax at aleax.it Mon Jul 8 02:36:39 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 06:36:39 GMT Subject: Properties - when and why References: Message-ID: Arthur Siegel wrote: > Learning something about properties - as usual the hard way. > Beginning to conclude that they, as I recently learned with __slots__, > are more "special case" than I first understood. Maybe, but I don't think the following example indicates that. It seems a perfectly normal and general case. > Say self.W and self.U are each 3 element vectors referenced on > initialization, with attributes x,y, z. V is a calculated vector. V=W-U > > def get_V(self): > return self.W-self.U > > V=properties(get_V) Presumably 'property', but OK, so far so good. Each time you access foo.V, this induces a call to foo.W.__sub__(foo.U). OK. > But occasionally I need to access V's attributes individually. Sure, it happens. > def V_homogenous(self): > return array((V.x,V.y,V.z,1.)) That, of course, doesn't work -- what's that "V"? Must be some global variable, and has no relation with method get_V. I'll assume you mean self.V here... > Have I not just made three calls to the vector subtraction > of the get_V method? Not good. Why not? As far as any of us know so far, and as far as Python knows, each call to self.W.__sub__(self.U) may return a completely different result. So, when you specify three calls, you get three calls. Nothing "special case" about this -- Python NEVER optimizes multiple calls down to one call, nor does it ever do any "common subexpression elimination". If you need such things to happen, you just specify them yourself. > Could have done: > def get_V(self): > self._V = self.W - self.V > return self._V > > def V_homogenous(self): > return array((self._V.x,self._V.y,self._V.z,1.)) Now THAT would be outright silly -- with no guarantee in the body of V_homogeneous that get_V has ever been called and this that self._V has any relation with reality! The obvious solution for this case is to keep your original get_V method intact and to code V_homogeneous the simple way: def V_homogenous(self): V = self.V return array((V.x,V.y,V.z,1.)) Seriously, what COULD be simpler -- or, less special-case...?! > Is the when and why of using properties something that can be > explained in few enough words? Use properties when you want the syntax of attribute access and the semantics of a method call. That has nothing to do with the fact that if you need "common subexpression elimination" you need to write that out explicitly -- Python never eliminates common subexpressions by itself. Alex From fredrik at pythonware.com Mon Jul 1 07:10:44 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 11:10:44 GMT Subject: arguments to functions References: Message-ID: Bengt Richter wrote: > >>> test(10, 11, 12, expected=5) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: test() got multiple values for keyword argument 'expected' > > I'd be inclined to call that a bug, actually. only if you're ignoring the language reference, which tells you how this really works. From phr-n2002b at NOSPAMnightsong.com Wed Jul 17 18:43:35 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 17 Jul 2002 15:43:35 -0700 Subject: pickle performance on larger objects References: Message-ID: <7x4reygelk.fsf@ruckus.brouhaha.com> Sam Penrose writes: > On a recent project we decided to use pickle for some quick-and-dirty > object persistence. The object in question is a list of 3,000 > dictionaries > whose keys and values are short (< 100 character) strings--about 1.5 > megs worth of character data in total. Loading this object from a pickle > using cPickle took so long we assumed something was broken. What happens (besides losing cross-version portability) if you use marshal instead of pickle? From mjackson at wrc.xerox.com Thu Jul 25 08:52:45 2002 From: mjackson at wrc.xerox.com (Mark Jackson) Date: 25 Jul 2002 12:52:45 GMT Subject: Requesting a reference for a book on NNTP References: <30770aa4.0207241752.ace193b@posting.google.com> Message-ID: bogusdrop at myself.com (TuxTrax) writes: > I need to learn how clients query nntp servers for specific messages, > what protocols are involved, how those protocols and commands are > used, syntax involved, authentication methods: in short, I need a book > that will teach me everything I would need to know to write a > newsreader (as far as interfacing with the usenet servers are > concerned), although that is not the project I am embarking on. If you find something better than RFC977 ("Network News Transfer Protocol") and RFC2980 ("Common NNTP Extensions") please let me know. They've been adequate for my purposes (I maintain xvnews, an XView-based newsreader) but I'm sure I'm missing stuff. Beyond that, look at the code for any open-source newsreader or for the Python nntplib module - or, as has been suggested, just use the latter directly. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson What is this endless series of meaningless experiences trying to teach me? - Bruce Eric Kaplan From bokr at oz.net Sat Jul 27 16:03:26 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2002 20:03:26 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 25 Jul 2002 12:51:31 +0200, holger krekel wrote: >Hi Bengt, > >thanks for your nice code samples. Although i had problems reading >code containing my name too often (Signal Overflow :-). >Especially your experiments with putting the execution >of the module-file into a class makes some sense to me. >Below i tried a similar yet different approach :-) > >I really wonder whether there are *any* reasons to have >a distinct ModuleType. What does it offer that a plain >good old (or new) 'class' could not do? > Probably some speed for internal access to named module contents. And write protection for __dict__ itself. Plus you can't just always create a new object on every call to __import__. There is an internal method in moduleobject.c (I only have 2.1 source handy, will have to fix that ;-) --- static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { if (m->md_dict != NULL) return visit(m->md_dict, arg); return 0; } --- which looks like a prime suspect to me, as a reason to have a built-in module type. The dealloc mechanism might be important too. But I think I can imagine a way that you could still get that, and use a custom container (I.e., an instance of an almost arbitrary class). You could add an extra parameter to __import__, which would be the container instance, and the current C moduleobject (with support) would be modified to be able to initialize itself to pass everything through while monitoring for __getattr__/__setattr__ to __dict__ itself (you could conceivably allow write, while doing the right thing inbetween) eliminating the old and setting the new, and module_traverse would know to use the latest user container __dict__. I.e., the C module __getattr__/__setattr__ could potentially keep up with apparent changes of __dict__ itself, since it would be able to intercept a change, though that wouldn't be frequent. A user-friendly interface to this __import__ with the extra parameter might be a modified import statement, with an optional "using myContainerInstance" at the end, e.g., import test using MyContainer() Incidentally, this should allow you to define __call__ in the class whose instance you passed to __import__, with the result of getting a "callable module." Properties too. With the right proxying, you could presumably import builtin modules and have the apparent effect of adding methods and properties etc. Almost like subclassing an instance. But import is a much bigger issue than just the module containers. >Anyway, here is one interesting small experiment ... > Yes, it's interesting, but I really don't think a class is a viable hook-in for __import__. It must not always create a new object, for one thing. My "myImport" class wasn't meant as a hook-in either, despite the name ;-) Just a separate way to do something import-like with class body source. OTOH, it should be possible to write a Python function that could plug in. It looks like imp/imputils were created to help do that, and rexec stuff apparently depends on that. I've not been into that yet. But this should be orthogonal to custom containers (though rexec might want to control use of custom containers). The kind of object surgery after creation done below makes me uneasy ;-) >** start Module.py ** >import __builtin__ > >class Module(object): > oldimporter = __builtin__.__import__ > > def __init__(self, name, globals={}, locals={}, fromlist=[]): A nit, but mutable defaults scare me. They tend to get shared in surprising ways ;-) I would use None and create new instances explicitly instead, like if globals is None globals={} # etc. Also, it's a bit worrisome re-using so many names with builtin meanings ;-) > module = self.oldimporter(name, globals, locals, fromlist) > self.__dict__ = module.__dict__ > > def __getattr__(self, name): > getter = self.__dict__.get('__getattr__') > return getter(name) > >__builtin__.__import__ = Module I think you only want to do this very carefully ;-) > >**end** > >** test.py ** >def __getattr__(name): > print "__getattr__ called with name",name > >import os,sys ^^^^^^ Note the danger here! These imports also get captured by Module. You'd have to be very careful to get the wrapping right. I don't think it's worth taking on the whole job. Better to mod the existing mechanism to use custom containers. >** > >and the sesssion with these experimental stuff: > >>>> import Module # wraps __import__ >>>> import test >>>> test > >>>> test.os > I think I'd rather see but maybe you could fix that with a __repr__ >>>> test.h >__getattr__ called with name h > >I wonder if there are any serious drawbacks of this approach. > Probably ;-) Especially since __import__ doesn't always create new objects, so a class is not a good fit for a direct replacement. Etc. ;-) Regards, Bengt Richter From cliechti at gmx.net Fri Jul 19 12:21:00 2002 From: cliechti at gmx.net (Chris Liechti) Date: 19 Jul 2002 18:21:00 +0200 Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: Johannes Graumann wrote in news:ah9cvk$st at gap.cco.caltech.edu: > Basicely I have two lists, one containing the future string-names > and one containing the values I want to give them. The order is > identical in both. Right now I'm solving this by a dictionary, but > I would really prefer to have straight strings as a result of my > operation. i think i don't understand what you exactly want... maybe you could illustrate you problem with an example of data and how the result should look like or a few lines from the interactive prompt, like: >>> names = ["one", "two", "tree"] >>> values = [1,2,3] >>> dict(zip(names,values)) {'tree': 3, 'two': 2, 'one': 1} chris -- Chris From emile at fenx.com Sun Jul 7 23:38:24 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 08 Jul 2002 03:38:24 GMT Subject: Getting IDLE 0.8 to recognize Python 2.2.1 References: Message-ID: Brad Fonseca > I've upgraded to python 2.2.1 but when I start IDLE it still starts Python > 2.1.1. How do I get IDLE to start Python 2.2 Hard to say without knowing the environment, but I'd say the system is finding the older version in your path first... so, delete the 2.1.1 references from your path? -- Emile van Sebille emile at fenx.com --------- From maxm at mxm.dk Thu Jul 25 10:08:46 2002 From: maxm at mxm.dk (Max M) Date: Thu, 25 Jul 2002 16:08:46 +0200 Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> Message-ID: <3D40066E.2090809@mxm.dk> Alex Martelli wrote: > Therefore, I find your criticism totally unfounded. I beg to differ Sire! To understand the error message you need to understand the implementation of the module. One of the reasons for having modules and encapsulation is to minimize the need to know implementation details. The message "Argument must be a string", while not technically correct, is far easier to understand and in line with the Docs where argument 's' is defined as a string. regards Max M From phd at phd.pp.ru Sun Jul 7 14:12:40 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sun, 7 Jul 2002 22:12:40 +0400 Subject: OT: New job and vacation Message-ID: <20020707221240.A2714@phd.pp.ru> Hello! The company I was working for had been having financial problems and finally was sold to a new investor. I am not going to join the new company and now I am completely free. If someone wants to hire me as a telecommuter please look at my CV (http://phd.pp.ru/My/resume.html mirrored at http://phd.by.ru/My/resume.html and http://phd2.chat.ru/My/resume.html). Tomorrow I am starting to move the domain phd.pp.ru to another server. Hence during next few days you may experince problems contacting me. If your message about job offer, my programs, patches or such bounces - just wait a day or two and retry. After the move I will take a rest for a week or two. I will put all my subscriptions on hold, but I will check my personal mail at least every few days. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jepler at unpythonic.net Mon Jul 8 22:07:00 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 8 Jul 2002 21:07:00 -0500 Subject: Why self? In-Reply-To: <080720021650379803%pecora@anvil.nrl.navy.mil> References: <080720021650379803%pecora@anvil.nrl.navy.mil> Message-ID: <20020708210700.A1771@unpythonic.net> On Mon, Jul 08, 2002 at 04:50:37PM -0400, Louis M. Pecora wrote: > In article , Brian > Quinlan wrote: > > > If the explicit self argument were removed, what would you add to the > > language to differentiate between local and instance variables? > > > > Here's a stab. > > (1) All self variables have to be initialized in __init__. That's just > good practice anyway. They are labeled with self in __init__ otherwise > they are local. In new-style classes, all variables are declared in __slots__. However, this doesn't seem to solve the problem of referring to class attributes (including methods and properties), which can also currently be named using 'self.attr'. A new __metaslots__ or __classslots__ ? Jeff From j-jinkins at usa.net Sun Jul 21 20:55:48 2002 From: j-jinkins at usa.net (Jim Jinkins) Date: Mon, 22 Jul 2002 00:55:48 GMT Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> Message-ID: <3D3B580F.20508@usa.net> Jeff Layton wrote: > Hello, > > If I instantiate a class in a function, > leave the function via a return and then > go back to the same function, will the > instantiation of the class still be there > or is it local to the function so it is > "destroyed"? (Does this make any sense?) > > TIA, > > Jeff > A class defined _and referenced_ only within the function is local. If the function returns the class to a name, that name holds the class definition. You can instantiate objects of the class using the 'class name' returned by the function. Or so says _my_ interpretation of the tutorial. Jim From skip at pobox.com Sat Jul 6 15:07:37 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 6 Jul 2002 14:07:37 -0500 Subject: COCOMO - appropriate for languages like Python? Message-ID: <15655.16377.250899.348691@localhost.localdomain> It's been many years since I've considered software cost estimation models like COCOMO. Is COCOMO appropriate to apply to high-level languages like Python? I believe COCOMO assumes each fully debugged source line of code (SLOC) in any language and for any purpose costs roughly the same amount to produce. The cost savings for languages like Python would come because you have to write so many fewer lines of code to implement the desired functionality. This constant cost per SLOC assumption seems at least marginally invalid to me. For example, writing an extension module which wraps a preexisting C library is generally pretty straightforward (even without tools like SWIG or Pyrex), but is pretty verbose, so COCOMO would tend to overestimate the cost to produce such code. It also seems the clarity of a language's constructs will make a difference. For example, in C I can write if ((c = gets(s)) == EOF) { ... } while in Python, even though I have to express that concept in two lines: s = sys.stdin.readline() if s == "": ... you can argue the Python code is less likely to contain a bug. Together, the cost to create those two (fully debugged) lines of Python code may well be less than the cost to create the one line of C code, not twice the cost of the one line of C code, as COCOMO would estimate it. Are there other (more modern?) cost estimation models which don't assume cost-wise that a SLOC is a SLOC is a SLOC? -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From mhuening at zedat.fu-berlin.de Mon Jul 29 14:23:55 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 29 Jul 2002 18:23:55 GMT Subject: Pmw.MenuBar hotkeys Message-ID: Hi, I seem unable to get the hotkeys to work with Pmw.MenuBar. They should be activated with +hotkey, but nothing happens... When a menu is opened, the hotkeys of the different menu items do work. The problem is only with the hotkeys on the menu bar. Any ideas? Matthias From h_j_fong at hotmail.com Sat Jul 27 15:43:02 2002 From: h_j_fong at hotmail.com (Chris) Date: Sat, 27 Jul 2002 15:43:02 -0400 Subject: wxPython TextCtrl overwriting Message-ID: So, with a couple hints from this group, I've created my first windows application. I have one quick question about improving my program (I'll have more, but I don't like to ask questions till I've exhausted myself trying it first): In my GUI I'm using a fairly standard dirDialog to get a path, with a line for manual entry or the browse button beneath. How do I write the selected path *over* the default text currently in the box. Seems like it should be a one-liner (.replace, .erase, .clear, .overwrite???). Currently I am using .write, which appends it. Essentially I want to start with a default value in the box, allow someone to browse and overwrite, or manually edit the path in the box, and then whatever's in the box when they hit ok, gets passed. ---I have a sizer with manual entry box and browse button: self.dataentry7 = wxTextCtrl(self, ID_DIRcsvstxt, default7, size=(125, -1)) self.button7 = wxButton(self, ID_DIRcsvsbut, 'Browse...') ----Events: EVT_TEXT(self, ID_DIRcsvstxt, self.EvtText7) EVT_BUTTON(self, ID_DIRcsvsbut, self.getDir7) --- And functions: def EvtText7(self, event): global text7 text7 = event.GetString() def getDir7(self,event): dlg = wxDirDialog(self) if dlg.ShowModal() == wxID_OK: global text7 dirname7= dlg.GetPath() self.dataentry7.write(dirname7) text7 = str(dirname7) dlg.Destroy() ---- "text7" is the path that I later pass to my main program. Thanks Chris From rpm1deletethis at nospamfrontiernet.net Tue Jul 23 06:37:03 2002 From: rpm1deletethis at nospamfrontiernet.net (RPM1) Date: Tue, 23 Jul 2002 06:37:03 -0400 Subject: good books References: Message-ID: I agree. "Dave Cinege" wrote in message news:mailman.1027405211.16343.python-list at python.org... > On Tuesday 23 July 2002 2:13, Percy Tambunan wrote: > > what is a good book in python, If i can only afford to buy just one book? > > IMO Python 2.1 Bible, www.hungryminds.com > > -- > The time is now 22:48 (Totalitarian) - http://www.ccops.org/ > > > From mark at mceahern.com Fri Jul 12 15:15:02 2002 From: mark at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 14:15:02 -0500 Subject: switch recipe? Message-ID: In response to a question earlier today, I wrote a function I called make_color_switch: from __future__ import generators def make_color_switch(color1, color2): def color_switch(): i = 0 while True: if i % 2: yield color2 else: yield color1 i += 1 return color_switch It seemed like this could be more generic: from __future__ import generators def make_switch(*args): """Return a generator that loops through args.""" if not args: raise RuntimeError("Missing parameter: args.") def switch(): i = n = 0 while True: i = n % len(args) yield args[i] n += 1 return switch Is switch a bad name for this? Can anyone suggest a better name? Other improvements? What I like about this code is it demonstrates several "advanced" features of Python, all the while retaining (imho) the simplicity and clarity Python is known for: generators nested scopes variable length argument arrays functions as objects Here's sample code that shows it used in the context of the original question: #! /usr/bin/env python from __future__ import generators def make_switch(*args): """Return a generator that loops through args.""" if not args: raise RuntimeError("Missing parameter: args.") def switch(): i = n = 0 while True: i = n % len(args) yield args[i] n += 1 return switch def colorize(s, *colors): switch = make_switch(*colors)() template = "<%(color)s>%(c)s" l = [] for c in s: color = switch.next() l.append(template % locals()) print ''.join(l) colorize("testing", "black", "red", "green", "blue") Is make_switch useful enough to post as a recipe? I didn't search to see whether someone has already made something like this. It seems at once both trivial and reuseful. Cheers, // mark - From zopestoller at thomas-guettler.de Fri Jul 12 05:08:39 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 12 Jul 2002 11:08:39 +0200 Subject: Python for data driven website? References: Message-ID: <3D2E9C97.6060304@thomas-guettler.de> Micah Mayo wrote: > Howdy Folks, > > My company is in the early stages of building a web application for > accountants. ... If you have more layout (html) than logic (programming language) than use php. I don't like to say that, because python is the better language. But zope and webware are not that easy. Except: If there will be a lot of people how edit the site use Zope and ust dtml and zpt through the web If you have more logic: Use pyhton's CGI-Module. Search the web for some examples. There is trick with a small wrapper-script which contains only a try: catch clause so that errors in you python will result be written to the browser (Otherwise your stacktrace gets lost) If you don't want to use a relational database use Zope and write a python product. But that's interesting but not good for newbies. Hint: A Zope python product is totaly different from a through the web created site. thomas From h.baumgartl at chello.NOSPAM.nl Wed Jul 17 09:11:00 2002 From: h.baumgartl at chello.NOSPAM.nl (Henry Baumgartl) Date: Wed, 17 Jul 2002 13:11:00 GMT Subject: string encoding - how to make it work References: Message-ID: "Martin v. L?wis" schreef in bericht news:j4heiyfu0e.fsf at informatik.hu-berlin.de... > No. You have to know what encoding the terminal uses. Some terminals > have no programmatic way to find out. So this isn't just possible in > Python; it is impossible in any language. > > Regards, > Martin OK Still, what i can't get my head around is that when entering short cut generated extended characters into, for instance, IDLE it works without any problem. It is only when i try to save it that the Error is raised. Kind Regards, Henry Please remove NOSPAM. from my e-mail address when answering directly to me. From mirvine at compsoc.com Sat Jul 13 19:55:45 2002 From: mirvine at compsoc.com (mirvine555) Date: 13 Jul 2002 16:55:45 -0700 Subject: dictionary confusion... Message-ID: <9ef8bd6b.0207131555.73b82f57@posting.google.com> Hi, I'm trying to use dictionarys to store a table. The table looks like: Data mc1 mc2 mc3 hot 1:35 1:22 . cold . . 7:43 dry 10:25 10:38 4:17 and I'm trying to put it into a dictionary something like: >>> statusTable={'mc1':{'hot':'1:35', 'cold':'.', 'dry':'10:25'}, 'mc2':{'hot':'1:22', 'cold':'.', 'dry':'10:38'}, 'mc3':{'hot':'.', 'cold':'7:43', 'dry':'4:17'}} >>> print statusTable {'mc3': {'dry': '4:17', 'hot': '.', 'cold': '7:43'}, 'mc2': {'dry': '10:38', 'hot': '1:22', 'cold': '.'}, 'mc1': {'dry': '10:25', 'hot': '1:35', 'cold': '.'}} I want to do this so I can look up values like this: >>> statusTable['mc3']['cold'] '7:43' >>> statusTable['mc2']['dry'] '10:38' >>> I've made a feeble effort, as listed below, but I'm new to python so I'm a bit stuck. If you have any ideas on how I can get this to work I would appreciate your help. TIA, Mark Irvine import string def makeStatusTable(data): statusTable={} index=0 lines=string.split(data,'\n') header=string.split(lines[0])[1:] for mc in header: index+=1 for line in lines[1:]: vals=string.split(line) status=vals[0] time=vals[index] print "vals: " + str(vals) + "\n" statusTable[mc]=mc statusTable[mc]={status:time} return statusTable data="""Data mc1 mc2 mc3 hot 1:35 1:22 . cold . . 7:43 dry 10:25 10:38 4:17""" t=makeStatusTable(data) print t From jerf at jerf.org Sat Jul 27 01:30:28 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 27 Jul 2002 05:30:28 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: On Fri, 26 Jul 2002 16:18:56 -0500, Alex Martelli wrote: > Robb Shecter wrote: > >> But to really answer you - I like lambdas and think lambdas can add >> clarity because their scope directly reflects their 'scope'. (Make >> sense?) > > Sorry, not to me. Take a typical bug sometimes posted here, such as: > > for word in 'fee fie foo fum'.split(): > Button(frame, command=lambda: print word) > > The poster is typically nonplusses that all buttons print 'fum'. Speaking as one who recently posted this, what's the alternative? for word in 'fee fie foo fum'.split(): def printThing(): print word Button(frame, printThing) doesn't work any better, you still need for word in 'fee fie foo fum'.split(): def printThing(word = word): print word Button(frame, printThing) Lambda wart, or just scoping wart in general? (And I'll still take the lambda form; the def statement feels wrong here.) From edream at tds.net Sat Jul 13 20:41:08 2002 From: edream at tds.net (Edward K. Ream) Date: Sun, 14 Jul 2002 00:41:08 GMT Subject: tk/tkinter radiobutton in grid bug? References: <3D2EF186.4CB25463@tds.net> Message-ID: <3D30C89E.25623C00@tds.net> > This _seems_ to work do you have an example that does not? Not anymore. I got rid of the radio buttons, as well as the grids :-) Thanks for this reply. My example had grids within grids, and mixed the packer into the soup. So it may not have deserved to work... Edward > import Tkinter > root=Tkinter.Tk() > variable=Tkinter.StringVar() > l=Tkinter.Label(root, text='On or Off?').grid(row=0, col=0) > rb1=Tkinter. Radiobutton(root, variable=variable, value='On', text='On') > rb1.grid(row=0, col=1) > rb2=Tkinter. Radiobutton(root, variable=variable, value='Off', text='Off') > rb2.grid(row=0, col=2) > rb2.select() > > root.mainloop() -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From gerhard.haering at gmx.de Tue Jul 2 21:41:58 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 3 Jul 2002 03:41:58 +0200 Subject: GoTo considered missing In-Reply-To: <002901c2222c$100a2180$289dfea9@t9k2t3> References: <002901c2222c$100a2180$289dfea9@t9k2t3> Message-ID: <20020703014157.GA3084@lilith.my-fqdn.de> * Harvey Frey [2002-07-02 17:53 -0700]: > [...] What is the approved Python method for getting from the bottom > of a set of nested loops to the top? [...] Exceptions. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 15.2 ?C Wind: 2.4 m/s From rajarshi at presidency.com Thu Jul 18 16:20:45 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Thu, 18 Jul 2002 16:20:45 -0400 Subject: replacing a part of a string using a regexp Message-ID: Hi, I'm trying to parse some HTML tags and I have the following situation: a line contains:
And I want to replace the url and make the line: Using re.sub I can substitute the whole string bewteen quotes, but the substituion needs to use the string that is *found* in the quotes. How can I access the matched portion in a re.sub() expression? TIA From chandan_mathur at hotmail.com Sat Jul 6 00:05:59 2002 From: chandan_mathur at hotmail.com (chandan) Date: 5 Jul 2002 21:05:59 -0700 Subject: win32com and internet explorer References: <3d235b64$1@post.usenet.com> <6vZU8.409778$cQ3.28013@sccrnsc01> Message-ID: alrite..., it works.., i don't really need the header part.. so i didn't bother. Had some trouble with saving the file to disk..., but eventually found out that i had to convert them to unicode and then ignore special characters. this is what i have so far... import win32com.client,time,string # Get the browser object ie = win32com.client.DispatchEx("InternetExplorer.Application") ie.Visible = 0 ie.Navigate("http://www.google.com") time.sleep(5) text = ie.Document.body.innerHTML text = unicode(text) text = text.encode('ascii','ignore') filename = "c:/test.html" output_file = open(filename,'w') output_file.write(text) output_file.close() ie.close() But i am stuck with the submiting username and password through the form.. i tried to adapt your code to my https..., this is what i found out.. i am pasting the HTML source from the login page that redirects it to https (http://www.fool.com/Login.asp") :
in " self.currColumn=0 self.rowData=[] def end_tr(self): self.in_tr=0 len_rd=len(self.rowData) if len_rd==0: if self.table_header: raise 'Parse Error: Two rows with no
User Name or Email Address:
Password: ...and so on I am guessing, name:value pairs are sent in the post request.. and therfore.. my code must look something like this.. ie.Navigate("http://www.fool.com/login.asp") doc = ie.Document doc.forms(0).uf.value = "username" #from name = "uf" refer HTML above time.sleep(1) doc.tcforms.gf.value = "Password" #from name = "gf" refer HTML above time.sleep(1) doc.forms(0).submit() # Sends the info. Am i doing this right? i get some crazy exception THanx for your time and help :) Chandan P.S , what does HTH mean? Also, the links to MSDN give me 404 error... "Jose Correia" wrote in message news:... > Don't know how to get the entire page saved to disk, but hopefully this gets > you a little closer to your goal if you're trying to get at the info on the > page. > > >>> from win32com.client import Dispatch > >>> ie = Dispatch("InternetExplorer.Application") > >>> ie.Navigate("http://www.google.com") > >>> ie.Visible=1 > >>> ie.Document.body.innerHTML > '
\015\012 > ... this gives you all the html between the BODY tag in a string, you just > don't get the Header bit. I'm sure there's a way to get it all but I > haven't been able to find it yet. If you find it let me know. > > If you're trying to submit info on the page you need to look at the source > to see the object names. > For example, a secure site I use has a form (called frmLogin) to enter an > account number (field called: Account) > and password (field called: Password). > > The code I use looks like this: > doc = ie.Document > doc.forms(0).Account.value = "987654321" # Referenced as the first (0 > based count) form on the page. > sleep(0.5) # Otherwise it seems to run too fast > and get confused :-( > doc.frmLogin.Password.value = "some_password" #Referenced by the form's > name in the HTML. > sleep(0.5) > doc.forms(0).submit() # Sends the info. > sleep(1) > > You can check if it's finished processing by checking if > ie.ReadyState == 4 and > doc.readyState == "complete" > > For further info on the MS stuff try: > http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/ref > erence/objects/obj_document.asp > > and > http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/webbrows > er/reference/ifaces/IWebBrowser2/IWebBrowser2.asp > > > HTH, > > Jose From opengeometry at NOSPAM.yahoo.ca Tue Jul 2 18:15:21 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 2 Jul 2002 22:15:21 GMT Subject: Splitting Text files References: <%XnU8.4057$aJ4.853781@news20.bellglobal.com> Message-ID: Ken Seergobin wrote: > Thanks. Csplit makes the task much easier! The extraction of the > critical data lines plus relevant fields was never an issue. With your > suggestions though I can now write batch or shell scripts to do most of > the work. However, python offers unlimited possibilities when > analysing/visualizing the data. As such, I was looking for an easy way > to abandon the use of mulitple unix(like) tools. "Right tool for the right job" is the key insight (as Guido would say :-) > > Part of what I was looking for was the ability to use the root of the > bitmap name as the output name. I can extract the bitmap name, but don't > know how to redirect data to a file with a similar name (e.g., > bitmap1.txt). In shell, out=`egrep 'bitmap[0-9]\.txt' ` command ... > $out In Python, out = "..." f = open(out, 'w') f.write(...) -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From tjreedy at udel.edu Tue Jul 9 10:15:49 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Jul 2002 14:15:49 GMT Subject: Splitting a string every 'n' References: Message-ID: wrote in message news:mailman.1026219434.22644.python-list at python.org... > > What is the idiomatic way to split a string into a list > containing 'n' character substrings? I normally do > something like: > > while strng: > substring = strng[:n] > strng = strng[n:] > You are asking two different questions in you text and code: 1. How generate explicit list of successie length n substrings (slices)? 2. How process successie length n substrings (slices), (which can then be tossed)? Second is easier than first: both require attention to possibility of remainder of length less than n. ... > Any better ideas, short of manually indexing through? What, pray tell, is wrong with doing the simple obvious thing that you can program correctly in a minute or two? > Is there something like: > > for substring in strng.nsplit(): > Note that this says that (2) rather that (1) above is your question. For 2.2+, write a generator that manually indexes thru sequence, returning successive slices. A second param could determine whether a short tail is returned or suppressed. Terry J. Reedy From andreas at kostyrka.priv.at Tue Jul 30 16:52:01 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 30 Jul 2002 22:52:01 +0200 Subject: How to detect the last element in a for loop In-Reply-To: <49S09.13011$9U4.7618@nwrddc01.gnilink.net> References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: <1028061882.5100.21.camel@vaio2> Am Son, 2002-07-28 um 15.16 schrieb Tom Verbeure: > > > > For a simple solution, how about: > > > > for a in myList[:-1]: > > do_stuff(a) > > special_stuff(myList[-1]) > > No, I still want to do 'do_stuff' for the last element also. This may be, > say, 10 lines of code. Too much to duplicate it outside the loop, not > enough for a separate function... Then do this: for a in myList: do_stuff(a): if myList: special_stuff(myList[-1]) Andreas From fakeaddress at nowhere.org Tue Jul 2 20:57:17 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 03 Jul 2002 00:57:17 GMT Subject: A problem with urllib References: <3D1FD7A1.F265FC8E@engcorp.com> <3D2163E3.3050605@nowhere.org> Message-ID: <3D224BFF.9090409@nowhere.org> Aki Niimura wrote: > I tried the script both from Solaris and from Windows, but I got the > same result. Ah, the base64.encodestring() includes a "\n" at the end of the output. In the version below, I strip it off. I've tested this with the current firmware version, and the "good" case works, while the "bad" case triggers the Linksys bug. --Bryan import socket import base64 for demo in ("good", "bad"): request_line = "GET /Status.htm HTTP/1.0\r\n" auth_header = ("Authorization: Basic %s\r\n" % base64.encodestring(":admin").strip()) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.1.1", 80)) if demo == "good": s.send(request_line + auth_header + "\r\n") else: s.send(request_line) s.send(auth_header + "\r\n") s.shutdown(1) print s.recv(99999) s.close() print "\n\n\n\n" From pinard at iro.umontreal.ca Sun Jul 7 18:12:15 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 07 Jul 2002 18:12:15 -0400 Subject: `~/.pythonrc' `from __future__ import' Message-ID: Hello, people. Here is a strange problem with `from __future__ import', maybe you can help me understand it. This is with Python 2.2.1. Given `export PYTHONSTARTUP=/home/pinard/etc/pythonrc', and that `pythonrc' file starting with: ----------------------------------------------------------------------> from __future__ import division print 3/4 ----------------------------------------------------------------------< then I interactively get: ----------------------------------------------------------------------> 18:01 0 pinard at titan:~ $ python Python 2.2.1 (#1, Apr 29 2002, 14:27:21) [GCC 2.95.3 20010315 (SuSE)] on linux2 Type "help", "copyright", "credits" or "license" for more information. 0.75 >>> 3/4 0 >>> from __future__ import division >>> 3/4 0.75 ----------------------------------------------------------------------< I wonder why I have to re-execute `from __future__ import divsion' interactively before it works. How should I proceed to activate this option once and for all for interactive applications? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From jubafre at zipmail.com.br Wed Jul 10 09:49:21 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Wed, 10 Jul 2002 10:49:21 -0300 Subject: =?iso-8859-1?Q?askopenfilename=3F=3F=3F=3F=3F?= Message-ID: <3D2C2D7A000005B4@www.zipmail.com.br> i don?t know how to use a filetypes option of askopenfilename, somebody can help? askopenfilename(filetypes=???) Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From andreas at kostyrka.priv.at Fri Jul 26 16:51:19 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 26 Jul 2002 22:51:19 +0200 Subject: calendar lameness! In-Reply-To: <3D3C0A21.1EB8A671@anansispaceworks.com> References: <3D3C0A21.1EB8A671@anansispaceworks.com> Message-ID: <1027715640.10236.200.camel@vaio2> Am Mon, 2002-07-22 um 15.35 schrieb Terry Hancock: > "calendar" is pretty neat -- except it has pretty > annoying arbitrary limits on the date: > > 1900-1/1 to 2038-1/18 Well, this is not that arbitrary. Considering the fact that the "calendar" wasn't standardized completly the beginning of the 20th century. So anything that goes that far back would have to specify the country (or even the substate in the country) to be precise. And that doesn't even take into account that the French Revolution tried to do away with the 7-days week, ... > I can see that this is adequate for a business > planner, but for historical or astronomical uses, > it's really inadequate. (e.g. "What day of the > week was the US Declaration of Independence signed > on?" I'm sure I could look that up, but gee it > would've been nice to just type: > > calendar.weekday(1776, 7, 4) calendar.weekday(1776,7,4,"USA") > Actually, it looks like maybe it's "mktime" that > is the limiter here (?). How hard would it be to > replace that call with something smarter? It seems > like Python longs would make it unnecessary to > have such arbitrary limits. Well, it's not that much a limit of calculating power, it's more that the subject of calendars is difficult. By using the underlying C library implementation the Python implementers don't have to think about these political and religious considerations. ;) Andreas From amuys at shortech.com.au Tue Jul 9 21:46:44 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 9 Jul 2002 18:46:44 -0700 Subject: COCOMO - appropriate for languages like Python? References: <15655.16377.250899.348691@localhost.localdomain> Message-ID: <7934d084.0207091746.3ec0f89a@posting.google.com> "James J. Besemer" wrote in message news:... > From a management standpoint, your strategy should be to always strive to hire > the very best people and to break projects into moderate sized, easily handled > chunks. > > From a schedule estimation standpoint, LOC (however you choose to count them) > appears to be a pretty good estimator to use for a fixed staff and fixed project > sizes. How the prediction varies as you change staff or project sizes is > something you'll have to measure or guess at yourself. At least COCOMO research > gives you some idea how the curves are shaped. > Do you have any references where I could follow up on this myself? Andrae From tim.one at comcast.net Tue Jul 30 18:32:43 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 30 Jul 2002 18:32:43 -0400 Subject: global interpreter lock not working as it should In-Reply-To: <200207302156.RAA31962@test-area.com> Message-ID: [anton wilson] > I think I understand what you mean. I assumed that python should > block and allow others to work every x byte codes on EVERY platform. I > see that that's a wrong assumption. It wasn't our intent, no -- we expect the platform thread library to do switching when it thinks it's best to do so. On Windows, for example, threads are very happy to switch frequently, but then Windows is a thread-happy OS geared toward interactive GUIs. Linux is more reluctant. For a while, it used to take a stick of dynamite to convince Solaris to switch threads. Etc; the pragmatics of various thread implementations aren't something Python wants to second-guess. I'll note one other odd thing: sys.setcheckinterval() exists in Python so you can change how often Python *offers* to switch threads. Production systems on Linux that care almost always boost it, not lower it; for example, Zope boosts it to 120, because Linux was switching threads "too often" under the default setting for its uses of threads. Thread switches incur real costs too. From gerhard.haering at gmx.de Fri Jul 19 00:30:23 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 19 Jul 2002 06:30:23 +0200 Subject: Tkinter vs. wxPython In-Reply-To: References: Message-ID: <20020719043023.GA4568@lilith.my-fqdn.de> Hi d2002xx, if that is indeed your real name. * d2002xx [2002-07-18 21:08 -0700]: > > My question is this: is there any compelling reason I shouldn't just go > > with Tkinter instead? I work (for now) exclusively on Win32 boxes, by > > the way. > > Just compare the number of widgets in wxPython and Tkinter, you will > find out tkinter is almost useless. I'm wondering why python doesn't > use wxPython (or PyQT) as default GUI. I personally am currently playing with wxPython, too. But it has its share of problems, at least the GTK version of it. It can also be a bitch to build on Unix, especially if you don't read the fine README and INSTALL.unix docs ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From shagshag13 at yahoo.fr Tue Jul 9 10:30:57 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 16:30:57 +0200 Subject: sorting many arrays from one... References: <_fCW8.48028$Jj7.1333638@news1.tin.it> Message-ID: "Alex Martelli" > All clear so far? ok, thanks to you, s13. From gyromagnetic at excite.com Wed Jul 17 09:09:00 2002 From: gyromagnetic at excite.com (gyromagnetic) Date: 17 Jul 2002 06:09:00 -0700 Subject: better 'splice' function Message-ID: <4620daca.0207170508.7820b059@posting.google.com> Hi, I have written a function that essentially 'splices' together a number of tuples in a list, and I would appreciate any suggestions that you might have on how to make the code or algorithm better. Each tuple in the input list comprises three strings, e.g. ('A','k1,'B'). The splice function should exhaustively try to match the 'end' (last element) of one tuple with the 'beginning' (first element) of another (eliminating the duplicate string) to create the longest tuples possible. For instance, if I had as a list mylist = [('B','k8','C'),('B','k3','D'),('A','k4','E'), ('Z','k5','F'),('F','k3','G'),('A','k1','B'), ('G','k2','H'),('C','k2','I')] splice_tuples(mylist) should return [('Z', 'k5', 'F', 'k3', 'G', 'k2', 'H'), ('A', 'k4', 'E'), ('A', 'k1', 'B', 'k3', 'D'), ('A', 'k1', 'B', 'k8', 'C', 'k2', 'I')] As another example, mylist = [('B','k8','C'),('B','k3','D'),('A','k4','E'), ('Z','k5','F'),('F','k3','G'),('A','k1','B'), ('G','k2','H'),('C','k2','I'),('H','k6','A')] splice_tuples(mylist) should return [('A', 'k4', 'E'), [('Z', 'k5', 'F', 'k3', 'G', 'k2', 'H', 'k6', 'A', 'k1', 'B', 'k8', 'C', 'k2', 'I'), ('Z', 'k5', 'F', 'k3', 'G', 'k2', 'H', 'k6', 'A', 'k1', 'B', 'k3', 'D'), ('Z', 'k5', 'F', 'k3', 'G', 'k2', 'H', 'k6', 'A', 'k4', 'E')] The same symbol will not appear as the first and last elements of a tuple in the input list. Also, there won't be 'loops' in the input data; input lists like [('A','k1','B'),('B','k2','C'),('C','k3','A')] won't happen. I'd appreciate any advice you may have on how to improve the (admittedly klunky) code below. I'm using Python v2.2. Thanks. -Brad #------------------------------------------------------------------- def splice_tuples(rlist): spliced_list, spliced_dict, mdict = [], {}, {} map(mdict.setdefault,rlist,[1]*len(rlist)) fdict, ldict = {}, {} spliced_dict = {} for item in rlist: t0,t2 = item[0],item[-1] if fdict.has_key(t0): if not item in fdict[t0]: fdict[t0].append(item) else: fdict[t0] = [item] if ldict.has_key(t2): if not item in ldict[t2]: ldict[t2].append(item) else: ldict[t2] = [item] def splice(ltup1,ltup2): if not ltup1 or not ltup2: return [] ltup = [] for t1 in ltup1: for t2 in ltup2: if t1[0] == t2[-1]: tup = t2 + t1[1:] if tup not in ltup: ltup.append(tup) if t1[-1] == t2[0]: tup = t1 + t2[1:] if tup not in ltup: ltup.append(tup) return ltup while mdict: cur_t0 = mdict.keys()[0] del mdict[cur_t0] rcur, pcur = cur_t0[0], cur_t0[-1] new_t0 = [] if ldict.has_key(rcur): new_t0 = splice(ldict[rcur],[cur_t0]) map(mdict.setdefault,new_t0,[1]*len(new_t0)) if fdict.has_key(pcur): new_t0 = splice(fdict[pcur],[cur_t0]) map(mdict.setdefault,new_t0,[1]*len(new_t0)) if not new_t0: spliced_dict[cur_t0] = 1 spliced_list = spliced_dict.keys() return spliced_list From andreas at kostyrka.priv.at Tue Jul 30 05:34:24 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 30 Jul 2002 11:34:24 +0200 Subject: python class question In-Reply-To: References: Message-ID: <1028020116.1314.32.camel@vaio2> Am Don, 2002-07-25 um 20.38 schrieb Chris Liechti: > > class xrml(SimpleItem.SimpleItem): > > def init_db(self): > > try: > > dbc = getattr(self, connection) > > why not: > dbc = self.connection Because this is eqivalent to dbc=getattr(self,"connection") > > > > Now I tried to modify the last line as follows: > > self.DB = dbc() > > and getting a very strange error (Error Type: UnpickleableError > > Error Value: Cannot pickle objects). > > don't know Zope but it look like that it uses pickle to store your instaces > and the DB object cannot be picked. thats probably because the connection > to a database cannot be stored, it must be terminated and rebuild, but > thats doesn't seem to be supported by the db object. Well, Zope does use pickle to serialize the objects in ZODB. You could try to use self._v_DB=dbc() Explanation: attributes starting with _v_ are not stored. Basically, in every of your methods you would need a check like: if not hasattr(self,"_v_DB"): self.reconnectDB() before using self._v_DB. This way your connection stays alive as long the object is active in memory. And when it gets reloaded, the db connection gets restarted. Andreas From dman at dman.ddts.net Tue Jul 9 23:54:28 2002 From: dman at dman.ddts.net (Derrick 'dman' Hudson) Date: Tue, 9 Jul 2002 22:54:28 -0500 Subject: How to grab a part of web page? In-Reply-To: <3D2B6810.13895.8A3A7A@localhost> References: <3D2B6810.13895.8A3A7A@localhost> Message-ID: <20020710035428.GB27035@dman.ddts.net> On Tue, Jul 09, 2002 at 10:47:44PM +0200, A wrote: | Hi, | Is it possible to download only a part of web page? | Say I need to find out an information about a customer that starts | at 1500 byte position and ends at 2000 byte position. If the whole | page has about 100 kb it seems to me waste of time to load all the | page. | What is the best, yet easy, solution? | Is it possible to use httplib or necessary socket module? Depending on the HTTP server at the other end, you _may_ be able to request that the document starts at a certain byte position. Older servers definitely won't support that feature. You can read up on it in the RFCs that define HTTP/1.1. I don't know much about it myself other than applications will call it "resuming" a download. Then you could just drop the connection when you've seen as much data as you want. You can probably do the first part with the httplib module -- I think it lets you specify "extra" headers to add. I don't think you can make it kill the connection, though. In any case, depending on where you are and where you download the data from, 100kb could take less than a second to transfer, and the gain of not transfering the whole thing won't be noticeable by the user. -D -- The nice thing about windoze is - it does not just crash, it displays a dialog box and lets you press 'ok' first. http://dman.ddts.net/~dman/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 248 bytes Desc: not available URL: From hancock at anansispaceworks.com Wed Jul 3 19:00:43 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 03 Jul 2002 16:00:43 -0700 Subject: [OT] What is Open Source? References: <20020704095101.29618.29172.Mailman@mail.python.org> Message-ID: <3D23821B.D1C54C06@anansispaceworks.com> > Paul Rubin > I think Clark was using contract in a metaphorical sense, describing a > deal made with authors on one side, and society as a whole on the > other. In what's called the "copyright bargain", society agrees to > grant limited temporary monopolies, in exchange for increased > "progress in science and the useful arts". As in "social contract" -- yes, I think that certainly makes sense. > There is some really terrific reading on the legal history of > copyright in the Amicus Curiae briefs to Eldred vs. Ashcroft linked > from . If you're not aware, Eldred > vs. Ashcroft is a case currently before the Supreme Court that aims to > get the most recent copyright extension (Sonny Bono Copyright Term > Extension Act, passed in 1998 by Disney lobbyists trying to stop > Mickey Mouse from ever entering the public domain, and extending all > copyrights by 20 years) thrown out on the grounds that it doesn't > promote progress. I especially recommend Malla Pollack's brief which > is short and forceful. Interesting. I'm basically at ground-zero on this sort of stuff (I'm in Los Angeles), so it's nice to keep alert. Seems to me that we'd have been better off if Copyright in the US had stayed in its 1977 incarnation. Of course, the excuse at the time was conforming to international convention, something we're usually accused of not doing (e.g. *still* not using metric for much). again. > For patents, Fritz Machlup's 1958 "Economic Review of the Patent > System" is terrific, but I don't know if it exists online. It's a > report to the Subcommittee on Patents, Trademarks, and Copyrights of > the Senate Judiciary Commitee, 85th Congress 2d Session. One of these > days I'll get a hardcopy and scan it. Some excerpts are here: > > http://swpat.ffii.org/papri/machlup58/index.en.html Interesting. I read this page though I haven't had a chance to follow the links yet. I'm pretty much of the opinion that software patents are just evil, already. But I'm increasingly thinking that patents *in general* are obsolete, too. It seems to me that time-to-market has shrunk so much that other protections such as trade-secret or mere market position are entirely sufficient to protect innovation, and that the damage caused by blocked patents and legal disputes are a serious hinderance to progress, especially by smaller organizations, which are more intrinsically inclined to innovate. So on balance, I think they do more damage than good. But that's an unscientific opinion -- would I be able to find any evidence to back up the idea? I can see that some of the links on the page above *might* help, but it's a very entrenched idea -- I'll probably need all the ammunition I can get to convince anyone. Not being too aware of the international legal landscape, I also wonder if there are countries who've had any success at avoiding these kinds of traps. My impression is that excessively closed "intellectual property" is an international problem, not just a US problem (though apparently few countries recognize the software patent). The thing is, I have a group of people I'd like to persuade who are, I think, very keenly (but IMHO foolishly) attached to patents. Also, in the absence of abolishing patents (I wish), I'm looking for a suitable "patent-left". I understand the W3C has done some work on this (I remember discussion of "RAND" patent agreements (not to be confused with the corporation of the same name), though I think that was the "bad" example. I also recall this being a pretty controversial topic, especially when the rtlinux patent was filed. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From chris.gonnerman at newcenturycomputers.net Fri Jul 5 01:26:29 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 5 Jul 2002 00:26:29 -0500 Subject: Is Python growing? References: <3D1D3D34.6080001@hotmail.com> <3D22263A.8090007@hotmail.com> <3D24F4D1.D136D730@hotmail.com> Message-ID: <005101c223e4$86718f20$0101010a@local> ----- Original Message ----- From: "scott" > Gerhard H?ring wrote: > > > > * scott [2002-07-02 22:16 +0000]: > > > Gerhard H?ring wrote: > > > [help builtin only available in Python 2.2 or later] > > > > > > You are mistaken Gerhard. 2.1.1 (Activestate on NT4) is demonstrated > > > below: > > > > > > bash-2.02$ python > > > ActivePython 2.1.1, build 212 (ActiveState) > > > Python 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32 > > > Type "copyright", "credits" or "license" for more information. > > > Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman > > > > It's either ActiveState or your Alternative ReadLine that's installing > > pydoc.help as a builtin. In the standard Python 2.1.x, it isn't there. > > > > Gerhard The Alternative Readline is my code, and it doesn't do squat with pydoc.help. FWIW. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From charles_mantha at hotmail.com Sun Jul 7 19:27:50 2002 From: charles_mantha at hotmail.com (Charles Mantha) Date: Sun, 7 Jul 2002 19:27:50 -0400 Subject: Why is it crashing? (newbie) References: Message-ID: <%34W8.1729$Qt6.474190@wagner.videotron.net> got it working : menu() menu_choice = 0 while menu_choice <= 3: try: menu_choice = int(raw_input("Choose one of the options: ")) if menu_choice == 1: run_test(get_questions()) break elif menu_choice == 2: print get_questions() elif menu_choice == 3: raise SystemExit except ValueError: print "That is not a number." "MontrezVosSeins" > > Oeps, sorry about my 2 posts, didn't know it took 3h to 9h > > > maybe this should do it, > > > > menu() > > menu_choice = input("Choose one of the options: ") > > if menu_choice == 1: > > run_test(get_questions()) > > elif menu_choice == 2: > > ... > > elif menu_choice == 3: > > print "Byee" > > else: > > print "Whoops, illegal choice, try again." From ls2312 at netcom.com Wed Jul 10 17:30:01 2002 From: ls2312 at netcom.com (Lowel Stern) Date: Wed, 10 Jul 2002 14:30:01 -0700 Subject: php function "addslashes" / "removeslashes" in python References: <%RKW8.47006$n4.11323296@newsc.telia.net> Message-ID: On Wed, 10 Jul 2002 00:04:11 GMT, "Fredrik Lundh" wrote: >Lowel Stern wrote: > >> Does anyone know if this exists already? > >if you're doing database, you really should learn to use bound >parameters... > I don't belive that MySQL can use that yet. >but if you insist, this might be a pretty good approximation: > >import re > >def addslashes(string, sub=re.compile(r"[\\\"']").sub): > def fixup(m): > return "\\" + m.group(0) > return sub(fixup, string) > >def removeslashes(string, sub=re.compile(r"(?s)\\(.)|\\").sub): > def fixup(m): > ch = m.group(1) > if ch is None: > raise 'Parse Error: backslash at end of string' > if ch not in r"\\\"'": > raise 'Parse Error: unsupported character after backslash' > return ch > return sub(fixup, string) > > > Thanks for the regx stuff, I'm now testing it Lowel From max at alcyone.com Tue Jul 9 19:17:15 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Jul 2002 16:17:15 -0700 Subject: A better self References: Message-ID: <3D2B6EFB.4DA9A4DB@alcyone.com> David LeBlanc wrote: > I notice that in every discussion of self, there's always a '.' in > there. > So, why not make a leading '.' mean self? AFAIK, it's otherwise > currently > illegal. The only drawback that I can think of is that it's less > visible as > a first argument for class defs. > > class foo(): > def __init__(., me, me2, me3) > .a = me > .b = me2 > .c = me3 > def fee(.) > print .a, .b, .c > def bar(.) > .fee() This doesn't totally revolt me, but I would prefer that the "self" argument still be an explicit self: def __init__(self, me, me2, me3) ... so that the notation `.attribute' is just a shortcut for `self.attribute'. Having the "self" argument written as . suggests that accessing an attribute in it should involve an extra space, e.g. `..attribute' which is clearly not what you meant. `self' as the name of that first argument is already so entrenched it's really hard to come up with reasonable arguments about replacing it. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From CousinStanley at HotMail.com Thu Jul 11 10:46:23 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Thu, 11 Jul 2002 07:46:23 -0700 Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> Message-ID: || ... || Does someoone know an editor for editing hierarchical text data ? || ... Thomas ... You might check out TreePad ... http://www.treepad.com/ They also offer a free version called TreePad Lite ... Cousin Stanley From jolsen at mailme.dk Fri Jul 5 05:36:25 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 5 Jul 2002 02:36:25 -0700 Subject: Why self? Message-ID: Why is it necessary to use a "self" argument to class methods in python? To me it seems a bit like doing object oriented programming in C... Why not make it implicit like "this" in C++? I do not find it usefull that I can give it my own name. So, is it just legacy or is there a reason for this convention? Cheers Jesper From b.hall at irl.cri.nz Tue Jul 30 17:25:02 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Wed, 31 Jul 2002 09:25:02 +1200 Subject: A generic question: idiom for a paramterized base class? Message-ID: <3D47042E.33823879@irl.cri.nz> I would like to know if there is a Python idom to elegantly solve the following problem. I have a base class that needs to instantiate generic classes that are actually derived from it. In C++ this can be achieved by passsing the derived class as a template parameter to the base class (something like: class Derived : public GenericBase { ... }; ) In terms of Python, this is my problem. The following module works fine: ############ example.py ########### class GenericBase(object): def __iadd__(self,other): return TAdd(self,other) # Problem!! def __add__(self,r): return GenericBase.__iadd__(self,r) def __radd__(self,l): return GenericBase.__iadd__(l,self) # One type of TAdd: class TAdd(object,GenericBase): def __init__(self,l,r): print "TAdd instance" class TNode(object,GenericBase): def __init__(self): print "TNode instance" ############################ You can use to to do something like: >>> import example >>> x = example.TNode() TNode instance >>> y = example.TNode() TNode instance >>> t = x + y TAdd instance However, the first class, GenericBase, is actually one that I need to reuse in a number of different situations, each with different TAdd definitions! What can I do? If I put the GenericBase in a module of its own (base.py) and import it into example.py then the following results: >>> x = example.TNode() TNode instance >>> y = example.TNode() TNode instance >>> t = x + y Traceback (most recent call last): File "", line 1, in ? File "base.py", line 5, in __add__ return GenericBase.__iadd__(self,r) File "base.py", line 3, in __iadd__ return TAdd(self,other) # Problem!! NameError: global name 'TAdd' is not defined The answer would appear to be to modify 'import' so that the local namespace for modules base and example are the same. Is this reasonable? Can it be done? From shalehperry at attbi.com Tue Jul 30 18:19:07 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 30 Jul 2002 15:19:07 -0700 (PDT) Subject: A generic question: idiom for a paramterized base class? In-Reply-To: <1028067021.578.988.camel@lothlorien.colorstudy.net> Message-ID: > > That might do what you want. To me, though, the whole thing seems vague > and maybe there's another approach that avoids some of these > complexities. > indeed ugly hierarchies often indicate to little or too much thought. From p.magwene at snet.net Sat Jul 13 17:27:21 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 13 Jul 2002 21:27:21 GMT Subject: structs in python References: Message-ID: On Sun, 07 Jul 2002 00:12:00 -0400, Kevin O'Connor wrote: > It would be useful if there were a simple way of declaring a class with > only member variables (and no methods); an object more akin to a C > struct. > > What if a syntax like the following were permitted: >>>> p = ( .x = 10, .y = 11, .color = 'blue') I often find myself doing something similar to the following (usually when I want to return multiple things from a function) >>> class Struct: ... pass ... >>> p = Struct() >>> p.x = 10 >>> p.y = 11 >>> p.color = 'blue' That's slightly more verbose than you're proposed syntax but doesn't usually feel to onerous (especially since you only have to declare the Struct class once). If you like everything on one line you could do: >>> p = Struct(); p.x = 10; p.y = 11; p.color = 'blue' --Paul From gerhard.haering at gmx.de Mon Jul 15 13:36:21 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 15 Jul 2002 19:36:21 +0200 Subject: could not import mod_python.apache In-Reply-To: References: Message-ID: <20020715173621.GA1089@lilith.my-fqdn.de> * Michael Hoffmann [2002-07-15 16:39 +0200]: > Hi, > I've the folowing Error when I try to run my pythonscript: > > make_obcallback(): could not import mod_python.apache. In my experience, this is the single most often experienced problem with mod_python: For some reason your "make install" step didn't put the mod_python support modules into the right places. You could try to fix this manually: the directory lib/python/mod_python in the mod_python source distribution should go into the site-packages directory of the Python you compiled it against. I'd also recommend to ask on the mod_python mailinglist in the future, as that's where the people who're using it hang out. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 21.4 ?C Wind: 4.7 m/s From jon_bills at hotmail.com Fri Jul 5 05:11:30 2002 From: jon_bills at hotmail.com (Jon Bills) Date: Fri, 5 Jul 2002 10:11:30 +0100 Subject: Making computer into server for free References: Message-ID: "Ali K" wrote in message news:LM3V8.241165$nZ3.111238 at rwcrnsc53... > I would like to know how to make my computer into a web site host with which > I can use python for making my website. Please Reply. Thank You. http://www.zope.org/ From shalehperry at attbi.com Tue Jul 9 18:51:55 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 09 Jul 2002 15:51:55 -0700 (PDT) Subject: A better self In-Reply-To: Message-ID: > > Before you all react (programmers can be SO conservative), please think > about it! > I have played with ideas like this in python and other languages, and witnessed others do the same. .foo is REALLY hard to see if the font is not just right. .size = .r + .l is even worse. I am not 100% against the idea as an idea, but the actual usage is not all that fun. From skip at pobox.com Wed Jul 31 17:38:51 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 31 Jul 2002 16:38:51 -0500 Subject: 'import mod_python' fails In-Reply-To: <158d3913.0207311316.6e2b3e7b@posting.google.com> References: <158d3913.0207311316.6e2b3e7b@posting.google.com> Message-ID: <15688.22763.107809.6199@localhost.localdomain> >> >>> from mod_python import apache >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: No module named mod_python Peter> I don't know if this helps, but I have searched my whole system Peter> and there is no file named 'mod_python.pyo' anywhere! What about mod_python.so? It's an extension module. My guess is the library search path Apache uses doesn't include the directory containing your .so file. Once you locate your .so file, try running Apache with LD_LIBRARY_PATH set appropriately. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From gerhard.haering at gmx.de Wed Jul 3 10:12:39 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 3 Jul 2002 14:12:39 GMT Subject: Thread safetyness in Python References: Message-ID: John Goerzen wrote: > 1. In C, a++ would be atomic because CPUs have an atomic increment > operation, in most cases. What about SMP systems? Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From duncan at NOSPAMrcp.co.uk Wed Jul 31 08:44:24 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 31 Jul 2002 12:44:24 +0000 (UTC) Subject: comparing strings References: <3d47d6b9$1_6@news.teranews.com> Message-ID: "jadedlime" wrote in news:3d47d6b9$1_6 at news.teranews.com: > I appreciate any and all help on this problem, part of the code is > included. this seems to produce the matches, but not the mismatches. > > for key in dictionarylist: > for item in journallist: > if re.search(key, item): > output.write("found\t" + item + "\n") break > else: > output2.write("not found\t" + item + "\n") > You don't want that else clause on the for loop to execute if a match was found, so insert a break statement after the output.write (as shown above). It isn't clear from your code why you are using regular expressions at all. The expressions in your example are all simple string matches. You could go a lot faster by dropping the ^ and $ from each dictionary key and simply testing each item for dictionary membership. Or does your real data have some more complex patterns? -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From pecora at anvil.nrl.navy.mil Tue Jul 9 17:13:28 2002 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 09 Jul 2002 17:13:28 -0400 Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: <090720021713287921%pecora@anvil.nrl.navy.mil> In article , Charles Hixson wrote: > Let's be explict: > from __future__ import nested_scopes > class A: > def ma(self): > print "ma, ma" > def pa(self): > self.ma() > class B(A): > def ma(): > print "hello, world" > tst = B() > tst.pa() > > Testing this produces the message, "hello, world" > This seems to be the wrong message. The version of pa that was called > was the version defined in class A, so the routine called should have > been the routine defined in class A. ??? This is the one I would expect to be called, B.pa. Same rule for C++, IIRC. The inherited displaces the ancester. Sounds "logical" to me. Q. Is the ancester accessible? Like B.A.pa() ? It is in C++ using the scope operator, I think From opengeometry at NOSPAM.yahoo.ca Tue Jul 9 22:35:53 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 10 Jul 2002 02:35:53 GMT Subject: How to grab a part of web page? References: <_ZJW8.46998$n4.11321007@newsc.telia.net> Message-ID: Fredrik Lundh wrote: > "A" wrote: >> Is it possible to download only a part of web page? >> Say I need to find out an information about a customer that starts >> at 1500 byte position and ends at 2000 byte position. If the whole >> page has about 100 kb it seems to me waste of time to load all the >> page. > > import urllib > > file = urllib.urlopen(DATA) > data = file.read(2000) > file.close() > > print data[1500:2000] What if it's the last 500 bytes that he wants? -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From pereira at cis.upenn.edu Thu Jul 4 11:14:09 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Thu, 04 Jul 2002 11:14:09 -0400 Subject: XP: on or off-topic? (was Re: Efficient python programming...) References: <3D00A456.4315EDA3@engcorp.com> <3d238f6b.579164824@news.dsl.pipex.com> <3D23D092.4E3AD523@engcorp.com> <3D243DC0.C82E6B45@engcorp.com> Message-ID: On 7/4/02 8:21 AM, in article 3D243DC0.C82E6B45 at engcorp.com, "Peter Hansen" wrote: > Python programmers are by definition not the kind to follow the > rest of the crowd Are you suggesting that the XP cult is not a crowd yet? <0.9 grin> -- F From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 15:31:31 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 12:31:31 -0700 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> <7xeldq1zzp.fsf@ruckus.brouhaha.com> Message-ID: <7xptxawajw.fsf@ruckus.brouhaha.com> Dale Strickland-Clark writes: > We are providing a number of forms which sit, seamlessly, inside > client web pages. We handle the form and the data, although the > content of the form will depend on the client - not the user of the > browser. The client needs to identifiy and authenticate themselves on > the URL that puts the form in the frame. > > The communication between our servers and the browser isn't the issue > here. > > Had a quick look at HMAC I'm not sure I understand this--where does the challenge come from? What stops someone from intercepting and re-using the authenticating URL? Maybe you want to read the HTTP spec for digest authentication and do what it says. But use HMAC instead of simply appending a password to the challenge. From eric.brunel at pragmadev.com Tue Jul 23 04:41:01 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 23 Jul 2002 08:41:01 +0000 Subject: Tkinter question: how to make hotkeys work References: Message-ID: Gabe Newcomb wrote: > (I'm working in Win2k) > > I've found how to underline a letter on a Button widget, but I can't > seem to use the hotkey to trigger it (Alt + underlined key). What am I > missing? To quote Tk's documentation for the -underline option of the button command (the stars are mine): "Specifies the integer index of a character to underline in the widget. This option is used by the default bindings to implement keyboard traversal for **menu** buttons and **menu** entries. 0 corresponds to the first character of the text displayed in the widget, 1 to the next character, and so on." So apparently, for regular buttons, this option does just what it says: underline a character. You'll have to do explicitly the binding with bind to make it work... > Additionally, if there is a Tkinter mailing group, please let me know. Apart from this one and comp.lang.tcl for tk questions/issues, I don't know of any. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From pinard at iro.umontreal.ca Wed Jul 10 12:53:21 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 10 Jul 2002 12:53:21 -0400 Subject: Hierarchical Editor In-Reply-To: <3D2C500D.5000100@thomas-guettler.de> References: <3D2C3458.1090902@thomas-guettler.de> <3D2C500D.5000100@thomas-guettler.de> Message-ID: [Thomas Guettler] > I love emacs for editing source code. But I need something that > can be used by everybody. Hey, hey! But Emacs _can_ be used by everybody :-) :-). [John Hunter] > [Thomas Guettler] > > Hi! Does someoone know an editor for editing hierarchical text data? > > I need it for something like a todo-list. One task can have several > > subtasks. > Emacs has a number of todo modes: > http://www.emacswiki.org/cgi-bin/wiki.pl?ToDo For my simple needs. I'm happy to edit my TODO files in Emacs' Outline mode, or more precisely, the Allout mode flavour, which I find cleaner. Besides TODO files, Allout is very convenient for writing short manuals, the overall sketch of bigger documents, inventories, indexes, and many other such things. I much prefer knowing one generic folding mode covering many possible applications, than over-specialised modes, like TODO modes may be. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From claird at starbase.neosoft.com Tue Jul 16 09:23:05 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 16 Jul 2002 08:23:05 -0500 Subject: Python and Parrot References: <3D316CCA.90605@myrealbox.com> <7FeY8.15997$p56.5173354@newsb.telia.net> <3D31C707.9020706@myrealbox.com> Message-ID: <25A0677B49A990EA.7729E94769399B96.68B05096197499A2@lp.airnews.net> In article , Christopher Browne wrote: . . . >A not-so-idle idle thought: > >It might be a neat idea, instead of buying a $40 book from some of >these folks that _maybe_ they get $2 out of, to go with the >online/electronic version and send them a $20 in the mail. > >If a few thousand people did that, I suppose O'Reilly or Addison >Wesley might be somewhat chagrined, but it would certainly pump _your_ >money more directly to the authors and "prime mover" types... . . . Books are a hilariously inefficient way to finance their authors. The only advantage they have is that they're often better than any of the alternatives. Anyone with ideas for new "business models" has ripe fields for experimentation. Note that effbot's in a position of leadership on this topic, with his electronic guides. In less of a change of subject than it might seem, how come Tkinter people aren't forever wondering, "How do I embed a foreign application (display) in a Tkinter frame?" It's the kind of question other toolkit users ask often; why not Tkinter, too? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From alessandro.iob at dlevel.com Wed Jul 24 11:31:51 2002 From: alessandro.iob at dlevel.com (Alessandro Iob) Date: 24 Jul 2002 17:31:51 +0200 Subject: How to get the method/function which called a function? Message-ID: <1027524712.2754.10.camel@taz.rv.dlevel.net> Example: def log(msg): caller = GET_CALLER() print repr(caller), msg class A: def t(self): log('a message') a = A() a.t() # prints "> a message" How can I implement the "GET_CALLER()" function in "log()" ? Thanx -- Alessandro Iob D-Level srl, via Cavour 78, 33050 Rivignano UD ITALY Tel: +39 0432 773785, Fax: +39 0432 774217 WWW: http://www.dlevel.com , E-Mail: info at dlevel.com -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 240 bytes Desc: This is a digitally signed message part URL: From andrewm at object-craft.com.au Mon Jul 29 04:37:22 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Mon, 29 Jul 2002 18:37:22 +1000 Subject: order of test In-Reply-To: Your message of "Mon, 29 Jul 2002 09:59:51 +0200." <20020729095951.4cfad491.wilk-spamout@flibuste.net> Message-ID: <20020729083722.C2D1738F67@coffee.object-craft.com.au> >can we be sure of the order of a test expression ? >i mean that >t=["one","two"] >x=10 >if x<2 and t[x]=="oups": > >will never throw an exception if t[2] will be tested before x<2 It's called lazy evaluation, and python shares this trait with C. You can see it in action with something like: >>> def foo(): ... print "foo" ... return 1 ... >>> if 1 and foo(): ... print "bar" ... foo bar >>> if 0 and foo(): ... print "bar" ... >>> -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From fredrik at pythonware.com Sun Jul 28 04:08:54 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 28 Jul 2002 08:08:54 GMT Subject: global param to exec (on win32) References: <1027710735.14561.0.nnrp-07.3e314eb6@news.demon.co.uk> Message-ID: david evans wrote: > # construct "my_dictionary" variable containing outside_func and sdk > exec "outside_func()", my_dictionary > > the call works but the called function complaiss that it can't find > global 'sdk' and when I print globals() from within the called function, > its the same as globals() from within the caller, but I expect it to > be the same as "my_dictionary" within the caller. > > Whatever I specify for the "local" param in my exec call, the target sees > "locals()" as its param list. > > Have I misunderstood the way that global/local params to exec work? yes. the dictionary you pass to exec is used as the global scope for that code. the function itself will use the global scope it was defined in (python uses lexical scoping). for details, see http://www.cwi.nl/www.python.org/doc/current/ref/execframes.html (the table contains a concise summary) and http://www.cwi.nl/www.python.org/doc/current/ref/function.html (I'm banned from www.python.org, it seems ;-) From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 10:02:59 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 09:02:59 -0500 Subject: Dictionaries References: Message-ID: Marcus> How can I change the order of the items in a dictionary Take a look at this thread http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&frame=right&th=bb49e5ca90412fc6&seekm=m2it5ih3v5.fsf%40 From aleax at aleax.it Fri Jul 5 12:45:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 16:45:45 GMT Subject: replacing instance __setattr__ References: Message-ID: Robin Becker wrote: ... >>Is there something intrinsically hard about overriding an instance's >>special methods? I'm using ... > well it seems Python not as dynamic as I believed. The object is > searched last which seems completely counter-intuitive to me, but there > you go. Python is dynamic aplenty, but if it used special methods *found in the instance* rather than those *found in the class*, as it did pre-2.2, then metaclasses would be a mess (as they were pre-2.2). Say that a class object C defines a method __call__. Now what happens when we call C() ... ? Should Python use C.__call__? That's not what we want -- we want C.__call__ used when INSTANCES of C are called, NOT when C itself is called. So, to avoid specialcasing and sundry irregularities, it's best to generalize this. This doesn't impede your abilities to customize an instance, without affecting other instances of the same class: def changeSpecial(inst, name, function): class Customized(inst.__class__): pass setattr(customized, name, function) inst.__class__ = Customized Alex From ld at nospam.com Wed Jul 24 18:03:27 2002 From: ld at nospam.com (Larry) Date: Wed, 24 Jul 2002 22:03:27 GMT Subject: UDP Multicast HELP! Message-ID: I've spent 2 hours searching google for my answer and I can't find it...you are my last hope! How do I set up a socket to join and receive on a UDP multicast? I have tried the following on a windows 2000 machine... ==================================== import socket s1 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, '234.5.6.7') s1.bind(('',6000)) while 1: data = s1.recv(10000) print data ==================================== It just HANGS at the s1.recv(10000). However, if I don't try to do a multicast and just have server UDP to the regular IP, I receive the packets just fine. Now, when I take the above code to a Linux computer, I can't even run the program cuz I get and error that says... "Invalid argument" when it gets to line s1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, '234.5.6.7') I really need to be able to receive multicast messages. Your help is most appreciated!!! Larry From ned at nedbatchelder.com Thu Jul 11 20:26:18 2002 From: ned at nedbatchelder.com (Ned Batchelder) Date: 11 Jul 2002 17:26:18 -0700 Subject: Most pythonic way to format a number with commas? Message-ID: For dir/ls replacement script, I wanted to format file sizes with commas as a thousands separator. I didn't find anything in the standard library, but figured it couldn't be too hard to do with list manipulation. I came up with this: def formatNumber(num): """Format a number for display""" sl = [c for c in str(num)] for i in range(len(sl)-3, 0, -3): sl[i:i] = [','] return string.join(sl, '') While this works, and uses list ops to do it, I thought it would be possible to get a simpler solution. Is there one? --Ned. http://www.nedbatchelder.com From P.Chiu at rl.ac.uk Wed Jul 17 13:26:35 2002 From: P.Chiu at rl.ac.uk (Peter Chiu) Date: Wed, 17 Jul 2002 18:26:35 +0100 Subject: Python 2.2.1 Build Trouble Message-ID: Hi, I tried to build python-2.2.1 on an AlphaServer running Tru64 Unix 5.1a. The .configure process went through okay, but make failed with error: gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_ H -c ./Modules/posixmodule.c -o Modules/posixmodule.o Modules/posixmodule.c: In function `posix_stat': Modules/posixmodule.c:1310: `stat' undeclared (first use in this function) Modules/posixmodule.c:1310: (Each undeclared identifier is reported only once Modules/posixmodule.c:1310: for each function it appears in.) Modules/posixmodule.c: In function `posix_plock': Modules/posixmodule.c:2227: warning: implicit declaration of function `plock' Modules/posixmodule.c: In function `posix_lstat': Modules/posixmodule.c:3380: `lstat' undeclared (first use in this function) Modules/posixmodule.c: In function `posix_unsetenv': Modules/posixmodule.c:4118: warning: implicit declaration of function `unsetenv' make: *** [Modules/posixmodule.o] Error 1 $ Attached below is the full log. Any advice? Regards, Peter Chiu CLRC Rutherford Appleton Laboratory Space Science & Technology Department Building R25 Room 1.27 Chilton Didcot Oxfordshire OX11 0QX UK Voice: +44-(0)1235-446699 Fax: +44-(0)1235-445848 Email: P.Chiu at rl.ac.uk ====================================================== Script started on Wed Jul 17 07:49:26 2002 BADC:\w$ pwd /usr/local/kits/Python-2.2.1 BADC:\w$ gcc -v Reading specs from /usr/local/lib/gcc-lib/alphaev67-dec-osf5.1/3.1/specs Configured with: ../gcc-3.1/configure Thread model: single gcc version 3.1 BADC:\w$ ./configure creating cache ./config.cache checking MACHDEP... osf1V5 checking for --without-gcc... no checking for --with-cxx=... no checking for c++... c++ checking whether the C++ compiler (c++ ) works... yes checking whether the C++ compiler (c++ ) is a cross-compiler... no checking for gcc... gcc checking whether the C compiler (gcc ) works... yes checking whether the C compiler (gcc ) is a cross-compiler... no checking whether we are using GNU C... yes checking whether gcc accepts -g... yes checking how to run the C preprocessor... gcc -E checking for AIX... no checking for minix/config.h... no checking for Cygwin environment... no checking for mingw32 environment... no checking for executable suffix... no checking for --with-suffix... checking for case-insensitive build directory... no checking LIBRARY... libpython$(VERSION).a checking LINKCC... $(PURIFY) $(CC) checking LDLIBRARY... libpython$(VERSION).a checking for ranlib... ranlib checking for ar... ar checking for a BSD compatible install... /usr/local/bin-saved/install -c checking for --with-pydebug... no checking whether gcc accepts -OPT:Olimit=0... no checking whether gcc accepts -Olimit 1500... no checking whether pthreads are available without options... no checking whether gcc accepts -Kpthread... no checking for ANSI C header files... yes checking for dlfcn.h... yes checking for fcntl.h... yes checking for grp.h... yes checking for limits.h... yes checking for langinfo.h... yes checking for locale.h... yes checking for ncurses.h... no checking for poll.h... yes checking for pthread.h... no checking for signal.h... yes checking for stdarg.h... yes checking for stddef.h... yes checking for stdlib.h... yes checking for thread.h... no checking for unistd.h... yes checking for utime.h... yes checking for termios.h... yes checking for sys/audioio.h... no checking for sys/file.h... yes checking for sys/lock.h... yes checking for sys/modem.h... no checking for db_185.h... no checking for db.h... yes checking for sys/param.h... yes checking for sys/poll.h... yes checking for sys/select.h... yes checking for sys/socket.h... yes checking for sys/time.h... yes checking for sys/times.h... yes checking for sys/un.h... yes checking for sys/utsname.h... yes checking for sys/wait.h... yes checking for pty.h... yes checking for term.h... yes checking for libutil.h... no checking for ndbm.h... yes checking for db1/ndbm.h... no checking for gdbm/ndbm.h... no checking for sys/resource.h... yes checking for netpacket/packet.h... no checking for dirent.h that defines DIR... yes checking for opendir in -ldir... no checking for clock_t in time.h... yes checking for mode_t... yes checking for off_t... yes checking for pid_t... yes checking return type of signal handlers... void checking for size_t... yes checking for uid_t in sys/types.h... yes checking size of int... 4 checking size of long... 8 checking size of void *... 8 checking size of char... 1 checking size of short... 2 checking size of float... 4 checking size of double... 8 checking size of fpos_t... 8 checking for long long support... yes checking size of long long... 8 checking for uintptr_t support... no checking size of off_t... 8 checking whether to enable large file support... no checking size of time_t... 4 checking for pthread_t... no checking for --enable-toolbox-glue... no checking for --enable-framework... no checking for dyld... no checking SO... .so checking LDSHARED... ld -shared -expect_unresolved "*" checking CCSHARED... checking LINKFORSHARED... checking CFLAGSFORSHARED... checking for dlopen in -ldl... no checking for shl_load in -ldld... no checking for t_open in -lnsl... no checking for socket in -lsocket... no checking for --with-libs... no checking for --with-signal-module... yes checking for --with-dec-threads... no checking for --with-threads... yes checking for _POSIX_THREADS in unistd.h... yes checking for mach/cthreads.h... no checking for --with-pth... no checking for pthread_create in -lpthread... yes checking if PTHREAD_SCOPE_SYSTEM is supported... yes checking for pthread_sigmask... yes checking for usconfig in -lmpc... no checking for thr_create in -lthread... no checking if --enable-ipv6 is specified... yes checking if RFC2553 API is available... yes checking ipv6 stack type... unknown checking for --with-cycle-gc... yes checking for --with-pymalloc... no checking for --with-wctype-functions... no checking for --with-sgi-dl... no checking for --with-dl-dld... no checking for dlopen... yes checking DYNLOADFILE... dynload_shlib.o checking MACHDEP_OBJS... MACHDEP_OBJS checking for alarm... yes checking for chown... yes checking for chroot... yes checking for clock... yes checking for confstr... yes checking for ctermid... yes checking for ctermid_r... no checking for execv... yes checking for flock... yes checking for fork... yes checking for fsync... yes checking for fdatasync... yes checking for fpathconf... yes checking for ftime... yes checking for ftruncate... yes checking for gai_strerror... yes checking for getgroups... yes checking for getlogin... yes checking for getpeername... yes checking for getpid... yes checking for getpwent... yes checking for getwd... yes checking for hstrerror... yes checking for inet_pton... yes checking for kill... yes checking for link... yes checking for lstat... yes checking for mkfifo... yes checking for mktime... yes checking for mremap... no checking for nice... yes checking for pathconf... yes checking for pause... yes checking for plock... yes checking for poll... yes checking for pthread_init... no checking for putenv... yes checking for readlink... yes checking for select... yes checking for setegid... yes checking for seteuid... yes checking for setgid... yes checking for setgroups... yes checking for setlocale... yes checking for setregid... yes checking for setreuid... yes checking for setsid... yes checking for setpgid... yes checking for setuid... yes checking for setvbuf... yes checking for snprintf... yes checking for sigaction... yes checking for siginterrupt... yes checking for sigrelse... yes checking for strftime... yes checking for strptime... yes checking for symlink... yes checking for sysconf... yes checking for tcgetpgrp... yes checking for tcsetpgrp... yes checking for tempnam... yes checking for timegm... no checking for times... yes checking for tmpfile... yes checking for tmpnam... yes checking for tmpnam_r... no checking for truncate... yes checking for uname... yes checking for unsetenv... yes checking for waitpid... yes checking for _getpty... no checking for getpriority... yes checking for openpty... yes checking for forkpty... yes checking for fseek64... no checking for fseeko... yes checking for fstatvfs... yes checking for ftell64... no checking for ftello... yes checking for statvfs... yes checking for dup2... yes checking for getcwd... yes checking for strdup... yes checking for strerror... yes checking for memmove... yes checking for getpgrp... yes checking for setpgrp... yes checking for gettimeofday... yes checking for getaddrinfo... yes checking getaddrinfo bug... good checking for getnameinfo... yes checking whether time.h and sys/time.h may both be included... yes checking whether struct tm is in sys/time.h or time.h... time.h checking for tm_zone in struct tm... yes checking for st_rdev in struct stat... yes checking for st_blksize in struct stat... yes checking for st_blocks in struct stat... yes checking for time.h that defines altzone... no checking whether sys/select.h and sys/time.h may both be included... yes checking for addrinfo... yes checking for sockaddr_storage... yes checking whether char is unsigned... no checking for working const... yes checking for working volatile... yes checking for working signed char... yes checking for prototypes... yes checking for variable length prototypes and stdarg.h... yes checking for bad exec* prototypes... no checking if sockaddr has sa_len member... no checking for bad static forward... no checking whether va_list is an array... no checking for gethostbyname_r... yes checking gethostbyname_r with 6 args... no checking gethostbyname_r with 5 args... no checking gethostbyname_r with 3 args... yes checking for __fpu_control... no checking for __fpu_control in -lieee... no checking for --with-fpectl... no checking for --with-libm=STRING... default LIBM="-lm" checking for --with-libc=STRING... default LIBC="" checking for hypot... yes checking what malloc(0) returns... null checking for wchar.h... yes checking size of wchar_t... 4 checking what type to use for unicode... unsigned short checking whether byte ordering is bigendian... no checking whether right shift extends the sign bit... yes checking for getc_unlocked() and friends... yes checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no checking for broken nice()... no checking whether mvwdelch is an expression... yes checking whether WINDOW has _flags... yes checking for socklen_t... no checking for build directories... done updating cache ./config.cache creating ./config.status creating Makefile.pre creating Modules/Setup.config creating pyconfig.h creating Setup creating Setup.local creating Makefile BADC:\w$ type make make is /usr/local/bin-saved/make BADC:\w$ make gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Modules/python.o Modules/python.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/acceler.o Parser/acceler.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/grammar1.o Parser/grammar1.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/listnode.o Parser/listnode.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/node.o Parser/node.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/parser.o Parser/parser.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/parsetok.o Parser/parsetok.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/tokenizer.o Parser/tokenizer.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/bitset.o Parser/bitset.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/metagrammar.o Parser/metagrammar.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/myreadline.o Parser/myreadline.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/abstract.o Objects/abstract.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/bufferobject.o Objects/bufferobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/cellobject.o Objects/cellobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/classobject.o Objects/classobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/cobject.o Objects/cobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/complexobject.o Objects/complexobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/descrobject.o Objects/descrobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/fileobject.o Objects/fileobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/floatobject.o Objects/floatobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/frameobject.o Objects/frameobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/funcobject.o Objects/funcobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/intobject.o Objects/intobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/iterobject.o Objects/iterobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/listobject.o Objects/listobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/longobject.o Objects/longobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/dictobject.o Objects/dictobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/methodobject.o Objects/methodobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/moduleobject.o Objects/moduleobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/object.o Objects/object.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/rangeobject.o Objects/rangeobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/sliceobject.o Objects/sliceobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/stringobject.o Objects/stringobject.c Objects/stringobject.c: In function `PyString_Format': Objects/stringobject.c:3425: warning: int format, different type arg (arg 5) gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/structseq.o Objects/structseq.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/tupleobject.o Objects/tupleobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/typeobject.o Objects/typeobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/weakrefobject.o Objects/weakrefobject.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/unicodeobject.o Objects/unicodeobject.c Objects/unicodeobject.c: In function `PyUnicodeUCS2_Format': Objects/unicodeobject.c:5544: warning: int format, different type arg (arg 5) gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Objects/unicodectype.o Objects/unicodectype.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/bltinmodule.o Python/bltinmodule.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/exceptions.o Python/exceptions.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/ceval.o Python/ceval.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/mysnprintf.o Python/mysnprintf.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/firstsets.o Parser/firstsets.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/grammar.o Parser/grammar.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/pgen.o Parser/pgen.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/printgrammar.o Parser/printgrammar.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Parser/pgenmain.o Parser/pgenmain.c gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes Parser/acceler.o Parser/grammar1.o Parser/listnode.o Parser/node.o Parser/parser.o Parser/parsetok.o Parser/tokenizer.o Parser/bitset.o Parser/metagrammar.o Python/mysnprintf.o Parser/firstsets.o Parser/grammar.o Parser/pgen.o Parser/printgrammar.o Parser/pgenmain.o -lpthread -o Parser/pgen Parser/pgen ./Grammar/Grammar ./Include/graminit.h ./Python/graminit.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/compile.o Python/compile.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/codecs.o Python/codecs.c Python/codecs.c: In function `normalizestring': Python/codecs.c:104: warning: subscript has type `char' gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/errors.o Python/errors.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/frozen.o Python/frozen.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/frozenmain.o Python/frozenmain.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/future.o Python/future.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/getargs.o Python/getargs.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/getcompiler.o Python/getcompiler.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/getcopyright.o Python/getcopyright.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/getmtime.o Python/getmtime.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -DPLATFORM='"osf1V5"' -o Python/getplatform.o ./Python/getplatform.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/getversion.o Python/getversion.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/graminit.o Python/graminit.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/import.o Python/import.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -I. -o Python/importdl.o ./Python/importdl.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/marshal.o Python/marshal.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/modsupport.o Python/modsupport.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/mystrtoul.o Python/mystrtoul.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/pyfpe.o Python/pyfpe.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/pystate.o Python/pystate.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/pythonrun.o Python/pythonrun.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/structmember.o Python/structmember.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/symtable.o Python/symtable.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/sysmodule.o Python/sysmodule.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/traceback.o Python/traceback.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/getopt.o Python/getopt.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/dynload_shlib.o Python/dynload_shlib.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Python/thread.o Python/thread.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Modules/config.o Modules/config.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -DPYTHONPATH='":plat-osf1V5:lib-tk"' \ -DPREFIX='"/usr/local"' \ -DEXEC_PREFIX='"/usr/local"' \ -DVERSION='"2.2"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Modules/main.o Modules/main.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONF IG_H -o Modules/gcmodule.o Modules/gcmodule.c gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_ H -c ./Modules/threadmodule.c -o Modules/threadmodule.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_ H -c ./Modules/signalmodule.c -o Modules/signalmodule.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_ H -c ./Modules/posixmodule.c -o Modules/posixmodule.o Modules/posixmodule.c: In function `posix_stat': Modules/posixmodule.c:1310: `stat' undeclared (first use in this function) Modules/posixmodule.c:1310: (Each undeclared identifier is reported only once Modules/posixmodule.c:1310: for each function it appears in.) Modules/posixmodule.c: In function `posix_plock': Modules/posixmodule.c:2227: warning: implicit declaration of function `plock' Modules/posixmodule.c: In function `posix_lstat': Modules/posixmodule.c:3380: `lstat' undeclared (first use in this function) Modules/posixmodule.c: In function `posix_unsetenv': Modules/posixmodule.c:4118: warning: implicit declaration of function `unsetenv' make: *** [Modules/posixmodule.o] Error 1 BADC:\w$ pwd /usr/local/kits/Python-2.2.1 BADC:\w$ find . -name Python ./Mac/Contrib/BBPy.lm/Python ./Mac/Python ./Python ./RISCOS/Python BADC:\w$ exit script done on Wed Jul 17 07:56:16 2002 ====================================================== From sholden at holdenweb.com Mon Jul 1 13:02:03 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 13:02:03 -0400 Subject: New style classes as exceptions (Was: exception handing) References: Message-ID: <7V%T8.69851$F16.33443@atlpnn01.usenetserver.com> "Jonathan Hogg" wrote in message news:B946351B.D405%jonathan at onegoodidea.com... > On 1/7/2002 14:57, in article > mailman.1025531942.11729.python-list at python.org, "Mark McEahern" > wrote: > > >> New style classes don't work when used as exceptions. I guess it > >> should be considered as a bug. > > > > Just out of curiousity: How come you aren't subclassing from Exception? > > The language doesn't require anyone to. You can throw an instance of any old > class: > > >>>> class Foo: pass > > ... > >>>> raise Foo() > > Traceback (most recent call last): > > File "", line 1, in ? > > __main__.Foo: <__main__.Foo instance at 0x3f7aa8> > >>>> > That's well known, but it certainly isn't good style. > Besides which, it doesn't work even if you do: > > >>> class FooError( StandardError, object ): > ... pass > ... > >>> raise FooError() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: exceptions must be strings, classes, or instances, not FooError > >>> > I fail to see how the example above claims to "subclass from Exception". It certainly doesn't seem to be a very good idea to use object as one of the bases, since this is *known* to cause problems. Instead see, for example: >>> class MyError(IOError): ... pass ... >>> raise MyError Traceback (most recent call last): File "", line 1, in ? __main__.MyError >>> raise MyError("Hooray!") Traceback (most recent call last): File "", line 1, in ? __main__.MyError: Hooray! >>> > The problem is that only pure instances of old-style classes can be thrown. > This bit me too when I was doing the above - mixing in a new-style class > with an exception. > > I'd consider this a bug too, but I haven't bothered checking Sourceforge to > see if anyone else has already. > I think it's currently a feature, but it will doubtless become a bug if this situation continues for too long... regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From egbert at bork.demon.nl Mon Jul 1 09:44:13 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Mon, 1 Jul 2002 15:44:13 +0200 Subject: Tkinter destroy() or quit() Message-ID: <20020701154412.A989@bork.demon.nl> Hello, In Tkinter destroy() destroys a widget, and quit() exits the mainloop. However if I replace in the following script the callback by root.destroy, the effect is the same: the button disappears and the mainloop exits. #!/usr/bin/python from Tkinter import * root=Tk() button=Button(root,text='STOP',command=root.quit) button.grid(row=0,column=0) root.mainloop() print "This the end" Intuitively it doesn't look strange in this case. I would like to know more about their effects: when (not) to use the one or the other one, when do they bite or complement each other, and especially, what about these two and nested mainloops. egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From Lutz.Wendland at student.uni-ulm.de Thu Jul 18 12:49:57 2002 From: Lutz.Wendland at student.uni-ulm.de (Lutz.Wendland) Date: 18 Jul 2002 09:49:57 -0700 Subject: slicing and parallel assignment: inconsistent behaviour?? References: Message-ID: <3b3cc51b.0207180849.67346210@posting.google.com> tjd at sfu.ca (Toby Donaldson) wrote in message > I was hoping someone might be able to help me with a problem I've run > into with slices and parallel assignment. I want to swap to segments > of a list. For instance: > > >>> B = range(10) > >>> B[1:5], B[5:10] = B[5:10], B[1:5] > >>> B > [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] The list B has 10 elements. And the indices into the list are like this: B: [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] | | | | | | | | | | | Indices: 0 1 2 3 4 5 6 7 8 9 10 1) The slice B[1:5] spans over four elements and is substituted by a sclice B[5:10] which spans over five elements. That is, B is enlargened by one element: B: [ 0 , 5 , 6 , 7 , 8 , 9 , 5 , 6 , 7 , 8 , 9 ] | | | | | | | | | | | | Indices: 0 1 2 3 4 5 6 7 8 9 10 11 2) Now the sclice B[5:10], which is [9, 5, 6, 7, 8], is substituted by the slice B[1:5] of the original B: B[1:5] is [1,2,3,4], and we get B as [0, 5, 6, 7, 8, 1, 2, 3, 4, 9]. > This works as I expect. But if I leave out the 10s in the slice ... they stretch right to the end of B. This affects only the second step of the assignment as in 2): (since in the first step, B[5:] is identical to B[5:]) 2a) The sclice B[5:], which is [9, 5, 6, 7, 8, 9], stretches now over 6 elements, and is substituted by the slice B[1:5] of the original B, which is [1,2,3,4], and we get B as [0, 5, 6, 7, 8, 1, 2, 3, 4]. > indices, I get this: > > >>> A = range(10) > >>> A[1:5], A[5:] = A[5:], A[1:5] > >>> A > [0, 5, 6, 7, 8, 1, 2, 3, 4] > > Where has the 9 gone? It has been substituted as part of A[5:] which is [9,5,6,7,8,9]. I hope not being too unclear or too exhaustive. Lutz. From gerhard.haering at gmx.de Tue Jul 30 17:38:44 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 30 Jul 2002 23:38:44 +0200 Subject: Console Installation In-Reply-To: References: Message-ID: <20020730213844.GA2132@lilith.example.com> * Tim Peters [2002-07-30 17:23 -0400]: > [Mathieu Belanger] > > [...] Is there a console installer that don't have to be > > interactive?? I've search for that everywhere and didn't find > > anything! > > > > All our PC run WinNT4. > > I really don't know. Here are the docs for the command-line switches > the PythonLabs installer purportedly accepts [...] If that > (particularly /S) doesn't do the trick, I'd suggest contacting > ActiveState. [...] Or you could try the more minimal PythonWare > installer, Installing a standard Python 2.2.1, then copying the python22.dll from the Windows system directory into the same place as python.exe, then zipping the whole thing up and unzipping it on the client machine(s) works fine for me. For better automation, a self-extracting executable or just wrapping it with NSIS should work fine. But I'm not in that stage, yet. I was only testing if this works with my target platforms (NT4SP6 and W2KSP2) at all. Another plus is that you can easily add additional modules that way (PIL in my case). Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From baas at ira.uka.de Thu Jul 4 16:20:34 2002 From: baas at ira.uka.de (Matthias Baas) Date: Thu, 04 Jul 2002 22:20:34 +0200 Subject: Quaternion Arithmetic Module References: Message-ID: <3eb9iu4shhk9frrp7hdfc2mj4prlb925o1@4ax.com> On Thu, 4 Jul 2002 08:32:57 -0500, "Dave Feustel" wrote: >Is there a python module for doing quaternion arithmetic? There's one in my graphics kit: http://cgkit.sourceforge.net - Matthias - From jonathan at onegoodidea.com Fri Jul 12 04:07:53 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 12 Jul 2002 09:07:53 +0100 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: On 12/7/2002 6:54, in article mailman.1026453319.2703.python-list at python.org, "Oren Tirosh" wrote: > XML combines all the inefficiency of text-based formats with most of the > unreadability of binary formats :-) Snicker away, but XML is the closest we've got to a universally accepted structured data format. > A growing number of utilities is a sign that a format is popular, not that > it is good. In fact, it may be argued that a simpler format would actually > need less tools. It doesn't need to be "good". I'm not even sure what you mean by "good". If you feel you can do a better job of designing an extensible structured data format that you can convince the rest of the world to write parsers and generators for that plug into pretty much every available language, editor and database, then be my guest. If I need to exchange some structured data with someone else, I can spend an unbounded amount of time agreeing a format in advance with them or I can just pick a sensible looking schema and dump it to XML. As long as the other party can see what the different tags mean they can trivially import it. I'm not sure it is possible to "overuse" XML. If you need to read and write structured data, why bother coming up with your own format? (see: the entire contents of /etc) Or why use something that is proprietary to a particular language or system? (see: Pickle) Jonathan From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 20:31:11 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 22 Jul 2002 17:31:11 -0700 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> Message-ID: <7x7kjne14g.fsf@ruckus.brouhaha.com> Chris Liechti writes: > considering the backwards incompatibility, it makes no sense to add a > __call__ right now. What incompatibility? Do you think people are out there writing modules with __call__ functions, and then depending on raising an exception when they call the module directly? From j-jinkins at usa.net Sat Jul 20 13:27:02 2002 From: j-jinkins at usa.net (Jim Jinkins) Date: Sat, 20 Jul 2002 17:27:02 GMT Subject: Using pointers References: <4210d7a2.0207200538.44a91c0f@posting.google.com> Message-ID: <3D399D61.3020803@usa.net> Joe Krahn wrote: >Can I make a pointer to an object in Python? I know that all >objects/variables are references, but not in the same sense as in C. >How do I get multiple pointers to reference and modify one variable? > > You can't. This is a 'definition of terms issue. Each variable _is_ a pointer. You can have multiple variables pointing to the same object. If the object is mutable, changes made by accessing it through any of the variables are seen when accessing it through any of the others. a = 5 b = 5 c = 5 a = 6 # b and c still reference 5. print "%s %s %s" % (a, b, c) 6 5 5 a = [] b = a c = b a.append[1] c.append[3] print "%s %s %s" % (a, b, c) [1, 3] [1, 3] [1, 3] When I first came to dynamically typed languages from C and COBOL, this was really hard to wrap my head around. Try Diving Into Python which is linked from the Python Language website. Jim Jinkins From tim.one at comcast.net Fri Jul 26 15:51:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 26 Jul 2002 15:51:56 -0400 Subject: thread wierdness In-Reply-To: <200207261828.OAA29906@test-area.com> Message-ID: [anton wilson] > Ok, I see that python creates an init thread when the first > thread is being created that sits there and does nothing but loop. > That seems very pointless although I'm sure there is a reason for this. Try writing an equivalent C program and see what happens. This is almost certainly something being done by your C runtime library, and/or OS. From jblazi at hotmail.com Wed Jul 17 06:06:39 2002 From: jblazi at hotmail.com (JB) Date: Wed, 17 Jul 2002 12:06:39 +0200 Subject: Making code faster References: <3d3445f9_7@news.newsgroups.com> Message-ID: <3d353fee_10@news.newsgroups.com> Bengt Richter wrote: >>[,] > - Do you mean that literally? I.e., would > "['abc','def']\n" > be a valid example? > - Why do you have to eval() it? That is probably > timeconsuming compared to alternatives. I thought, that would be fast. I can choose the format that is best. (But probably, I 'd like to have a text format.) So I could shoose abc def too. > - Are there always two elements in the list? Yes. Now I have changed my program to i = -1 print 'loading file' def tmp1(s,color=self.sv.lv.newColor): global i i += 1 j = string.find(s,' ') return QSimpleViewItem(i,color,[s[:j],s[j+1:-1]]) try: myfile = open(filename) except: pass else: tmp = myfile.readlines() print 'lines loaded' myfile.close() self.sv.lv.rows = map(tmp1,tmp) self.sv.lv.visible = range(len(self.sv.lv.rows)) print 'lines decoded',self.sv.lv.rows[0].col[0] This is really faster. I did not undertand, how to get rid of the global variable , but even if I do not use i at all and replace it by 0, the time I need is the same. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From aleax at aleax.it Fri Jul 12 13:29:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 17:29:03 GMT Subject: newbie question: getting rid of space in string :( References: Message-ID: Joseph Youssef wrote: ... > print "<" +color+ ">" +a+ "", ... > now this works just fine exept that space in between each block of text, I print's job is to put that space there. Don't want the space, don't use print -- use sys.stdout.write instead: sys.stdout.write("<" +color+ ">" +a+ "") voila, no space -- nothing but what you pass as write's argument. Personally I'd prefer to use % formatting here: sys.stdout.write("<%s>%s" % (color, a, color) ) I find it more readable -- but that's another issue. Alex From jdhunter at nitace.bsd.uchicago.edu Mon Jul 22 19:06:11 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 22 Jul 2002 18:06:11 -0500 Subject: Anybody using 4suite for xslt processing? References: Message-ID: >>>>> "Marko" == Marko Faldix writes: Marko> In diretory Python22\Lib\site-packages\Ft\Lib there is a Marko> file __packageInfo__.py that says: version = "0.12.0a2" Mine is 0.11.0 Marko> What do you have in your directories, which path contains a Marko> class with appendstylesheeturi? I have the Ft dir, but I also have the _xmlplus dir. When I use a recursive grep on *.py files in my site-packages tree for appendStylesheetUri, I get three matches: ./Ft/DbDom/transformDbDom.py ./_xmlplus/xslt/Processor.py ./_xmlplus/xslt/_4xslt.py It appears that the xslt/Processor.py is the one you want. Why you don't have it, I don't know. John Hunter From david.levy at xrce.xerox.com Tue Jul 23 03:34:55 2002 From: david.levy at xrce.xerox.com (David Levy) Date: Tue, 23 Jul 2002 09:34:55 +0200 Subject: Python UDDI implementation References: <3D3C104D.1EDB2D48@xrce.xerox.com> <915a998f.0207220933.44a332ef@posting.google.com> Message-ID: <3D3D071F.BADCBD13@xrce.xerox.com> Thanks I know, this library was released last week However, it is just an interface, not the repository itself ! There are few ones available : jUDDI, .net, IBM's one, but no one in Python or else I think ... I need the server side ;) Hamish Lawson wrote: > David Levy wrote: > > > I am looking for a Python UDDI implementation. > > IBM alphaWorks recently released UDDI4Py: > > http://xml.coverpages.org/ni2002-07-17-a.html > > Hamish Lawson -- _____________________________________________________________ David Levy Xerox Research Centre Europe 6, ch. de Maupertuis F - 38240 Meylan Email david.levy at xrce.xerox.com http://www.xrce.xerox.com From sarah.fraser at cnet.com Wed Jul 10 17:02:33 2002 From: sarah.fraser at cnet.com (builder) Date: 10 Jul 2002 14:02:33 -0700 Subject: Python in the enterprise: Pros and cons Message-ID: <33e8a47f.0207101302.1bd3d902@posting.google.com> Python has many fans in the open source community, but is it ready for the enterprise? Here are the advantages and disadvantages of using Python in the corporate environment. http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm From marklists at mceahern.com Thu Jul 18 09:57:19 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 18 Jul 2002 08:57:19 -0500 Subject: raw_input In-Reply-To: <3D36C5F1.9C966A8F@millfilm.co.uk> Message-ID: [Eric Texier] > It's there anything better than raw_input to query a string > input from the user in a console window. What are the criteria? // m - From charles_mantha at hotmail.com Fri Jul 5 20:23:51 2002 From: charles_mantha at hotmail.com (Charles Mantha) Date: Fri, 5 Jul 2002 20:23:51 -0400 Subject: test Message-ID: really sorry From wdraxinger at darkstargames.de Wed Jul 10 09:28:08 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 10 Jul 2002 15:28:08 +0200 Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> <3D2C32A3.6040505@darkstargames.de> Message-ID: <3D2C3668.9090008@darkstargames.de> Wolfgang Draxinger wrote: > Of course games developed by me will contain error free scripts. OK, I'll try to do so ;-) Bugs can appear everywhere. From pecora at anvil.nrl.navy.mil Mon Jul 8 16:45:11 2002 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 08 Jul 2002 16:45:11 -0400 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <080720021458067296%pecora@anvil.nrl.navy.mil> Message-ID: <080720021645110243%pecora@anvil.nrl.navy.mil> In article , Roy Smith wrote: > Saves typing, yes, but makes your code harder to understand by > somebody else who has to read and maintain it later. True, to some extent, although nobody will have to maintain my code. It's strictly specialized to my work and will not be used for production of anything. But that is a concern, you're right. From jonathan at onegoodidea.com Mon Jul 1 11:34:35 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 01 Jul 2002 16:34:35 +0100 Subject: New style classes as exceptions (Was: exception handing) References: Message-ID: On 1/7/2002 14:57, in article mailman.1025531942.11729.python-list at python.org, "Mark McEahern" wrote: >> New style classes don't work when used as exceptions. I guess it >> should be considered as a bug. > > Just out of curiousity: How come you aren't subclassing from Exception? The language doesn't require anyone to. You can throw an instance of any old class: >>>> class Foo: pass > ... >>>> raise Foo() > Traceback (most recent call last): > File "", line 1, in ? > __main__.Foo: <__main__.Foo instance at 0x3f7aa8> >>>> Besides which, it doesn't work even if you do: >>> class FooError( StandardError, object ): ... pass ... >>> raise FooError() Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be strings, classes, or instances, not FooError >>> The problem is that only pure instances of old-style classes can be thrown. This bit me too when I was doing the above - mixing in a new-style class with an exception. I'd consider this a bug too, but I haven't bothered checking Sourceforge to see if anyone else has already. Jonathan From fakeaddress at nowhere.org Sat Jul 6 06:06:19 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 06 Jul 2002 10:06:19 GMT Subject: sending a file through sockets References: Message-ID: <3D26C135.3000001@nowhere.org> brueckd at tbye.com wrote: > On Fri, 5 Jul 2002, Bryan Olson wrote: >>No, cutting the cord will not do the same thing. You only get the zero- >>byte successful read on graceful shutdown. > > Actually, you get 0-byte successful read when you simply call close() too. I assume you mean when the other side calls close. Yes, that's a clean shutdown (of it's writing end). > Try it. Also note that the socket object destructor calls close(), so > those sockets also get closed cleanly. Right, that's the one gottcha I noted. The system will try to shutdown cleanly, so a local error at the sender could result in a graceful shutdown of his socket. > Finally, I just tried killing the > server process and the client side immediately came back with a 0-byte > successful read. That's the system doing the shutdown for you. If you think it's too dangerous, well, the code you posted didn't actually check the length. The explicitly sent length only protected against the server sending more data than that. > ...and is not small source of errors in HTTP agents, and is also why > HTTP 1.1 discourages this method. I'm prepared to believe you that this was a consideration in HTTP/1.1, but can you cite it? I see a different reason in RFC 2068, "In order to remain persistent, all messages on the connection must have a self- defined message length (i.e., one not defined by closure of the connection), as described in section 4.4." > It's especially annoying to deal with > if you're writing web proxies and caches and the origin server is using > closed sockets to mean end-of-transmission. What's annoying is proxying from a source that delineates the end by marker (connection close or other) to a protocol that puts the content length up front. Even if you don't trust shutdown to mark the end of content, requiring the length beforehand is problematic. Sometimes the sender doesn't know. >>[...] > Ahh... there's the problem. ;-) ------' > Works on Unices.. I tried searching for what it does, and what I found is a Linux patch (2.02) with the comment: "connect() to INADDR_ANY means loopback (BSD'ism)." So, yes, it works on many systems; count me surprised. It caught my eye because I didn't think INADDR_ANY makes sense for connect(). > FWIW, latest CVS version of sockets has timeout support. Yay! Actually the sockets in the Python 2.2 (Windows) library I have support timeouts and select(). The problem is that the protocol libraries don't use them. >>Try your pull-the-plug idea on the Python network protocol libraries. >>Most TCP stacks will detect the dead connection in about two hours. > > Again, a call to shutdown is not needed to get the 0-byte successful recv > call. The remote side has to do the shutdown, though it may not be a deliberate call from the application that does it. > The other side detects it immediately, for other problems you tend > to get a socket.error exception. On pull-the-plug a recv won't detect the connection loss until the local system tries a keepalive probe, which is typically two hours. > What you _do_ need timeouts for is when > you are reading data from a buggy sender that puts your connection on a > shelf and then forgets about it, i.e. the connection is still open and > ready for use but the sender side simply fails to send anything. Lots of connections go silent do to failures other than sender bugs, such as system crashes, power failures, and the ever popular loss of modem connections. And then of course there are malicious senders. --Bryan From fakeaddress at nowhere.org Tue Jul 2 04:26:59 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Jul 2002 08:26:59 GMT Subject: A problem with urllib References: <3D1FD7A1.F265FC8E@engcorp.com> Message-ID: <3D2163E3.3050605@nowhere.org> Aki Niimura wrote: > Peter, thank you for trying out. > Any further suggestion? I did some diagnosis, and the problem seems to be a Linksys bug. The router insists on getting the entire request in a single read, rather than reading until the end of the headers (and content if present). The URL library must be sending one line at a time or something like that. The code below runs through two cases: the first retrieves the resource as it should, and the second triggers the router bug. In the second case, the router returns an "HTTP/1.1 401 Authorization Required" error response, even though we send exactly the same request as in the first case. The code below also has the same bug as the Linksys router: it does just one recv() and assumes it has the entire message. That works in many cases, including demo'ing the problem here, but is not correct. --Bryan import socket import base64 for demo in ("good", "bad"): request_line = "GET /Status.htm HTTP1/0\r\n" auth_header = ("Authorization: Basic %s\r\n" % base64.encodestring(":admin")) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.1.1", 80)) if demo == "good": s.send(request_line + auth_header + "\r\n") else: s.send(request_line) s.send(auth_header + "\r\n") s.shutdown(1) print s.recv(99999) s.close() print "\n\n\n\n" From imcmeans at home.com Tue Jul 2 05:31:41 2002 From: imcmeans at home.com (Ian McMeans) Date: Tue, 02 Jul 2002 09:31:41 GMT Subject: CGI oddness with urllib Message-ID: <1qeU8.54178$vo2.2989593@news2.telusplanet.net> I want a CGI script to load a page with urllib.open(), do some parsing, and then do some output. The script works fine as a command-line script, but fails when I have it running as a CGI script. The CGI script works (it can do other stuff okay, like load files off my hard drive and do output) but it's unable to do urllib.open() when the exact same code works when run from the console. Anyone know what's happening? Is it restricted execution or something? Here's the code: #!F:\Python22\python.exe import urllib, cgi, cgitb cgitb.enable() print "Content-Type: text/html" # HTML is following print # blank line, end of headers print urllib.urlopen('http://www.google.com/').read() From m.laranjeira at datacraft.com.br Mon Jul 29 10:21:47 2002 From: m.laranjeira at datacraft.com.br (Marcus Vinicius Laranjeira) Date: Mon, 29 Jul 2002 11:21:47 -0300 Subject: DIV and MOD Message-ID: <5.1.1.6.0.20020729112008.009fa0c0@imap.datacraft.com.br> I need to use some function like DIV (returns the integer part of a division) and MOD (returns the reminder of a division) in python, but I don't know how to do that. % does not work as expected (in this context) and in the MATH module, I didn't find any kind of function to do such thing. Can anyone help me ? From peter at engcorp.com Thu Jul 18 18:18:13 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Jul 2002 18:18:13 -0400 Subject: Tkinter vs. wxPython References: Message-ID: <3D373EA5.D62E1369@engcorp.com> Gabe Newcomb wrote: > > I've been trying to get into wxPython, but I'm finding the lack > of documentation difficult. There's some, and I'm very grateful for > everybody who's contributed it, but I'm somebody who really likes having > a decent reference and more examples. Do you mean more examples than the massive demo program for wxPython? I don't think I've found almost anything not covered by something in that code yet. > My question is this: is there any compelling reason I shouldn't just go > with Tkinter instead? I work (for now) exclusively on Win32 boxes, by > the way. I switched to wxPython for reasons which were, to me, compelling, but they simply related to my failure to get acceptable looking and performing results under Tkinter. Note I said it was my failure, not Tkinter's... -Peter From dcinege at psychosis.com Mon Jul 22 20:00:55 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Mon, 22 Jul 2002 20:00:55 -0400 Subject: ANNOUNCE: proctitle - manipulate 'argv[]' (process listing) of the Python process Message-ID: <200207222000.55743.dcinege@psychosis.com> keyphrases: setproctitle proctitle change process name change process title change ps output argv[0] argv[-1] It was about a year ago, I produced a nasty patch to sys that allowed changing the raw argv[] of the python process. A year later its sad this functionality has *still* not be intergrated into Python itself. : < In linux this modules allows one to change the output seen from 'ps'. (And the processes 'cmdline' in /proc/) It is useful for hiding 'python', an argument that is a password, or update process information. The joy of unempoyment has given me the time to rewrite my patch as a stand alone module. The module is by no means done. I need people to test on platforms other then Linux and provides results. Once it has been made portable, I intend to talk to Guido about how he'd like to see this intergrated into Python, and then do so. It would likely become an extension to the posix module. Please DL from: http://ftp.psychosis.com/python/ ftp://ftp.psychosis.com/python/ An idea how it currently works: import proctitle Argv = proctitle.ProcTitle() print 'Saving Original argv[]' Argv.save() print 'argv[0:2]: ', Argv[0:2] print Argv Argv[0] = 'Python - Why use anything else?' Argv[0:] = 'Python - Why use anything else?' print 'Slide argv args back one. (hide "python")' print 'Process line now matches sys.argv' Argv[0:] = string.join(Argv[1:]).replace(',','') print 'Restoring Original argv[]' Argv.restore() From tim at bladerman.com Fri Jul 26 08:36:53 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Fri, 26 Jul 2002 12:36:53 GMT Subject: Guide to the python interp. source? Message-ID: Hi <> Is there a guide or a recomended way to "get to know" the source code to the python interpreter? <> I am creating a new language and an IDE intended for beginners. This is my CS master thesis. I plan to use Python as primary language and the Python interpreter as my interpreter. I will probably need to make quite a few changes to the the interpreter to make the language behave the way I want, and I will need to monitor the state of the interperter for debugging purposes <> Python is, I think, a verry intuitive language for beginners, with some modifications it can be even better. Especially with a good IDE. That is what I have set out to create. I have designed the language I want to creat and I have made the first draft of the IDE using Tkinter but I have a big problem with the python source. It is quite extensive and I am not one of those people that can have a look at a million lines of code and se the connections. The best would be, ofcourse, some UML documentation but I would also be happy if I found a small description och what code is where, how to compilem, design thoughts or anything like that. A lot of projects have "a small guide for wannabe developers" but I havn't found anything like that for this project. Not on the website and not in any FAQ. Things I want to change is for example, everything should be "call by refferense", it shall not by case sensitive, redirect output, better errormesages, etc, etc. <> I have given it some thought and think that I can make alot of my changes by preprocessing the code and turn it into correct python code before I send it to the interpreter but that is not viable for everything so I will need to look into the sources anyway. For instance the graphics libary I plan to create I can do all in Python (speed is not an issue). Any thoughts on the subject is ofcourse more then welcome and I am sure I will come back with other questions but the first thing I need is a guide to the Python interpreter sources. Thanks Tim Gahnstr?m From wyojustin at hotmail.com Tue Jul 16 20:53:55 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Wed, 17 Jul 2002 00:53:55 GMT Subject: Problem importing in a cgi script Message-ID: After upgrading to Solaris 8 my cgi scripts are unable to import some modules. The code runs standalone but not when called as a cgi script. I was able to isolate the problem to these short scripts: #!/usr/local/bin/python # test_cgi.py import socket print 'OK!' # cgi_server_like.py import os os.execve('test_cgi.py', ('',), {}) Too bad I don't have the actual traceback. I look like the loader can't find _socket.so. I've done runs where I print sys.path right before the import showing that the directory where _socket.so resides is in there. Any ideas? OS: Solaris 8 Python version: 2.2 From cartermark46 at ukmail.com Thu Jul 18 15:51:55 2002 From: cartermark46 at ukmail.com (Mark Carter) Date: 18 Jul 2002 12:51:55 -0700 Subject: Do GUIs for DBs exist? Message-ID: I was using PySqlite (a module that interfaces Python with the SQLite database ) the other day, and I was thinking: hey, wouldn't it be great if it had a GUI like MSAccess. Maybe such tools already exist, maybe Tkinter might be useful (although I've never used it before). Maybe even an interface written in CGI/html would be best. Comments? From mwh at python.net Tue Jul 30 05:21:35 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 09:21:35 GMT Subject: Python design failures (was Re: Let's Talk About Lambda Func References: Message-ID: Neil Schemenauer writes: > Sean 'Shaleh' Perry wrote: > > I could submit a patch for the repr cleanup in pretty short order. > > Guido's not big on this kind of "hit and run" cleanup. It scares the crap out of *me* when people do this. Don't know what it does to Guido. > He prefers it if someone looks at the entire module while > modernizing it. I think a good strategy is: if you are working on a module *anyway* (adding new functionality, fixing bugs, whatever) then it's reasonable to modernize the style while you're at it (though it's sensible to do the style changes and the code changes in different checkins). The theory being that if you're working on a module, you hope you understand what you're changing... Cheers, M. -- I never disputed the Perl hacking skill of the Slashdot creators. My objections are to the editors' taste, the site's ugly visual design, and the Slashdot community's raging stupidity. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq From correia_j at hotmail.com Fri Jul 5 22:25:37 2002 From: correia_j at hotmail.com (Jose Correia) Date: Sat, 06 Jul 2002 02:25:37 GMT Subject: Corrupt mxODBC installation? References: <0t2V8.25132$YC4.386257@news0.telusplanet.net> Message-ID: Hi Marc-Andre, Thanks for replying. Marc-Andre Lemburg wrote: > Could it be that Python is still picking up some not 100% > uninstalled version of mxODBC on the machine ? > > Try running Python in verbose mode to have it print out the > paths it tries for finding the modules: > > python -vv Did that, all looks ok to me. relevant bit of the output: === START line 289 of output file === # trying mx.pyd # trying mx.dll # trying mx.py # trying mx.pyw # trying mx.pyc # trying D:\Python\lib\site-packages\Pythonwin\mx.pyd # trying D:\Python\lib\site-packages\Pythonwin\mx.dll # trying D:\Python\lib\site-packages\Pythonwin\mx.py # trying D:\Python\lib\site-packages\Pythonwin\mx.pyw # trying D:\Python\lib\site-packages\Pythonwin\mx.pyc # trying D:\Python\lib\site-packages\win32\mx.pyd # trying D:\Python\lib\site-packages\win32\mx.dll # trying D:\Python\lib\site-packages\win32\mx.py # trying D:\Python\lib\site-packages\win32\mx.pyw # trying D:\Python\lib\site-packages\win32\mx.pyc # trying D:\Python\lib\site-packages\win32\lib\mx.pyd # trying D:\Python\lib\site-packages\win32\lib\mx.dll # trying D:\Python\lib\site-packages\win32\lib\mx.py # trying D:\Python\lib\site-packages\win32\lib\mx.pyw # trying D:\Python\lib\site-packages\win32\lib\mx.pyc import mx # directory D:\Python\lib\site-packages\mx # trying D:\Python\lib\site-packages\mx\__init__.pyd # trying D:\Python\lib\site-packages\mx\__init__.dll # trying D:\Python\lib\site-packages\mx\__init__.py # D:\Python\lib\site-packages\mx\__init__.pyc matches D:\Python\lib\site-packages\mx\__init__.py import mx # precompiled from D:\Python\lib\site-packages\mx\__init__.pyc import mx.ODBC # directory D:\Python\lib\site-packages\mx\ODBC # trying D:\Python\lib\site-packages\mx\ODBC\__init__.pyd # trying D:\Python\lib\site-packages\mx\ODBC\__init__.dll # trying D:\Python\lib\site-packages\mx\ODBC\__init__.py # D:\Python\lib\site-packages\mx\ODBC\__init__.pyc matches D:\Python\lib\site-packages\mx\ODBC\__init__.py import mx.ODBC # precompiled from D:\Python\lib\site-packages\mx\ODBC\__init__.pyc import mx.ODBC.Windows # directory D:\Python\lib\site-packages\mx\ODBC\Windows # trying D:\Python\lib\site-packages\mx\ODBC\Windows\__init__.pyd # trying D:\Python\lib\site-packages\mx\ODBC\Windows\__init__.dll # trying D:\Python\lib\site-packages\mx\ODBC\Windows\__init__.py # D:\Python\lib\site-packages\mx\ODBC\Windows\__init__.pyc matches D:\Python\lib\site-packages\mx\ODBC\Windows\__init__.py import mx.ODBC.Windows # precompiled from D:\Python\lib\site-packages\mx\ODBC\Windows\__init__.pyc Traceback (most recent call last): File "testmx.py", line 3, in ? dbc = mx.ODBC.Windows.Connect("TradeHive32", user="", password = "", clear_auto_commit = 0) AttributeError: 'module' object has no attribute 'Connect' ==== END line 327 of output file (total length 937)======== > Versions prior to mxODBC 2.0 are no longer available on the web. > The egenix-mx-commercial Windows installers are around 196kB in > size, so the size you reported looks odd. Sorry my mistake (typo) the files are as follows (downloaded both 3 times now from your site): 12-20-01 20:38 591,644 egenix-mx-base-2.0.3.win32-py2.2.exe 01-11-02 14:31 197,293 egenix-mx-commercial-2.0.4.win32-py2.2.exe I've un-installed and re-installed them several times (base file 1st) but still no luck. I've also uninstalled and re-installed Python (and renamed odbc.pyd in win32 just in case). You mention you keep the base and odbc files in sync. Grasping at straws, could the fact that one is 2.0.3 and the other 2.0.4 have anything to do with it? Appreciate your input. Jose From jtk at yahoo.com Tue Jul 30 12:41:32 2002 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Tue, 30 Jul 2002 12:41:32 -0400 Subject: Deriving from base class, adding an attribute Message-ID: Pardon the ultra-newbie question, but I want to derive a number of classes (in a single module) from the classes in another module. To each of the classes, I need to add a single attribute (if in fact attributes are what they're properly called): The base product is Formulator, the module StandardFields.py http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/formulator/Formulator/ Products\Formulator\StandardFields.py (original) ----------------------------------------------- class StringField(ZMIField): meta_type = "StringField" widget = Widget.TextWidgetInstance validator = Validator.StringValidatorInstance class PasswordField(ZMIField): meta_type = "PasswordField" widget = Widget.PasswordWidgetInstance validator = Validator.StringValidatorInstance (...) What I need to add to my derived module (pseudocode): Products\MyFormulator\StandardFields.py ----------------------------------------------- import Products.Formulator.StandardFields class StringField(Formulator.StandardFields.StringField): layout = Layout.LayoutInstance class PasswordField(Formulator.StandardFields.StringField): layout = Layout.LayoutInstance (...) Where Layout.py is a module in this derived Python product. How is this intent supposed to be expressed? I would like to do this the manual way first, so I learn about module imports and python's inheritance syntax. But once I understand that, I would imagine that Python's nifty introspection features could make something like this possible: "For all classes deriving from X in module Y, add attribute Z" From gerhard.haering at gmx.de Wed Jul 10 08:58:59 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 10 Jul 2002 12:58:59 GMT Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> Message-ID: In article <3D2C2BEB.2040803 at darkstargames.de>, Wolfgang Draxinger wrote: > Michael Hudson wrote: >> For getting rid of builtin functions, why bother? > Because some of them can mess up all. Don't you provide the Python scripts yourself? If you want to expose your app to users and you want to restrict what they can do with the interpreter, you can check out the rexec and Bastion modules. Basically forking the Python source sounds like overkill. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From skip at pobox.com Wed Jul 3 11:34:28 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Jul 2002 10:34:28 -0500 Subject: Thread safetyness in Python In-Reply-To: <20020703182634.A15524@hishome.net> References: <20020703135851.GA73351@hishome.net> <20020703143408.GA32161@unpythonic.net> <20020703182634.A15524@hishome.net> Message-ID: <15651.6532.968436.256710@12-248-8-148.client.attbi.com> Oren> So a+=1 isn't atomic, but l+=[1] is. Interesting. How so? >>> def f(l): ... l += [1] ... >>> dis.dis(f) 0 LOAD_FAST 0 (l) 3 LOAD_CONST 1 (1) 6 BUILD_LIST 1 9 INPLACE_ADD 10 STORE_FAST 0 (l) 13 LOAD_CONST 0 (None) 16 RETURN_VALUE Looks to me like there's the opportunity for another thread to sneak in there and modify l between the LOAD_FAST and STORE_FAST instructions... -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From nico at nfg.nl Thu Jul 18 05:58:13 2002 From: nico at nfg.nl (Nico de Boer) Date: Thu, 18 Jul 2002 11:58:13 +0200 Subject: Apply and map function Message-ID: <3D369135.6040505@nfg.nl> Hi all, I want to implement the apply or map function into the following code: initmethods = InitMethods() methods = { 'SiteNav_OpenTreeLevel': initmethods.init_opentreelevel(), 'SiteNav_LinkTreeItem': initmethods.init_linktreeitem(), 'SiteNav_ActiveTreeItem': initmethods.init_activetreeitem(), 'SiteNav_CloseTreeLevel': initmethods.init_closetreelevel(), 'local_css': initmethods.init_localcss() } for (methodname,method) in methods.items(): self.createDTMLMethod(methodname, '',method) Self.createDTMLMethods is a function that creates Zope DTML Methods. I can't find out how to implement one of these functions. Can somebody help me out? Thanks, Greetz Nico From rjones at ekit-inc.com Wed Jul 24 20:15:40 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 25 Jul 2002 10:15:40 +1000 Subject: how to count lines in a file ? In-Reply-To: References: Message-ID: <200207251015.40671.rjones@ekit-inc.com> On Thu, 25 Jul 2002 9:56 am, Delaney, Timothy wrote: > > From: Richard Jones [mailto:rjones at ekit-inc.com] > > > > On Thu, 25 Jul 2002 8:31 am, Delaney, Timothy wrote: > > > > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt] > > > > > > > > print len(open('/etc/passwd').readlines()) > > > > Sorry, I'm coming in to this thread halfway through, but I > > need to know why > > that code is broken? Is it the > > "open('/etc/passwd').readlines()"? That's a > > very common pattern, as you note, because people think it is > > perfectly > > legitemate. What about it is broken? Why isn't it pointed out > > more often that > > it _is_ broken? > > We had this discussion just recently, but yes, that is precisely what is > broken. > > What is broken? The file is never explicitly closed. As far as the community is concerned, the file is explicitly closed because no reference to it is retained. No, this is not documented. Then again, the documentation makes no claims about any sort of behaviour when the object is collected. The community has, reasonably enough I think, always assumed (for a very long time in many public ways) that the file is closed when it is collected! As to Jython not closing the file - well, I'd consider that a bug... > Why is it broken? There are no guarantees that the file will be closed > either: > > 1. Immediately (the assumption in code that uses the above construct); See my response above. > It is explicitly documented that yo may not rely on reference-counting > semantics for such things (Paul Rubin - take note please). Where? I'm looking at the latest library reference for file objects, and it makes no such statement. Unfortunately, it makes no statement either way, and there's a lot of art out there that takes advantage of the close-on-collect behaviour :( Richard From loredo at astro.cornell.edu Thu Jul 18 16:27:44 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Thu, 18 Jul 2002 16:27:44 -0400 Subject: A better self References: Message-ID: <3D3724C0.F3286A11@astro.cornell.edu> Huaiyu Zhu wrote: > > However, there are situations, mostly in numerical computations, where it is > necessary to have, say, a dozen variables in one expression, and a dozen > statements containing such expressions and some other statements in one > method. It is far more readable to have them all appear in one screen in a > form that resembles written equations on paper, than to dogmatically follow > a convention in a particular programming language. Extremely well put. I've been using Python almost exclusively for scientific programming in the past 3 years or so. I've followed threads about many controversial aspects of Python (additions or long-held characteristics), and I've been impressed time after time with the choices of the development team. Even when my first instinct has been to disagree with a choice or policy, I have always come to see a great deal of wisdom in the final choice. But the one thing that continues to irk me about the language is "self," for just the reasons Huaiyu describes. I think non-numerical programmers are likely not in a position to appreciate the awkwardness of "self..." in numerical settings, where in a many-variable expression it serves to hinder understanding (by making the expression very long, often broken across multiple lines) rather than to enhance it. Yet I think the general arguments for "self" are strong and valid. Though I often wish there were something like a "with" statement in such contexts, Huaiyu's suggestion seems like a reasonable middle ground. But if there were a "with" statement, I'd probably welcome it! Cheers, Tom Loredo From craigmclean at shaw.ca Wed Jul 10 16:11:33 2002 From: craigmclean at shaw.ca (Craig McLean) Date: Wed, 10 Jul 2002 20:11:33 GMT Subject: Behaviour of print in functions Message-ID: I'm learning Python and I have run into something I can't explain. I have the following code X = 99 def foo(): print X X = 100 print X foo() When I call foo it complains that local variable X is referenced before been assigned. However X is a global and I was under the impression that it should realize that and resolve it automatically. I know that if you add a "global X" as the first line of function foo then this all works properly. I also know that X=99 def qux(): print X qux() prints 99 as I would expect. I'm assuming what is happening is that name resolutions use the LGB rule, but assignments always create a new entry in the local namespace, without checking to see if it is covering up a global object of the same name. I'm also assuming that this happens before any of the code in the function is executed. Am I correct? Or is something else happening here. From jonathan at onegoodidea.com Tue Jul 9 05:36:17 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 09 Jul 2002 10:36:17 +0100 Subject: replacing instance __setattr__ References: Message-ID: On 9/7/2002 5:23, in article mailman.1026188712.26963.python-list at python.org, "Tim Peters" wrote: > BTW, bound method objects aren't methods because they're bound > : the OO part of "a method" is the part that figures out where to > dispatch to, and in a bound method object that part has already been > computed and frozen (cached in the BMO). At the point it's just a flavor of > ordinary function. Hmmm. That's arguably incorrect. The OO part of method dispatch is that the function called is looked up per-object. This is clearly done if the pointer to the function is kept in the object's dictionary. Keeping the method table in the class instead of the object is, and always has been, purely a memory optimisation. In traditional OO languages, the methods cannot vary between different objects of the same class and therefore keeping the table in the object is unnecessary when it can be kept in the class and pointed to from the object. The difference between a bound method and a(n unbound) method is that the 'self' object has been associated. When the method table is kept in the class this has to be done at dispatch time, when the method is already associated with the object it need only be done once. All methods are a flavour of ordinary function. In other OO languages this may be made less clear, but in Python, with it's explicit 'self' reference, this is made obvious. -classless-prototype-languages-are-still-object-oriented-ly y'rs, Jonathan From cliechti at gmx.net Wed Jul 24 14:48:45 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 20:48:45 +0200 Subject: Which gui for slow (133 Mhz) pc References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> <3d42f3dc.5866543@news.utanet.at> Message-ID: scrutinizer at gmx.at (Francesco S.) wrote in news:3d42f3dc.5866543 at news.utanet.at: >>Another option is to just do "normal" Win32 GUI programming using the >>win32 (Mark Hammond's) Python extensions. Actually, you have 2 >>options: you can write Python code that looks nearly equivalent to MFC >>GUI code, or you can write Python code that looks nearly equivalent to >>C Win32 GUI code. Either way you'll have very fast load times and your >>program itself will be quite small (no huge libraries to ship with >>it). >> > > That's an alternative. > > Do I have to compile anything? (I know, stupid question, but I'm an > absolute beginner in python, beside, I have a little experience in > C/C++ and windows. no just download win32all: http://starship.python.net/crew/mhammond/ there are some examples that get installed. chris -- Chris From zopestoller at thomas-guettler.de Thu Jul 11 11:13:12 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 11 Jul 2002 17:13:12 +0200 Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> Message-ID: <3D2DA088.10606@thomas-guettler.de> Cousin Stanley wrote: > || ... > || Does someoone know an editor for editing hierarchical text data ? > || ... > > Thomas ... > > You might check out TreePad ... > http://www.treepad.com/ > > They also offer a free version called TreePad Lite ... > The screenshot at treepad.com looks good. But I am addicted to free source code thomas From eppstein at ics.uci.edu Thu Jul 18 18:56:08 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 18 Jul 2002 15:56:08 -0700 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: In article <5606b639.0207181429.2c6d2569 at posting.google.com>, otis_usenet at yahoo.com (OtisUsenet) wrote: > Python newbie question. How does one do something like this in > Python: > > # assign the value of j to i and then increment j by 1 > i = j++ Python is not designed for maximal terseness, nor for compatibility with C, so you need two statements to do this (well, maybe there's a way to do it in one, but the easiest-to-read and therefore best is with two): i = j j += 1 -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jolsen at mailme.dk Fri Jul 5 14:17:11 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 5 Jul 2002 11:17:11 -0700 Subject: Why self? References: Message-ID: Thanks for the reference. Actually I subscribe to the "explicit is better than implicit" axiom also. What I mean by the legacy part is that you have to name self in the list of arguments to the class methods. This part is redundant - but once you are inside a method, it is fine that you have to explicitly qualify by self when refering to class variables. As holger points out, a frequent source of errors in C++ is that a method takes an argument with the same name as a class variable - which then hides the class variable. When I prototype new classes, the methods often start out as functions, and typically I forget to add self to the argument list when they are promoted to methods. It is not a big thing and not difficult to spot when it happens, but still it bugs me, and I think the language would be better off without it. Of course changing this now would brake the existing code base, so I guess we will have to stick with it. Legacy. Cheers Jesper > > So, is it just legacy or is there a reason for this convention? > > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.007.htp From aleax at aleax.it Tue Jul 9 10:09:39 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 14:09:39 GMT Subject: Splitting a string every 'n' References: Message-ID: Simon.Foster at smiths-aerospace.com wrote: > > What is the idiomatic way to split a string into a list > containing 'n' character substrings? I normally do I'm not sure there is just one. I suspect what _feels_ idiomatic to you in this respect depends on where you're coming from -0- just saw Harvey Thomas post a re-based solution that is surely quite correct (and perhaps may even have good performance!) but would just never occur to me first thing... > something like: > > while strng: > substring = strng[:n] > strng = strng[n:] > > > But the performance of this is hopeless for very long strings! Definitely! > Presumable because there's too much list reallocation? Can't Python Yep. > just optimise this by shuffling the start of the list forward? Not without a lot of trouble that would definitely complicate the interpreter's code and quite possibly deteriorate performance for all normal cases that can't easily benefit from such "sharing" of pieces of one string. > Any better ideas, short of manually indexing through? Is there What's wrong with "manually indexing through"? I assume you mean: for i in xrange(0, len(strng), n): substring = strng[i:i+n] process(substring) and I don't see anything wrong with it -- though I might shrink it a bit down to for i in xrange(0, len(strng), n): process(strng[i:i+n]) that's basically the same idea. I'm honestly having a hard time seeing anything wrong with this solution, as presumably needed to come up with anything BETTER. DIFFERENT is easy, e.g., on 2.3 or 2.2 + from __future__ import generators, why not a generator: def slicer(strng, n): for i in xrange(0, len(strng), n): yield strng[i:i+n] and then for substring in slicer(strng, n): process(substring) but that's really the same code again with a false moustache... Alex From buradley at hotmail.com Thu Jul 11 22:58:59 2002 From: buradley at hotmail.com (buradley) Date: Fri, 12 Jul 2002 02:58:59 GMT Subject: Recomendations on Books References: Message-ID: O'Reilly has a number of good titles. Check them out at Amazon.... Make sure to get the O'Reilly Python Pocket Reference. Very handy! "Ray Tux" wrote in message news:hfrX8.3972$7W6.2920 at nwrddc02.gnilink.net... > Hello I am a beginer to programming and I have chose Python. I was just > wandering if you guys could recomend some good Python Beginers books. > > Thanks > > > From gerhard.haering at gmx.de Thu Jul 25 22:07:31 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 26 Jul 2002 04:07:31 +0200 Subject: Python NetBIOS/RPC module ? In-Reply-To: <83942ed5.0207251720.673c9bc4@posting.google.com> References: <83942ed5.0207251720.673c9bc4@posting.google.com> Message-ID: <20020726020731.GA1219@lilith.my-fqdn.de> * Gerald_Bustock [2002-07-25 18:20 -0700]: > hi, > is there any Python module that can do either win32 NetBIOS mecahnisms, > or Unix's RPC/NFS..etc calls ? "pysmb" might be the right keyword to enter into Google. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From brian at sweetapp.com Fri Jul 12 12:38:16 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 12 Jul 2002 09:38:16 -0700 Subject: SimpleXMLRPCServer help Message-ID: <003301c229c2$85cfd660$bd5d4540@Dell2> > help(SimpleXMLRPCServer) describe how to install an instance > on the server: > > 2. Install an instance: > > class MyFuncs: > def __init__(self): > # make all of the string functions available through > # string.func_name > import string > self.string = string > def pow(self, x, y): return pow(x, y) > def add(self, x, y) : return x + y > server = SimpleXMLRPCServer(("localhost", 8000)) > server.register_instance(MyFuncs()) > server.serve_forever() > > BUT I cannot figure out the syntax to access it from a client point of > view In Python, you could call those functions like this: from xmlrpclib import ServerProxy s = ServerProxy('http://127.0.0.1:8000/') s.pow(2,3) s.add(2,3) s.string.find('This is a test', 'test') Cheers, Brian From alexis.layton at post.harvard.edu Thu Jul 11 22:43:50 2002 From: alexis.layton at post.harvard.edu (Alexis Layton) Date: Fri, 12 Jul 2002 02:43:50 GMT Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <3D2487CB.9000102@gmx.de> <3D24FAC5.3050406@something.invalid> Message-ID: <110720022243508221%alexis.layton@post.harvard.edu> In article <3D24FAC5.3050406 at something.invalid>, Greg Ewing wrote: > On the other hand, a situation that *is* very common is > a loop-and-a-half, with the exit condition in the middle. > So far, I've never seen *any* really good loop-and-a-half > structure in any language, and I think Python has a chance > to be truly innovative here. > > The syntax I favour at the moment for Python looks like > > while: > line = f.readline() > gives line <> "": > do_something() > > Some day I'll get around to PEPping this... The syntax I've always liked comes from an old SIGPLAN Notices submission, which I am unable to locate right now, and therefore cannot attribute. Of course, it was for a Algol-ish/Pascal-ish language, and adapting it to Python runs into a little trouble. Please not that no attempt has been made to conserve reserved words. This is a theoretical excercise. It goes along the lines of loop: exit when ALTERNATIVE: when exit when : exit ... Pseudo BNF: (note does not handle suite one-liners) LoopStmt -> "loop" ":" INDENT LoopSuite DEDENT LoopSuite -> Statement | ExitWhenClause | WhenClause ExitWhenClause -> "exit" "when" Condition WhenClause -> "when" Condition ":" INDENT ExitSuite DEDENT ExitSuite -> Statements* ExitStatement ExitStatement -> "exit" Any attempt to move the "when" clauses out to the "loop" level of indentation runs into the problem of continuing the loop after the exit: loop: unconditional-stmts when : cleanup-stmts exit <> If we don't allow cleanup, we could do loop: stmts exit when stmts ... which is certainly simpler but less practical. It has the "distinction" of having indentation following a non-":" statement. This just looks wrong to me, but in any exit-in-the-middle construct you have this problem. Note that there is no reason that exit/when clauses could not also apply to for and while loops. The principal advantages of exit/when clauses is that they are lexical constructs tied to the loop itself, rather than arbitrarily deeply constructed if-elif-else statements with break/continue statements. loop: thing = getAThing() exit when not thing thing.process() -- Alexis Layton alexis . layton @ post . harvard . edu From zopestoller at thomas-guettler.de Mon Jul 1 06:18:54 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Mon, 01 Jul 2002 12:18:54 +0200 Subject: getatime() changes atime on cygwin Message-ID: <3D202C8E.6030509@thomas-guettler.de> Hi! time.getatime() (access time) changes the atime on cygwin. If a run the following script twice. The atime got changed by the first run. Version: Python 2.2 (#1, Dec 31 2001, 15:21:18) [GCC 2.95.3-5 (cygwin special)] on cygwin If I use the native version, the access time does not get changed by calling time.getatime() Version: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 The next strange thing: 'cat foo.txt' in cygwin does not change the atime which you get if you call the getatime() in win32 python. If I open it in an windows application it get changed. Any hints, suggestions? BTW: I use this script for displaying the atime recursively: import os.path import time def print_atime(arg, dirname, files): for file in files: file=os.path.join(dirname, file) time_str=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime( os.path.getatime(file))) print file, time_str os.path.walk(os.getcwd(), print_atime, None) From jadedlime at hotmail.com Tue Jul 30 15:13:05 2002 From: jadedlime at hotmail.com (jadedlime) Date: Tue, 30 Jul 2002 15:13:05 -0400 Subject: comparing strings Message-ID: <3d47d6b9$1_6@news.teranews.com> Hi, I am very new to Python and very new to programming in general. I need to take a particular string of data and compare it to a dictionary which will put all matching records in a specific file and all the records from the string that do not match in another to be dealt with on an individual basis. I appreciate any and all help on this problem, part of the code is included. this seems to produce the matches, but not the mismatches. import string, re, codecs # create inputs and outputs input = codecs.open("/home/jadedlime/Julio/julio.work", "r", encoding="ISO-8859-1") output = codecs.open("sec_try", "w", encoding="ISO-8859-1") output2 = codecs.open("sec_trynotfound", "w", encoding="ISO-8859-1") # read and split the lines of the main julio records whole = input.read() lines = string.split(whole, "\n") # create the dictionary with regular expressions built in dictionary = {"^aarl australian academic & research libraries$" : "10735", "^acimed$" : "11225", "^adbs: l'association des professionnels de l'information et de la documentation$" : "11715", "^alpha 94. strat\351gies d\222alphab\351tisation et de d\351veloppement culturel en milieu rural\ $" : "12205", "^american archivists$" : "13185", "^anales de documentaci\363n$" : "14165", "^annual review of information science and technology (arist)$" : "14655", "^aproximaciones a la traducci\363n$" : "15145", "^apuntes$" : "15635", "^architectural records conference report$" : "16125", "^archivaria$" : "16615", } # take the desired field (journal titles) and put it in a list format journallist = [] for line in lines: field = string.split(line, '"') journalitems = string.strip(string.lower(field[23])) journallist.append(journalitems) # compile the dictionary and make it into a list format dictionarykeys = dictionary.keys() dictionarylist=[] for dictionaryexp in dictionarykeys: regular = re.compile(dictionaryexp) dictionarylist.append(regular) # run a search that should match all the journal titles in the julio file to the ones in # the dictionary, if they match send them to a specific file, if they do not, send them # to another file so ajustments can be made. for key in dictionarylist: for item in journallist: if re.search(key, item): output.write("found\t" + item + "\n") else: output2.write("not found\t" + item + "\n") From mhuening at zedat.fu-berlin.de Wed Jul 10 05:18:39 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 10 Jul 2002 09:18:39 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: Tim Daneliuk wrote in news:qmqgga.g31.ln at eskimo.tundraware.com: > Does some kind soul out there happen to have a pointer to a > tutorial/examples on fiddling with the Win32 registry from PythonWin? > There is a module called pyRegistry. Can't find the url right now, but you can get it from ActivState: http://aspn.activestate.com/ASPN/Modules/Python/dist_html?dist_id=11218 Matthias From gerhard.haering at gmx.de Sun Jul 28 17:55:46 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 28 Jul 2002 21:55:46 GMT Subject: announcement References: Message-ID: Uwe Schmitt wrote in comp.lang.python: > Hi, > > in order to become acquainted with wxPython I developed a > programm which facilitates the drawing of resistor nets, > and is able to compute associatied electrial values. Very nice! It might also come in useful, as I plan to do a graph-drawing app in wxPython, too. One correction for rnetgui.py: try: from win32api import RegOpenKeyEx, RegQueryValueEx, error from win32con import HKEY_LOCAL_MACHINE, KEY_READ key = RegOpenKeyEx(HKEY_LOCAL_MACHINE,r'SOFTWARE\Ziarc',0,KEY_READ) homepath=RegQueryValueEx(key,'Path')[0] #except error: except Exception, reason: homepath=os.path.abspath(".") I replaced the "except error:" line to get it running on Linux. You might want to do a try: from win32api import ... except ImportError: # ... to check wether the win32 extensions are available, which on non-Windows system, they usually aren't ;-) Cool work. It also looks polished. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From eugene1977 at hotmail.com Sat Jul 20 18:31:03 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sat, 20 Jul 2002 17:31:03 -0500 Subject: correct syntax for db api.. References: Message-ID: nvm.. i suceeded with pypgsql.. thx From cce at clarkevans.com Tue Jul 30 23:44:27 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 30 Jul 2002 23:44:27 -0400 Subject: ANN: PyYaml 0.22 Message-ID: <20020730234427.A86750@doublegemini.com> summary: > YAML(tm) is a straightforward machine parsable data serialization format designed for human readability and scipting languages. where: > http://yaml.org/python/PyYaml_30jul2002.tgz details: - now parses in-line mapping and sequence collections (A5/A6) - now has support for timestamps (D4), optionally with mxDateTime - integrated with the testing suite contributed via the Ruby binding. - includes a first stab at a ypath language (./TestingSuite/ypath.yml) credits: - Steve Howell is the primary author of this distribution - WhyTheLuckyStiff has contributed an excellent set of test files notes: > This is still "alpha" quality software, but that said, I'm personally using it in a production environment since my data set is limited to those features that are well tested. The ypath stuff is actually kinda neat, it it completely independent of the yaml serialization format and works on native in-memory map/list structures. This is a experiment and will be toyed with over the next few months, and then formalized as a specification. -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From sdrake at knology.net Mon Jul 29 20:43:51 2002 From: sdrake at knology.net (Steve Drake) Date: 29 Jul 2002 17:43:51 -0700 Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 Message-ID: I am having a problem using PyXML with tutorial code that I got at http://www.ibm.com/developerWorks. Although this code works on Windows with python-2.2.1, and works on RH 7.3 with python-1.5.2, I get an error when attempting to use python-2.2.1 on RH 7.3. I tried installing python-2.2.1 and PyXML-0.7.1 from source, but I get the same error as when using rpm packages. Any help will be appreciated... Python 2.2.1 (#1, Jul 15 2002, 10:55:56) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> from xml.dom.ext.reader.Sax2 import Reader >>> PyXMLReader = Reader() >>> xmlText=""" Text """ >>> doc = PyXMLReader.fromString(xmlText) Traceback (most recent call last): File "", line 1, in ? doc = PyXMLReader.fromString(xmlText) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/__init__.py", line 63, in fromString return self.fromStream(stream, ownerDoc) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/Sax2.py", line 373, in fromStream self.parser.parse(s) File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", line 107, in parse self.reset() File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", line 236, in reset self._parser = expat.ParserCreate(intern = self._interning) TypeError: 'intern' is an invalid keyword argument for this function From oren-py-l at hishome.net Wed Jul 3 14:18:14 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 3 Jul 2002 21:18:14 +0300 Subject: Thread safetyness in Python In-Reply-To: <15651.6532.968436.256710@12-248-8-148.client.attbi.com>; from skip@pobox.com on Wed, Jul 03, 2002 at 10:34:28AM -0500 References: <20020703135851.GA73351@hishome.net> <20020703143408.GA32161@unpythonic.net> <20020703182634.A15524@hishome.net> <15651.6532.968436.256710@12-248-8-148.client.attbi.com> Message-ID: <20020703211814.A17136@hishome.net> On Wed, Jul 03, 2002 at 10:34:28AM -0500, Skip Montanaro wrote: > > Oren> So a+=1 isn't atomic, but l+=[1] is. Interesting. > > How so? > > >>> def f(l): > ... l += [1] > ... > >>> dis.dis(f) > 0 LOAD_FAST 0 (l) > 3 LOAD_CONST 1 (1) > 6 BUILD_LIST 1 > 9 INPLACE_ADD > 10 STORE_FAST 0 (l) > 13 LOAD_CONST 0 (None) > 16 RETURN_VALUE > > Looks to me like there's the opportunity for another thread to sneak in > there and modify l between the LOAD_FAST and STORE_FAST instructions... That is also true of l.append(1) - if another thread modifies the binding of the name l it doesn't matter so much if the append operation on the object it previously pointed to was atomic or not. Assuming the two threads both use l+=[x] or otherwise modify the object but avoid rebinding the reference they should be ok. Oren From giovannic75 at nospam.yahoo.it Sun Jul 28 14:32:56 2002 From: giovannic75 at nospam.yahoo.it (giovanni) Date: Sun, 28 Jul 2002 18:32:56 GMT Subject: connection problems References: Message-ID: the same for me From lull at acm.org Wed Jul 31 01:49:29 2002 From: lull at acm.org (John Lull) Date: 31 Jul 2002 00:49:29 -0500 Subject: Pythonwin error logs? Message-ID: Since I upgraded to Python 2.21, I keep getting "Program Error" dialogs from Pythonwin, both build 146 and 148, on both Win98 and Win2K. The dialog says: Pythonwin.exe has generated errors and will be closed by Windows. You will need to restart the program. An error log is being created. I presume the error log would be helpful in figuring out what's causing these crashes, but extensive searching has failed to turn up even one of these error logs. Any ideas where they're being stored would be appreciated. I've looked in and around the current directory, the entire Python 2.2 directory tree, WINNT\Temp, and the root directory on every local or network drive with no success. Any ideas where they're being stored would be appreciated. Regards, John From ianb at colorstudy.com Tue Jul 9 22:50:49 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 09 Jul 2002 21:50:49 -0500 Subject: How to grab a part of web page? In-Reply-To: <3D2B6810.13895.8A3A7A@localhost> References: <3D2B6810.13895.8A3A7A@localhost> Message-ID: <1026269450.543.33.camel@lothlorien.colorstudy.net> I don't know if this is built in to any Python library. You may have to use httplib. There are HTTP headers (which I don't remember at the moment -- you'd have to look them up somewhere) that allow you to request a specific byte range (though I don't believe the server has to honor that request -- it may return the entire page). httplib allows (and requires) you to set all your headers. Though it looks like you could just use the urllib2.Request to put in your specific headers... I'm not that familiar with that module. You definitely don't have to use the socket module. On Tue, 2002-07-09 at 15:47, A wrote: > Hi, > Is it possible to download only a part of web page? > Say I need to find out an information about a customer that starts > at 1500 byte position and ends at 2000 byte position. If the whole > page has about 100 kb it seems to me waste of time to load all the > page. > What is the best, yet easy, solution? > Is it possible to use httplib or necessary socket module? > Thank you for help. > Ladislav > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From fw58959 at hotmail.com Wed Jul 3 01:50:04 2002 From: fw58959 at hotmail.com (CK) Date: 2 Jul 2002 22:50:04 -0700 Subject: jythonc AttributeError -- Works OK When Invoked Via Jython Message-ID: Being very new to Jython I took a sample chunk of code from "Python Essential Reference" by David Beazley to try it out. When I ran it using jython it ran just fine. I then wanted to see what the generated java code would look like so I ran jythonc against this sample bit of code and I got the following error message: [colin at linux1 colin]$ jythonc /home/colin/sample.jpy Traceback (innermost last):import SocketServer File "/usr/local/jython-2.1/Tools/jythonc/jythonc.py", line 5, in ? File "/usr/local/jython-2.1/Tools/jythonc/main.py", line 300, in main File "/usr/local/jython-2.1/Tools/jythonc/main.py", line 214, in doCompile AttributeError: instance of 'Resource' has no attribute 'file' I understand that certain python bits are not available under jython (namely C routines) but I would have thought that if the code worked under jython then jythonc should have no trouble compling it. Or am I totally misunderstanding something here (and I would not be surprised if I am). Here is the contents of sample.jpy import SocketServer import socket import string class EchoHandler(SocketServer.BaseRequestHandler): def handle(self): f = self.request.makefile() self.request.send("HTTP/1.0 200 OK\r\n") self.request.send("Content-type: text/plain\r\n\r\n") self.request.send("Received connection from %s \r\n\r\n" %(self.client_address,)) while 1: line = f.readline() self.request.send(line) if not string.strip(line): break f.close() serv = SocketServer.TCPServer(("",8051),EchoHandler) serv.serve_forever() Any insight into this would be most appreciated. Thanks. ./CK From aleax at aleax.it Wed Jul 24 07:54:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 11:54:27 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > martin at v.loewis.de (Martin v. Loewis) writes: >> You can put a callable object in sys.modules. Module objects >> themselves are not callable. > > Is this documented somewhere? I don't see it in the obvious places. I could claim it's documented in the cookbook (both online and in print), but I don't think I remembered to list __call__ among the special methods you can use this way -- my specific recipe deals with __setattr__ and __delattr__, and I did also mention __getattr__ in the discussion text, but of course the same idea generalizes to other specials. > If the main purpose of the module is to provide one function, I think > it's cleaner to be able to import the module and call the function > without special tricks. A respectable opinion. Mine is just the reverse -- were it not for backwards compatibility, I wouldn't mind losing __call__ in instances. A bound method can do it, and we could have a _convention_ about how a "primary" method (if any) should be named, just as we have for the 'self' argument. It's all theoretical anyway, __call__'s never going to go away in fact. You may be right that, given that many types have __call__, so should the module type (there being no accepted convention for the name of the 'primary' method). But then why not, e.g., __str__, or __iter__? Where (if anywhere) do we draw the line? Alex From shagshag13 at yahoo.fr Sat Jul 20 05:45:08 2002 From: shagshag13 at yahoo.fr (Shagshag) Date: 20 Jul 2002 02:45:08 -0700 Subject: file ops on the fly ? References: <21TZ8.101254$vm5.3505549@news2.tin.it> Message-ID: <409a56e2.0207200145.77c2004@posting.google.com> "Chris Gonnerman" wrote in message news:... > It can't be done. Line deletion can be done using a > dual-file-pointer algorithm, but if you can't load the > dataset into RAM you can't do insertions without copying > to another file. > > Ur. Maybe it can. If you buffer a few lines ahead, > rewriting them as you go... > > I'm not even going to try to write the code for that. > It's giving me a headache. well, i think it's some kind of warning... i was also thinking of this mecanism, but my biggest trouble is how to write the new file end ? and/or delete the last lines : input_file.txt 1 2 3 4 5 need to replace 2, delete 3 and 5 output_file.txt 1 2b (this one was re-written) 4 (4 take 3 place) 4 (this line is un-wanted) 5 (and this line is also un-wanted) s13. From martin at v.loewis.de Wed Jul 24 15:18:17 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Jul 2002 21:18:17 +0200 Subject: Python 2.2.1 Idle can't find _sre (Win98) References: Message-ID: "Gary Pajer" writes: > Using Win98SE. > Python 2.2 has been working fine. On a whim I upgraded to 2.2.1 today. > Now Idle won't start. What exactly did you do to update? What files did you download (precise URL please), in what order did you perform what actions? Regards, Martin From guy at lightwork.co.uk Mon Jul 8 08:25:28 2002 From: guy at lightwork.co.uk (Guy) Date: 8 Jul 2002 05:25:28 -0700 Subject: mac sit files. Message-ID: Hi Quick question, I've been looking at the zip module, I was wondering if there is some code of some sort, anywhere that could do the same but in a mac sit file. From spam at ob_scure.dk Sun Jul 7 08:11:36 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 14:11:36 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> Message-ID: <3D282FF8.6040602@ob_scure.dk> Paul Rubin wrote: > Thomas Jensen writes: > >>I am quite certain that scaling (well) to multiple CPU requires one to >>use threading at least. Scaling to several physical machines might be >>(relativly) easy with Java, but imagine it must require some coding, >>or? > > You are obsessed with this multi-CPU stuff but have not given the > slightest bit of evidence that you need that complexity to meet your > performance goals. Spend your time trying to understand your problem > better rather than throwing fancy technology at it. Chances are you > can do what you need with a simple, single-CPU approach. :-) Please read my original post again. I merely said, that one of the design goals was scalability. The current job takes about 5 hours to complete! I am absolutely certain that I would be able to write a new job in any language whatsoever (be it Python, C++ or even *shiver* Basic) that would complete the job in less than 30 minutes, given the right DB optimizations and program design. It could be written entirely in SQL for that matter (which would probably perform rather well!). "Spend your time trying to understand your problem better rather than throwing fancy technology at it" This is exactly what I'm trying to do. Distributed computing is far from the number one priority in this project! However, since noone known excactly how much data we will be handling in a year or two, I have been asked to make sure the job is written in a scalable manner. Once the algoritms and database design has been optimized, there is still an upper bound as to how much data one CPU can handle, don't you agree? I expect it to be much easier to build the job around a distributed core now, rather than adding support later. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From cce at clarkevans.com Tue Jul 16 21:30:56 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 16 Jul 2002 21:30:56 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: ; from huaiyu@gauss.almadan.ibm.com on Tue, Jul 16, 2002 at 10:14:51PM +0000 References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <20020716213056.A76960@doublegemini.com> On Tue, Jul 16, 2002 at 10:14:51PM +0000, Huaiyu Zhu wrote: | Thanks a lot for this link. The basic idea is very similar, but apparently | they have done a lot more of formal specification than I have ever | attempted. There are several differences in the details, so neither is | superset of the other. I'll comment on the differences once I have time to | read through their docs. I look forward to the commentary, could you do it or cc the YAML discussion list? | The emphasis is on using indentation and leading markers to denote | structure, in contrast to markups, puctuations, quotes and escapes in the | markup languages. Exactly. We started with leading markers (% and @ initially) and eventually found ways that allowed us to skip these... | There are facilities for conversion among the data structures: set, seq, | dict, seqdict, with various specifications. I do not see how yaml indicates | the types of structures. YAML does this with the bang (!) you can see this in the preview for type family (http://yaml.org/spec/#preview-family) and also in the transfer method section (http://yaml.org/spec/#syntax-trans) | Yaml is very interesting. I'd say aobut 60-80% similar to what I did. I'm | sure I have stuff that they don't have. I'll dig up my stuff anyway. If | anyone is insterested in seeing a mess of code and doc ... :-)a I'd love to hear about the overlap; I'm sure we don't do everything. But if you found something important that we don't have, I'd love to know since we'd like to start finalizing the spec at this time so that implementations can start emerging. | The hype on XML got me really depressed, as I thought no one would | be interested in a direction I regard as fundamentally better than | XML. Any new development that can make my life easier is very | welcome. I think the hype of XML will start to backfire as people realize that its function isn't magical, and that their particular solution isn't all that useable. The information model fits documents well, but is a poor match for object serialization, which is 90% of the use cases programmers face. XML came from the document processing domain, as such it had a good head-start, but I think something like YAML that caters more to the programmer intead of the document author will eventually win out. All in all, its great to hear that you were thining along similar line of thought a few years ago. This is very comforting to me. I'd love to hear more about your thoughts on YAML, and if possible, we'd really welcome your participation! Best, Clark -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From aleax at aleax.it Fri Jul 26 12:13:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 16:13:45 GMT Subject: What am i doing wrong References: <66614160.0207260738.1cefb9ad@posting.google.com> Message-ID: Lee wrote: ... > def detail() : > telnet = telnetlib.Telnet(HOST) > telnet.read_until("login: ") So this tries to telnet to the host named in global variable HOST. Let's see what's in that variable, set a bit later...: > HOST = entry_ph.grid(row=2, column=1) Method grid always returns None, therefore HOST is always None. > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ > return apply(self.func, args) > File "C:\python scripts\teltest.py", line 9, in detail > telnet.read_until("login: ") > File "C:\Python22\lib\telnetlib.py", line 294, in read_until > while not self.eof and apply(select.select, s_args) == s_reply: > File "C:\Python22\lib\telnetlib.py", line 260, in fileno > return self.sock.fileno() > AttributeError: 'NoneType' object has no attribute 'fileno' > Process terminated with exit code 0 and from this trace, we know that self.sock is also None (the only object of type NoneType). Unsurprising. The point is that you don't really want to telnet to host None, but rather to a hostname that is the content of an entry field when 'detail' starts running. Therefore, have function detail start by getting that field's text content, and use that as the argument to telnetlib.Telnet, and so on. Alex From bokr at oz.net Mon Jul 22 18:12:08 2002 From: bokr at oz.net (Bengt Richter) Date: 22 Jul 2002 22:12:08 GMT Subject: file ops on the fly ? References: <21TZ8.101254$vm5.3505549@news2.tin.it> Message-ID: On Sat, 20 Jul 2002 08:56:49 GMT, Alex Martelli wrote: [...] > >Some INCREDIBLY clever buffering algorithm might perhaps be >able to DOUBLE the speed of your desired in-place-editing >approach depending on your patterns of deletions and >insertions, by using (not wasting:-) memory most cleverly. >So you'd only slow down by say 500 times insted of by 1000. >Do you think it would be worth the huge coding effort? > If Alex Martelli's first reaction is that the buffering would have to be "INCREDIBLY" clever, that's saying something ;-) But the job is essentially building a diff file (or whatever memory representation of same is convenient) incrementally and presenting an updated view of a file window on demand, I would think. There is no way manually entered changes wouldn't fit in memory, assuming you represent inserted files (if that's required) by reference and substring parameters instead of literally. If you think of the current state of the file as a chunk list, with chunks either being strings or file slices, it should be easy to support read, and the same operating that indentifies the chunk list slice spanning a read window would re required when you want to do a write. The write would just modify or delete the first chunk and delete all intermediate chunks up to the last, modifying the last chunk to represent a remaining fragment as necessary If you made a class to do this, you could have it do a sequential merge/update at the end of a session. The question would be what a convenient API for the editor would be besides read/write/seek on a virtual file object (e.g., you might need something for lazy file insertions, depending on the editor's requirements, and/or want to see a line sequence window rather than a byte stream window, and whether you want special undo support in the class, etc.). Updating in place, even sequentially at the end, poses a risk though, so I'd rather have the disk space to merge to a new temp file and rename old->old.bak, rename temp->old, and maybe delete old.bak at the end. If that requires a new disk, it's definitely time to do as you say: > >Buy a new disk. They're cheap, VERY cheap. > That's true, but if the OP has an older system, it may be a pain to get past 8GB, or even lower values. Of course that's a good excuse for a whole new system (though reading EULAs is emotionally challenging 8^/ ). > >Or, change your data's structure. A flat text file does >not really make much sense when dealing with gigabytes, >particularly for data that needs to be updated in-place >(conceptually) such as yours. *INVEST* (not a waste!-) >some disk space into structuring your data in a way that >is a closer match for your application's needs...! Maybe a simple RDB of lines with suitable indexing? [ a weekend later ] I decided to try something along the lines of the above. Actually, I made a second pass, based on a mutable string represented as chunks above (strings or file slice specs), and supporting __getitem__,__setitem__,__delitem__ with slices, and hacked read/write/seek using those. Here's an example, peeking at the internal chunk list as we go: >>> from VMString import VMString as VMS >>> vs = VMS(path='test.txt') You can also instantiate other ways, see futher down. Here we induce a call to str(vs): >>> print '-------\n%s-------' % vs ------- Digits @[42:52], then alphabet @[54:80]: 0123456789 abcdefghijklmnopqrstuvwxyz Last line, after a blank one. ------- Here we do the same for slices, which evaluate to new VMString instances >>> print '%s %s' % (vs[42:52],vs[54:80]) 0123456789 abcdefghijklmnopqrstuvwxyz There is still only a single chunk in vs, representing the file. >>> vs.chunks [] Now we'll modify it and have a look: >>> vs[59:59]='XXX' >>> vs.chunks [, 'XXX', ] Notice the old chunk was split in two at the destination slice Now we'll go past the first X and replace 10 characters >>> vs[60:70]='YYY' >>> vs.chunks [, 'X', 'YYY', ] Notice that bit into the last file slice Now we'll replace 5 character starting one before the X, which should kill the YYY: >>> vs[58:63]='ZZZ' >>> vs.chunks [, 'ZZZ', ] QED. Printing the whole again: >>> print '-------\n%s-------' % vs ------- Digits @[42:52], then alphabet @[54:80]: 0123456789 abcdZZZnopqrstuvwxyz Last line, after a blank one. ------- Now I happen to have a file called test2.txt with just "" in it (no \n). We'll try to pqr with that, after the ZZZ: >>> str(vs[63:66]) 'pqr' Yup, that's where pqr is Here goes: >>> vs[63:66] = VMS(path='test2.txt') >>> vs.chunks [, 'ZZZ', , , ] Note what happened to the chunks (now two different files involved). Actually, such small strings should just be converted to actual strings, with some threshold that leaves only really large chunks as file slice specs. The result of the above is: >>> print '-------\n%s-------' % vs ------- Digits @[42:52], then alphabet @[54:80]: 0123456789 abcdZZZnostuvwxyz Last line, after a blank one. ------- Oh, there is a file interface. We know ZZZ starts at 58, so let's try 10 characters from what ought to be the beginning of the line at 54: >>> vs.seek(54) >>> vs.read(10) 'abcdZZZno<' Seems to have worked. Now we'll skip 6 characters (which should be 'Test2.') and write a new extension 'foo' >>> vs.seek(6,1) >>> vs.write('foo') Check result >>> print '-------\n%s-------' % vs ------- Digits @[42:52], then alphabet @[54:80]: 0123456789 abcdZZZnostuvwxyz Last line, after a blank one. ------- Notice what happened to the chunks. We split the text2 slice by putting 'foo' inside it. >>> vs.chunks [, 'ZZZ', , , 'foo', , ] Oop, I almost forgot about del. Let's kill everything from ZZZ up to one. Veriy our guess that 58+len('ZZZno') is the place to start, and knowing file ends with \r\n: >>> str(vs[63:-6]) 'stuvwxyz\r\n\r\nLast line, after a blank ' Looks ok, now delete that stretch and view result: >>> del vs[63:-6] >>> print '-------\n%s-------' % vs ------- Digits @[42:52], then alphabet @[54:80]: 0123456789 abcdZZZnoone. ------- And view chunks >>> vs.chunks [, 'ZZZ', , ] Look at their string representations: >>> map(str,vs.chunks) ['Digits @[42:52], then alphabet @[54:80]:\r\n0123456789\r\nabcd', 'ZZZ', 'no', 'one.\r\n'] We'll, this is a kind of functional proof of concept. It's not very efficient right now ;-) But I think you can see the way a true compulsive could work out a way to look through the chunk list and sort file slices by file and see what was needed to do rewriting "in place" with mimimized side buffers (very likely to be holdable in memory with todays sizes). The cleverness probably wouldn't be totally INCREDIBLE, but it _would_ be a fair amount of work for mostly nothing. It's not the old days any more, where you had to do such things ;-) Plus, a failure in the middle would leave you in deep doodoo. So I made a close() to accept a destination file name and a backup flag. It writes destfile.tmp and then either renames or deletes destfile, and then renames destfile.tmp to destfile. I should make it silent if there's no old file though: >>> vs.close('test3.txt',0) # 0==no backup Traceback (most recent call last): File "", line 1, in ? File "VMString.py", line 364, in close os.remove(destpath) OSError: [Errno 2] No such file or directory: 'test3.txt' Um, or at least catch the right exception ;-) That means I didn't get to the renaming, but we can easily check test3.txt.tmp: >>> print '-------\n%s-------' % VMS(path='test3.txt.tmp') ------- Digits @[42:52], then alphabet @[54:80]: 0123456789 abcdZZZnoone. ------- BTW, the close() copies file slices, but you can configure a constant to control max size copy buffering, so a huge file can be copied without loading it into memory. I set it to 8192, but I can see a better way for the whole file: use vs.read(8192) to consolidate chunks and write single large blocks on cluster boundaries (even if it doesn't wind up reading on boundaries when it walks into large file slices). I still have a bug or two, but it's close to working (having started thinking about it when I saw your post). Right now it requires binary mode read/write, but I think it would be possible to support text cooking and line oriented i/o, which might be nice support for building an editor. I did mention that you can init with a string as well, right? >>> import os >>> pi=VMS(os.popen(r'D:\python22\python C:\pywk\pi\meertens-pi-n.py 200').read()) >>> print '%s' % pi[:50] 31415926535897932384626433832795028841971693993751 >>> print '%s' % pi[50:100] 05820974944592307816406286208998628034825342117067 >>> pi.chunks ['3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034 825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105 5596446229489549303819'] And so forth ;-) Regards, Bengt Richter From cliechti at gmx.net Wed Jul 31 17:09:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 23:09:09 +0200 Subject: Problem - how to solve it ? References: Message-ID: "A" wrote in news:mailman.1028141984.27306.python- list at python.org: > I have a program that I compiled( with Installer) into exe for using > on Win32 systems. It works well on Windows Me, Windows 9x but > on some computers with Windows 2000 it causes General > Protection Error and the programs is finished. It would be nice if the > program wrote a line number or something similar that could help a > user find out which command caused that General Protection > Error. Is there any solution for that? you could try to debug it with a C debugger, but then you would need to recomile everything with debug libs etc. anyway, it's likely that soem extension module accesses memory it shouldn't and only NT based windows care about that. maybe you could tell us what extensions/libaries you use, so that we can get an idea what went wrong. e.g. i had crashes with wxPython it doesn't protect you from the c++ implementation of wxWindws in all respects. sometimes when one does "dispose()" an object (like a wxFrame) and works with it again a protection error can occour. chris -- Chris From gerhard.haering at gmx.de Wed Jul 3 15:42:42 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 3 Jul 2002 19:42:42 GMT Subject: how can I put mysql input without ([,]) References: Message-ID: Ria wrote in comp.lang.python: > Hi, > > I have a question about list or string in Python/Jython. > If I get a select command from mysql en put it in a string (print) than I > can't use it. > > example... > I wil know how many rows ther are in my database table: > >>>>cursur.execute("select count(*) from table") >>>>data = cursur.fetchall() >>>>if data: >>>> for a in data: > ... print a > ... > ([21345,]) > > how can I put only the 21345 without the ([,])?? cursor.fetchall() returns a list of tuples. Each tuple contains the columns from your query. Obviously, your query only returns one row, with a one-element tuple. So better use something like this: cursor.execute("select count(*) from table") result = cursor.fetchone() count = result[0] print "We have %i rows in the table." % count I use fetchone() because I know that there's exactly one row. No need to use fetchmany() or fetchall() in this case. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From ianb at colorstudy.com Fri Jul 12 04:00:28 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2002 03:00:28 -0500 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <33803989.0207110328.5ef01f1e@posting.google.com> References: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: <1026460828.781.70.camel@lothlorien.colorstudy.net> On Thu, 2002-07-11 at 06:28, Miki Tebeka wrote: > Although it's in the Humor section I take the Python Zen > (http://www.python.org/doc/Humor.html#zen) quite seriously. > However I can understand what does “Sparse is better than > dense” means. Tim hasn't chimed in yet -- I bet he's letting us make our own wild speculations, so that we may attain greater wisdom through pondering :) Or maybe his attention is just elsewhere... but I'd like to think that this is a Zen koan. Unlike most of the other people in this thread, I always thought of sparse v. dense as a syntactic/semantic issue. For instance, I think Perl is a very syntactically dense language. If you change one character, you'll probably end up with a valid -- and different -- piece of code. Every meaning is being squeezed out of the available combinations of characters. This is really coming out with Perl 6 too, it seems. Python isn't like that at all -- there's a lot of punctuation that isn't even used. There's also a fair amount of redundancy -- for instance, a colon introduces a block, even though the block explains itself through its indentation. Kind of the opposite of Perl is Lisp languages, but these have a certain density as well -- they pack all meanings into a single syntax. E.g.: (define (reverse x) (if (null? x) '() (append (reverse (cdr x)) (list (car x))))) Doing a binding -- using "define" -- looks a lot like a control structure -- using "if" -- and that looks a lot like a condition -- using "null?" -- or a function call -- using "car" -- and the return is implicit in the expression itself. One syntactic notion -- the space-seperated nested list -- is used to do absolutely everything. Python, while not nearly as regular, has an eclectic nature to the syntax that makes different concepts easier to distinguish from each other. I'm probably reading more into this little statement than is there. But to me this makes sense in thinking about interfaces and other parts of programming -- being too eclectic or too consistent both serve to pack too much meaning into too little space. So for instance, I don't use the dictionary interface for every mapping-like situation. But I also don't think it should never be used. Ian From whisper at oz.net Mon Jul 29 15:28:39 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 29 Jul 2002 12:28:39 -0700 Subject: Leo 3.1 Bugs Message-ID: Python 2.2.1 Windows 2000ProSp2 Leo 3.1 Font Dialog: Leo windows won't change to selected font unless one of (bold, italic) is clicked after the new font is selected. Color Picker: Reverts to color in use before choice is made - i.e. user's new choice is ignored. This was seen on the 'keywords' picker at least. Would be nice if the log window could be disappeared when not being used/not wanted. It would be nice if ?untangled? code was written a bit prettier. It might not generally be intended to look at, but then again, I don't forsee a need to send out tangled code... N.B. Leo on SF doesn't allow posts by unregistered users. David LeBlanc Seattle, WA USA From sholden at holdenweb.com Mon Jul 29 11:28:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Jul 2002 11:28:09 -0400 Subject: conditional importing References: Message-ID: <0ad19.92805$724.68398@atlpnn01.usenetserver.com> "Gerhard H?ring" wrote in message news:mailman.1027907323.21253.python-list at python.org... > * Scott Hathaway [2002-07-28 20:29 -0500]: > > How can I do a conditional import? I am creating a database wrapper class > > that is similar to adodb in PHP. > > I have the following class: > > > > >from mx.ODBC import Windows as db1 > > import MySQLdb as db2 > > Better use something like: > > module_name = "MySQLdb" > try: > dbmodule = __import__(module_name) > except ImportError, reason: > # error handling here > > def open_connection(*args, **kwargs): > return dbmodule.connect(*args, **kwargs) > > Unfortunately, the arguments for the connect method aren't standardized. > But at least some modules allow for a single connection string where the > arguments (host, user, passwd, ...) are separated by colons. > My preferred technique (when all modules obey the DB API sufficiently for my needs) is: if dbtype == 'odbc': import mx.ODBC.Windows as db else: import MySQLdb as db conn = db.open(...) The real problem at present appears to be the various different modules' insistence on using different paramstyles - in the case above, mxODBC expects a "?" for a parameter substitution, while MySQLdb expects a "%s". something-i-need-to-work-on-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From cce at clarkevans.com Tue Jul 30 22:52:20 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 30 Jul 2002 22:52:20 -0400 Subject: Pyrex / py2exe import interaction In-Reply-To: <200207310045.g6V0jWZc019035@kuku.cosc.canterbury.ac.nz>; from greg@cosc.canterbury.ac.nz on Wed, Jul 31, 2002 at 12:45:32PM +1200 References: <20020730165458.A81189@doublegemini.com> <200207310045.g6V0jWZc019035@kuku.cosc.canterbury.ac.nz> Message-ID: <20020730225220.A86211@doublegemini.com> On Wed, Jul 31, 2002 at 12:45:32PM +1200, Greg Ewing wrote: | > Hello. I'm having difficulty with using a combination | > of pyrex and py2exe; the problem occurs when the module | > compiled with pyrex has an "import". | | I'll look into this if I can, but I don't know if | there's much I can do, as I don't have easy access | to a Windows machine to debug this sort of thing on. I've tracked it down a bit further. The _import_one is being called on 'testmod', which is the binary module compiled by pyrex. Then, in some override code for "get_code" which appears to be provided as a dynamically generated string, it calls _import_hook on the following items: imp, marshal, sys, and then finally string. In the cases of imp, marshal, and sys the 'globals' parameter of _import_hook is a mapping. But then somehow, when it goes to import string, globals is actually a module object instead of a mapping. So, somehow the get_code operator provided somehow is passing a module to _import_hook instead of a mapping... Traceback (most recent call last): File "", line 1, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 267, in _import_one File "", line 163, in get_code File "imputil.pyc", line 89, in _import_hook File "imputil.pyc", line 152, in _determine_import_context AttributeError: 'module' object has no attribute 'get' Here is my trace that I generated... imputil.py#085 IN _import_hook(fqname='testmod',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},fromlist=('go',)) imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') imputil.py#102 _import_top_module('testmod') imputil.py#215 _import_one(None,'testmod','testmod') imputil.py$266 get_code(None,'testmod','testmod') imputil.py#215 _import_one(None,'testmod','testmod') imputil.py$266 get_code(None,'testmod','testmod') imputil.py#085 IN _import_hook(fqname='imp',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals=None,fromlist=None) imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') imputil.py#085 IN _import_hook(fqname='marshal',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals=None,fromlist=None) imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') imputil.py#085 IN _import_hook(fqname='sys',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals=None,fromlist=None) imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') imputil.py#085 IN _import_hook(fqname='string',globals=,locals=None,fromlist=[]) imputil.py#088 _determine_import_context(globals=) imputil.py#151 .get('__importer__') Traceback (most recent call last): File "", line 1, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 267, in _import_one File "", line 163, in get_code File "imputil.pyc", line 89, in _import_hook File "imputil.pyc", line 152, in _determine_import_context AttributeError: 'module' object has no attribute 'get' From squelart at hotmail.nospam.com Sun Jul 28 01:50:01 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Sun, 28 Jul 2002 15:50:01 +1000 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> Message-ID: <3d438609$1@duster.adelaide.on.net> "Erik Max Francis" wrote > Michele Simionato wrote: > > I know a print statement cannot stay in a lambda function, however as > > a newbie I ask : why ? > Because a lambda is an expression, not a statement. Therefore, a lambda *expects* an expression, not a statement. However, you could indirectly include a print statement in the course of a running lambda expression: def printArg(arg): print arg return arg l = lambda x: printArg(x) a = l(10) # will print 10 and assign 10 to a map(l, range(5)) # will print numbers 0 to 4 and return [0, 1, 2, 3, 4] It may be useful to debug a lamdba expression. Cheers, Gerald. From andymac at bullseye.apana.org.au Fri Jul 12 04:31:03 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 12 Jul 2002 19:31:03 +1100 (edt) Subject: Python Embedded Instances In-Reply-To: <0a2901c228fc$63290ee0$2901a8c0@amos> Message-ID: On Thu, 11 Jul 2002, Nathan Cassano wrote: > I am working on developing an application that utilizes embedded > python. My question is, can I create multiple instances of the Python > interpreter within my application? My application has multiple documents > each with their own embedded python code. I have read the Extending and > Embedding Python documentation several times and have not found the > answer. I don't believe the Python core in its current form supports separate interpreter instances in the one application (something I understand Tcl can support). You may be able to deal with this, if each "instance" is totally distinct, by using Python threads - the master Python thread starts a thread for each document. This probably has risks though (globals, preserved state in some library modules, etc). -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From ptak at pha.jhu.edu Thu Jul 11 13:41:42 2002 From: ptak at pha.jhu.edu (Andrew Ptak) Date: Thu, 11 Jul 2002 13:41:42 -0400 (EDT) Subject: Good SOAP lib for Python 2.2 (Christopher Browne) Message-ID: pygoogle (http://diveintomark.org/projects/) has an updated version of SOAP.py that works with python 2.2. I have tried it out and haven't had any problems with it, but haven't done anything very complicated (just a simple web service to return the highest cpu-usage processes under unix). Cheers, Andy Ptak From b.maryniuk at forbis.lt Thu Jul 4 08:49:52 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 14:49:52 +0200 Subject: Efficient python programming... In-Reply-To: <3D243BFE.C5105B22@engcorp.com> References: <3D243BFE.C5105B22@engcorp.com> Message-ID: <200207041449.52294.b.maryniuk@forbis.lt> On Thursday 04 July 2002 14:13, Peter Hansen wrote: > I don't think "now" is the same as "fast". XP programming can be "right" (and mostly is), but not even "cheap" or "fast". -- Sincerely yours, Bogdan M. Maryniuck As usual, this being a 1.3.x release, I haven't even compiled this kernel yet. So if it works, you should be doubly impressed. (Linus Torvalds, announcing kernel 1.3.3 on the linux-kernel mailing list.) From see_reply_address at something.invalid Thu Jul 4 22:13:14 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 14:13:14 +1200 Subject: ANN: Pyrex 0.3.3 Message-ID: Pyrex 0.3.3 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Another slew of minor improvements: - Can assign any pointer type to void * without casting - File names in error messages no longer quoted (this was apparently confusing some editors) - Problems with using array in pointer context fixed - Default arguments in extension type methods fixed - Quote chars embedded in triple-quoted strings fixed - Runtime crash when using *args fixed What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jwbaxter at spamcop.net Wed Jul 3 18:42:38 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Wed, 03 Jul 2002 15:42:38 -0700 Subject: Thread safetyness in Python References: Message-ID: In article , "Tim Peters" wrote: > Do a reality check before relying on this. I don't know of any platform > where C compiles a++ to atomic code, even assuming a is of integral type. And even if one finds such a platform, beware of builds with optimization turned off. (With optimization turned on, of course, the a++ may vanish entirely if the result is used not used and a is not used later, which can be "disconcerting".) (Although it's not possible to turn all code mashing off in many cases: it's common to compile as if the machine had an infinite supply of registers and then deal with the reality in a fixup operation.) --John--whose boss once wondered why his compiled code was putting 0 into a memory cell, then reading out the cell and checking whether it was 0...a clear result of if (a = 0) ... From johann.hoechtl at myrealbox.com Wed Jul 24 14:20:17 2002 From: johann.hoechtl at myrealbox.com (=?ISO-8859-1?Q?Johann_H=F6chtl?=) Date: Wed, 24 Jul 2002 20:20:17 +0200 Subject: PyXPCOM and SVG Message-ID: <3D3EEFE1.5090109@myrealbox.com> Hello ! I was thinking of using Mozillas new SVG and/or the gecko rendering engine and XUL capabilities in a wxpython-application using PyXPCOM bindings. First of all: is this the right track to follow? I was rather unhappy when i noticed that his requires me to build mozilla and PyXPCOM from sources. Are there technical reasons why there are no binary packages available? Or is the reason it's almost commercial background as it is used in the Komodo IDE? That means is there a legal or licence issue? Regards, Johann PS: I thinking I will do some initial development on the Windows plattform, If that matters. From pablo17 at hispavista.com Thu Jul 25 17:07:50 2002 From: pablo17 at hispavista.com (Pablo) Date: 25 Jul 2002 14:07:50 -0700 Subject: Python, QT, PyQt in Windows Message-ID: Hi, there. I am totally new in Python world(I started learning it from last weekend). I download the evaluation Python2.2 from Python.org. I download QT and PyQt, too. Now, my question is: how do I do Python program with QT or PyQt? In Python2.2, I have the IDLE, where I can do python program. But, in QT, the QT designer is for C++, in PyQt, there is no working environment at all. What do I need in order to take advantage of QT or PyQt when using Python? I saw a on-line book http://www.opendocs.org/pyqt/, but that is for Linux. I cannot follow the example in that book. Please, somebody who has the experience with Python, QT, PyQt in windows, tell me what I am supposed to do so that I can call the QT from Python. Thanks a lot. Pablo From syver-en+usenet at online.no Sun Jul 21 13:36:49 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sun, 21 Jul 2002 17:36:49 GMT Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> <918bc22f.0207200441.7a5a130d@posting.google.com> <918bc22f.0207210552.56806903@posting.google.com> Message-ID: donnal at donnal.net (Donnal Walter) writes: > > Yes, from the responses here that does appear to be the conventional > way of doing things, so I guess I will continue using unittest this > way too. I had thought I might replace my batch files with a > TestSuite, but I'm really not complaining about the way it works now. > Thanks. Btw, here's some code I put in my __init__.py files to run unittest for all modules in a package. Maybe it does some of the things your are looking for? moduleNames = map(lambda each: os.path.splitext(each)[0], filter(lambda each: each != '__init__.py', glob.glob('*.py'))) # this was the testLoader I was talking about, it makes a suite from all TestCase derived classes in moduleNames. suite = unittest.defaultTestLoader.loadTestsFromNames(moduleNames) runner = unittest.TextTestRunner(verbosity=1) runner.run(suite) -- Vennlig hilsen Syver Enstad From deathtospam43423 at altavista.com Wed Jul 17 20:58:06 2002 From: deathtospam43423 at altavista.com (netvegetable) Date: 18 Jul 2002 00:58:06 GMT Subject: newby: How do I execute external progs? Message-ID: Hello. I'm a python newby who's tinkered a bit. I've done a couple of python tuts on the web. What do I need to know in order to write progs which can execute other progs? e.g, if I want a program to execute a DOS batch file, or explorer, or open an html file how do I get python to do that? -- netvegetable at excite.com From anton.wilson at camotion.com Thu Jul 25 15:16:58 2002 From: anton.wilson at camotion.com (anton wilson) Date: Thu, 25 Jul 2002 15:16:58 -0400 Subject: join in threads Message-ID: <200207251917.PAA31615@test-area.com> Is there a reason why join is only available for threads created with the threading library? Is there some architectural drawback why I couldn't just release the GIL, pthread_join, and then grab the GIL when I'm done? I'm not sure what the threading module does but it doesn't seem to use the system's join functionality but somehow implements it on its own. Anton From anton.wilson at camotion.com Tue Jul 30 17:57:32 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 30 Jul 2002 17:57:32 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207302156.RAA31962@test-area.com> On Tuesday 30 July 2002 04:59 pm, Tim Peters wrote: > [anton wilson] > > > ... > > What's the purpose of releasing an reaquiring the lock if no > > other threads can run? > > They can, as other responses have amply demonstrated. Whether they *will* > is up to the platform thread package, which was presumably designed to pass > out timeslices in a way maximally efficient for it. I think I understand what you mean. I assumed that python should block and allow others to work every x byte codes on EVERY platform. I see that that's a wrong assumption. From fakeaddress at nowhere.org Sun Jul 28 02:45:22 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 28 Jul 2002 06:45:22 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> Message-ID: <3D439340.9020203@nowhere.org> Paul Rubin wrote: > There's a middle ground that says the name "lambda" (which comes from > Lisp) wasn't a good choice and another name should have been used > instead, like maybe 'func', which does the same thing. I guess that's > reasonable. I'm used to lambda from Lisp but another name would > probably be less scary to non-Lisp-users. I agree, though the name "lambda" actually pre-dates Lisp. It comes from Alonzo Church's "lambda Calculous" of the 1930's. ML uses "fn", which like "func" reads beautifully. The construct ceases to be arcane when people hear that "lambda x: x * 2 + 3" reads as "that function which applied to x, returns x * 2 + 3". --Bryan From martin at v.loewis.de Sat Jul 27 09:30:22 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Jul 2002 15:30:22 +0200 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> <3D4263E7.3000107@ims.u-tokyo.ac.jp> Message-ID: Michiel Jan Laurens de Hoon writes: > Thanks for your reply. I am having some difficulties setting the CC > environment variable, probably due to some peculiarities of our Unix > system. But if I solve that and set CC=gcc, would distutils know about > it? Yes, they use the compiler identified by this variable. > I would think that distutils would choose the compiler options for > the regular cc compiler, but substitute gcc for CC when the actual > compilation starts, thus ending up with the wrong compiler > options. Or am I missing something here? Does distutils check for > the CC environment variable? Yes, it does. As for the options: For most purposes, the options of cc and gcc are identical. In the few places where they differ, distutils know about the differences. Regards, Martin From python at ogbnet.com Wed Jul 10 17:54:04 2002 From: python at ogbnet.com (py thon) Date: Wed, 10 Jul 2002 14:54:04 -0700 Subject: Is this possible in python? Message-ID: I need a visual (gui) based app that can take a series of data point and plot them on a graph like a line chart. Then I would like to reshape the curve created above by moving the data points with the mouse. (all using spline interpolation). Then re-output the correct data to a textfile. I would like to know what part of this can python perform. Thanks for your time From tebeka at cs.bgu.ac.il Thu Jul 11 07:28:59 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 11 Jul 2002 04:28:59 -0700 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) Message-ID: <33803989.0207110328.5ef01f1e@posting.google.com> Hello All, Although it's in the Humor section I take the Python Zen (http://www.python.org/doc/Humor.html#zen) quite seriously. However I can understand what does “Sparse is better than dense” means. Any Ideas (Tim?) Thanks Miki From Gabe.Newcomb at noetix.com Thu Jul 18 17:19:57 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Thu, 18 Jul 2002 14:19:57 -0700 Subject: Tkinter vs. wxPython Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F60C6@NOXMAIL.noetixad.com> Ack! I've been trying to get into wxPython, but I'm finding the lack of documentation difficult. There's some, and I'm very grateful for everybody who's contributed it, but I'm somebody who really likes having a decent reference and more examples. My question is this: is there any compelling reason I shouldn't just go with Tkinter instead? I work (for now) exclusively on Win32 boxes, by the way. Thanks all, Gabe From shecky at experimentzero.org Fri Jul 26 15:52:38 2002 From: shecky at experimentzero.org (Britt A. Green) Date: Fri, 26 Jul 2002 12:52:38 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: <030801c234de$00827950$5f01000a@opentable.com.ot> I guess that begs the question: what's the advantage of functional-style programming? :) -- "My mom says I'm cool." ----- Original Message ----- From: "Chris Liechti" Newsgroups: comp.lang.python To: Sent: Friday, July 26, 2002 11:44 AM Subject: Re: Let's Talk About Lambda Functions! > "Britt A. Green" wrote in > news:mailman.1027705851.8443.python-list at python.org: > > > So I know what lambda functions are, they're syntax and how they're used. > > However I'm not sure *why* one would use a lambda function. > > Guido may have asked himself similar questions, considering the note on the > OSCON and EuroPython slides ;-) > > > What's the > > advantage that they offer over a regular function? > > you can define a lambda in an expression, while a "def" is a statement. > and that's probably all there it is. (lambdas have some constraints as they > can only be expressions, but thats a detail) > > cause' lambdas are expresions, they are useful when writing functional > style programs. > > map(lambda x,y:x+y, range(3), [7,8,5]) > > chris > -- > Chris > > From chouster at uclink4.berkeley.edu Thu Jul 11 18:51:58 2002 From: chouster at uclink4.berkeley.edu (Chris) Date: 11 Jul 2002 15:51:58 -0700 Subject: Transferring an excel file through HTTP Message-ID: <79b54d28.0207111451.35b583b2@posting.google.com> Hi everyone, I have a question about clients (on windows) uploading Excel spreadsheets (.xls) to a unix server. These spreadsheets contain information that wil be used to store and update a database. I need to be able to safely pass the information in the spreadsheet so that I can parse it and update accordingly. However, when I upload through my web page, the text that once was a nicely formatted excel spreadsheet becomes jarbled and illegible. Passing the information (presumably through a large string) messes it up understandably as there are text format issues and such. I've explored such things as the COM and win32com modules but am a little hesitant as my CGI script is not operating on a windows platform. I'm using Python 2.2. Can someone point me in the right direction? Thanks! Chris From burkhard.kloss at kbcfp.com Sun Jul 7 17:14:30 2002 From: burkhard.kloss at kbcfp.com (news) Date: Sun, 7 Jul 2002 22:14:30 +0100 Subject: is this a bug? Message-ID: <1026076470.877638@master.nyc.kbcfp.com> Python 2.0 (#1, Feb 7 2001, 22:41:16) [GCC 2.95.2 19991024 (release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> "aa" in ["aa", "ab"] 1 >>> "aa" in ["aa"] 1 >>> "aa" in ("aa") Traceback (most recent call last): File "", line 1, in ? TypeError: 'in ' requires character as left operand Is this a bug, or should this be consistent between lists and tuples? Puzzled. From fredrik at pythonware.com Mon Jul 29 12:07:06 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Jul 2002 16:07:06 GMT Subject: order of test References: <20020729095951.4cfad491.wilk-spamout@flibuste.net> Message-ID: William Dode wrote: > can we be sure of the order of a test expression ? > i mean that > t=["one","two"] > x=10 > if x<2 and t[x]=="oups": > > will never throw an exception if t[2] will be tested before x<2 when in doubt, consult the language reference: http://www.python.org/doc/current/ref/ref.html => expressions => boolean operations "The expression 'x and y' first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned." From russblau at hotmail.com Sun Jul 7 16:12:07 2002 From: russblau at hotmail.com (Russell Blau) Date: Sun, 7 Jul 2002 16:12:07 -0400 Subject: Why isn't this a bug? Message-ID: ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> str(33L) '33' >>> str([33L]) '[33L]' >>> c = 2/5. >>> str(c) '0.4' >>> str((c,)) '(0.40000000000000002,)' As the above example shows, the str() built-in function represents long and float values one way if they are passed directly as the argument of the function, but a different way if they are found inside a list or tuple (or dict, although I didn't illustrate that above). Digging into the source a bit, I found the reason for this. Lists, tuples, and dicts don't have built-in "__str__" methods, and if the str() function can't find such a method then it defaults to using the __repr__ method. Therefore, str() produces the same output as repr() when the argument is a list, tuple, or dict (or any other object that doesn't have a __str__ method). And the __repr__ methods for these objects, naturally enough, recursively call __repr__ on each element of the sequence or mapping. Ah hah, I thought, I've found a bug. However, I did a search on sourceforge.net and found that this issue (or at least part of it) had already been submitted as a bug and rejected! (It was number 506741, for anyone who wants to look.) If this is not a bug, however, it does raise a question about the design of the language. Granted, I suppose one *could* define the operation of the built-in function str() so that exactly the same value can result in different string representations depending on the context in which the value is found (i.e., a long that is inside a list "looks" different than one that is not inside a list); then, the output shown above is not a "bug" but is the way the feature was designed to operate. But why define your language in such a way as to produce inconsistent output? I don't see any value in doing so, and it seems vaguely un-Pythonic (although I admit my Pythonic-ness expertise is very limited). Anyway, if anyone is interested in *changing* this "feature" in a future version, I will point out that it can be done fairly easily by adding methods called "list_str" "tuplestr" and "dict_str" to the files listobject.c, tupleobject.c, and dictobject.c, respectively. Each method would be identical to the currently-defined methods "list_repr" "tuplerepr" and "dict_repr" except that all calls to PyObject_Repr would be replaced by calls to PyObject_Str. In the case of lists and tuples, this would just require changing one line: s = PyObject_Repr(v->ob_item[i]); to s = PyObject_Str(v->ob_item[i]); and adding the appropriate tp_str pointer in the PyTypeObject for each type. (dictobject.c is a little different, since there are two calls to PyObject_Repr() -- one for the key and another for the value, but the basic idea is the same.) Of course, if someone would like to explain why something so simple and intuitive is a "bad idea," please enlighten me. ;-) -- I don't actually have a hotmail account but I do have one on excite.com if you want to contact me. From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 10:12:05 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 09:12:05 -0500 Subject: good books References: Message-ID: >>>>> "Percy" == Percy Tambunan writes: Percy> what is a good book in python, If i can only afford to buy Percy> just one book? If you want a book with a long shelf life, many including myself, recommend Python Essential Reference by David Beazley. It's a reference book, but the first 10 chapters read more like a tutorial and introduction to python for experienced programmers. If you are comfortable with the concept of classes, objects, lists, maps, strings, functions, loops and so forth, then thisis a great book that won't waste your time and you'll come back to it again and again, even as you pass from python newbie to guru. Also the docs that ship with python are latex, so they can be built into ps, dvi, pdf, whatever printer friendly format you prefer. If you have access to a good laser printer and want to save money, print out *The Python Tutorial* and *The Python Library Reference* that ship with the src code. Much of Beazley's books is lifted from the freely available docs. John Hunter From jonathan at onegoodidea.com Tue Jul 2 09:08:04 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 02 Jul 2002 14:08:04 +0100 Subject: cpickle and classes References: Message-ID: On 2/7/2002 12:30, in article c07d0edc.0207020330.5f0d9ec5 at posting.google.com, "Guy" wrote: > If you look at the file there is NO sign of the > Data002.flourUsage.ammount > and Data002.flourUsage.date values or var names. > > Why ? > Can cpickle not handle this ? Aha. This is because you have mixed up class and instance variables. Looking at the example: > class mill: > time = "" > date = "" > name = "" > flourUsage = flour() > add =[""] > > class flour: > ammount = "" > date = "" The variables 'time', 'date', 'name', 'flourUsage', 'add', 'ammount' and 'date' are all class variables - that is they are initialised within the class, not when instantiating a new instance - and thus "belong" to the class not instances of it. > data = mill() > > data.time = "1" > data.date = "2" > data.name = "3" > data.flourUsage.ammount = "4" > data.flourUsage.data = "5" > data.add=["adsfads","dsgdsfgdf"] Here you instantiate a 'mill' object, 'data', which has a pointer to its class and thus to the class variables. However when you do an attribute assignment, like 'data.time = "1"', you create a new instance variable that hides the class one. However, 'data.flourUsage.ammount = "4"' looks up the *class* variable 'flourUsage' and then overrides its 'ammount' variable with "4". Now, to answer your original question, pickle does not write out the class variables since they are not part of the instance you are pickling. So the variables you overrode, 'time', 'date' and 'name', will be written out, but not 'flourUsage'. I think the main thing going wrong is that you have misunderstood how to use classes. The variables shouldn't be assigned in the class body, they should be assigned in an '__init__' method, something like this: >>> class mill: ... def __init__( self ): ... self.time = "" ... self.date = "" ... self.name = "" ... self.flourUsage = flour() ... self.add = [""] ... >>> class flour: ... def __init__( self ): ... self.amount = "" ... self.date = "" ... >>> data = mill() >>> data.time '' >>> data.time = "1" >>> data.flourUsage.amount = "4" Now all of these variables are instance variables, not class variables: >>> mill.time Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'mill' has no attribute 'time' >>> This is at it should be, the 'mill' class itself does not have a time, only instances of it should have a time. Now if we pickle 'data' we get something like: >>> import cPickle >>> >>> cPickle.dumps( data ) "ccopy_reg\n_reconstructor\np1\n(c__main__\nmill\np2\nc__builtin__\nobject\n p3\nNtRp4\n(dp5\nS'date'\np6\nS''\nsS'add'\np7\n(lp8\nS''\nasS'flourUsage'\n p9\ng1\n(c__main__\nflour\np10\ng3\nNtRp11\n(dp12\ng6\nS''\nsS'amount'\np13\ nS'4'\nsbsS'name'\np14\nS''\nsS'time'\np15\nS'1'\nsb." >>> which you can see now includes the 'flourUsage' object, the values we have set, and all the empty initial values. > Is there anything I can do to improve the code to make cpickle work ? > Are there any work arounds for this ? > Maybe suggestions of how to do this in a different way. Well hopefully this has helped to clear it up. In summary: * Definitions made within the 'class' construct become attributes of the class itself. Usually these are just the methods, which are shared between all instances of the class. * Attribute assignments made to 'self' in an '__init__' method create instance variables. These are unique to each new instance and are not shared. * Pickle (and cPickle) only saves and restores instance variables since these represent the unique information about that instance. Jonathan From fredrik at pythonware.com Sat Jul 13 08:12:55 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 12:12:55 GMT Subject: Is count supposed to still work? References: Message-ID: David LeBlanc wrote: > Aren't these all built in anyway? I don't recall having to do it for > len(mystring). what's this? is too much wiki hacking bad for your brain? ;-) the builtins are all that's built in; see: http://www.python.org/doc/current/lib/built-in-funcs.html and http://www.python.org/doc/current/lib/builtin.html From mwh at python.net Mon Jul 29 10:55:17 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Jul 2002 14:55:17 GMT Subject: Newbie question about dictionaries References: Message-ID: "Vladimir Cherepanov" writes: > Is it right then that I have to implement a custom class for key objects if > I want to use a custom hash function? Yes. Why do you ask? Is there some feature of the standard type's hash functions that you dislike? Cheers, M. -- Presumably pronging in the wrong place zogs it. -- Aldabra Stoddart, ucam.chat From chandan_mathur at hotmail.com Wed Jul 3 16:28:16 2002 From: chandan_mathur at hotmail.com (chandan) Date: 3 Jul 2002 13:28:16 -0700 Subject: win32com and internet explorer... sorry if this is a repeat... wasn't sure of the first one Message-ID: Hi..., I am new to python/programming.. I was trying to read and save a page from the internet using win32com and internet explorer..., easy rite? well.. not workin for me.. this is what i have so far import win32com.client,time # Get the browser object ie = win32com.client.DispatchEx("InternetExplorer.Application") # open a page ie.Visible = 1 ie.Navigate("http://www.google.com") time.sleep(5) #to make sure the page has finished loading print ie.Document.toString() result: -- [object] ...I was expecting to see the html junk displayed. help appreciated.... thank you chandan From emile at fenx.com Sat Jul 20 19:54:04 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 20 Jul 2002 23:54:04 GMT Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: Message-ID: Terry Reedy > PyOneWire is new to me, Google, and probably most readers here. Find > the author/distributor. > Start here http://groups.google.com/groups?selm=1bf96e7f.0206060356.417a7394 at postin g.google.com which links to http://www.tykebsd.net/ and http://www.brianlane.com/digitemp.php finally getting to http://www.fellsman.org.uk/tykebsd/pyonewire.html which says Report any bugs (I'm sure there will be some :-) or suggestions to me at pyonewire at tykebsd.net -- Emile van Sebille emile at fenx.com --------- From g0riaman at cdf.toronto.edu Wed Jul 3 11:02:07 2002 From: g0riaman at cdf.toronto.edu (so very tired) Date: Wed, 3 Jul 2002 15:02:07 GMT Subject: creating XML elements Message-ID: Hi, I've been using python for parsing XML, but I need to now create and add elements with subelements, attributes and text. How do I do this using the DOM libraries assuming I just have an XML document with a root node? Thanks for any help. mRiaz From aleax at aleax.it Thu Jul 25 04:05:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 08:05:54 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <3D3E9BCF.90806@mxm.dk> Message-ID: Huaiyu Zhu wrote: > Alex Martelli wrote: >>How is it more convenient to pass, say, object X, rather than >>to pass bound method (e.g.) X.primary? Take your example: > > Well, here's one example: I don't think we're really communicating. >>>> class A: > ... def __call__(self, x): return x+self.x > ... >>>> a = A() >>>> a.x = 3 >>>> a(2) > 5 >>>> a.x = 4 >>>> a(2) > 6 So, the role of an instance of A is "incrementer by an amount that is runtime changeable". OK, not common, but, does happen. >>>> >>>> class B: > ... def call(self, x): return x+self.x > ... >>>> b = B() >>>> b.x = 3 >>>> b.call(2) > 5 >>>> b.x = 4 >>>> b.call(2) > 6 >>>> > > If you take b as the object, you need to use explict call. If you take Right! Explicit is better than implicit. If __call__ didn't exist, and by universal convention an instance's "primary method if any" was named call, this would be exactly as expected. > b.call as object, you can't do other things to the object. Callable Bound methods currently are not allowed to have arbitrary rebindable attributes, while objects of other types can. But that's just how things stand today. Not long ago, functions were not allowed to have arbitrary rebindable attributes either -- when that was added, it made a miniscule difference to Python usage, possibilities, and convenience, simply because the use cases are SO very rare. If rebinding attributes of callables on the fly was deemed important, it would be child's play to add that to bound methods too, of course -- might be even simpler than for functions, since there would be no need to invent a dict for the purpose. Do you REALLY think that having b.call.x = 23 become convenient shorthand for b.call.im_self.x = 23 would make a DEEP difference to Python? I see it as trivial enough to not be worth the bother -- not a frequent need, and all that. > objects > can be viewed as parameterized functions. Regarding whether the > parameters can be modified later, it is similar to functions with > attributes, but not similar to bound methods. Ability to bind arbitrary attributes on functions is recent, and adding the same ability to bound methods would be trivial. If this is your real objection to the (totally abstract) case for taking the time machine and going back to remove __call__, I think it underscores my point: such a removal would make no really significant difference. Note that my case is NOT "you shouln't use __call__ today": as Python actually works, __call__ is sometimes preferable (we do NOT have a universal convention for how else a primary method should be called -- that's the main point, and more significant and harder to fix than trifles such as arbitrary attribute binding). Rather, I claim Python would be OK if it had never had __call__, but rather a convention about primary method name. Ability to bind arbitrary attributes on bound methods might have been added at some point if, like for functions, it had been deemed useful enough (I believe the case for functions was quite different from the parallel you draw, and related instead to making it easier to store _metadata_ about a function, such as, "what syntax production is this function for", which some frameworks were using docstrings for -- a likelier-sounding, if very marginal, use case, anyway). "Ability to bind attributes on objects", now THAT is a thing well worth generalizing. Property lists in very old Lisps, and even in clunkier systems such as Windows (almost nobody KNOWS, but the generic-property-list API's STILL work perfectly well in Win32...), showed up the usefulness. The object to which you're binding properties need know nothing about them -- they're still quite useful as metadata to be used by other parts of the code. Dicts in Python partly obviate that (though you may have to index them by id(object), and/or use weak variants, but that's mostly OK). Alex From fakeaddress at nowhere.org Fri Jul 5 14:12:13 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 05 Jul 2002 18:12:13 GMT Subject: sending a file through sockets References: <3D253AA6.1090806@nowhere.org> Message-ID: <3D25E196.5090207@nowhere.org> Donn Cave wrote: > Quoth Bryan Olson : > | brueckd at tbye.com wrote: > ... > |> but to send the length of the file first so the receiving end > |> knows if and when it got the whole thing. > | > | That's not really needed. Just call shutdown(1) when finished writing. > | The receiver can detect the end when recv() returns zero bytes without > | error, which only happens on clean shutdown. The socket will also > | select() as readable just before the zero-byte recv(). > > Fine if the file is all you're sending, but it's like "who needs > an on-off switch on this appliance, when you can just cut the > power cord with a pair of insulated wire cutters." No, cutting the cord will not do the same thing. You only get the zero- byte successful read on graceful shutdown. That is in fact how HTTP 0.9 handles the end of response, and one of the options in HTTP 1.0 and FTP data connections. [...] > | Did you test this? The Python library uses the empty string for > | INADDR_ANY, which is fine for bind(), but I don't think it's legal for > | connect(). > > So, did you test it? I did! According to my results, he's right, > you're wrong. Yes, the connect() fails on my system (Win 2000, Python 2.2). I'm not sure what a connect to INADDR_ANY should mean either. > | I understand it's a basic demo, but I'll note that any real application > | requires some time-out discipline to avoid very long hangs. Also on > | most Unix systems we'd need to watch out for signals that force system > | calls to return. > > We would? I never have, and I don't notice the standard library > modules doing that. It might something to think about, but hardly > the given it would be in C. You just wing-it and hope for the best? The Python "standard library modules" for network protocols are not so good. The need for timeouts has come up many times in this group. As for signals, there's even comment in the HTTPlib.py "Note that we cannot distinguish between EOF and an interrupt when zero bytes have been read." That's no longer true according to current sockets library doc, so now that it can be handled correctly, surely it should be. > Does any real application need a timeout discipline? Some applications > probably need one, but "real" or not doesn't sound like a very useful > way to think about it. Real as in the ones that need to be robust enough for production use in the real world. Try your pull-the-plug idea on the Python network protocol libraries. Most TCP stacks will detect the dead connection in about two hours. --Bryan From mwh at python.net Mon Jul 29 12:10:59 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Jul 2002 16:10:59 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: "Fredrik Lundh" writes: > to fix the other "mistake", some needs to come up with a > really great syntax (and get michael hudson to implement > it for them ;-). ideas are welcome. I only implement syntax for things I think are a good idea :) I have no problem coming up with names for functions... Cheers, M. -- If i don't understand lisp, it would be wise to not bray about how lisp is stupid or otherwise criticize, because my stupidity would be archived and open for all in the know to see. -- Xah, comp.lang.lisp From tdelaney at avaya.com Wed Jul 24 19:18:58 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 25 Jul 2002 09:18:58 +1000 Subject: how to count lines in a file ? Message-ID: > From: Gerhard H?ring [mailto:gerhard.haering at gmx.de] > > * Delaney, Timothy [2002-07-25 08:31 +1000]: > > > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt] > > > > > > print len(open('/etc/passwd').readlines()) > > > > There is currently discussion on python-dev of the file > object possibly > > becoming collectable by GC (and hence not going away > immediately the last > > reference you know about disappears). > > :-/ > > I thought that Python had a reference-counting garbage collector > combined with a mark-and-sweep gc?! So that if a refcount > goes to zero, > I can count on the object being collected immediately? > > If this is not true, then some of my own code is buggy, too :-( In CPython 2.0+, any code which creates cycles will lead to garbage which is *not* released immediately when the last reference goes away. A GC thread breaks those cycles, allowing them to then be collected - but this takes time. However, not all objects are collectable - if those are in a cycle they will just sit around as garbage forever. A patch was proposed to fix iterator semantics on files, but which would have resulted in the file object being in a cycle. Currently file objects are not collectable (since there was no way to put them in a cycle) so that would have been the worst case (all opened files would sit around forever, not being closed). It was proposed that file objects be made collectable. This would still mean that files would not be closed immediately (or possibly ever). Another patch is being worked on because putting a file in a cycle would kill *lots* of (broken) code written as above. Although the above is not as bad as *writing* to a file and not closing it ... but the principal is the same. The python developers don't want to break code if they can avoid it - I personally would be in favour of files not being collected immediately as it would remove *any* legitimacy from arguments that "this is OK because it's what the implementation does". Tim Delaney From dreed at capital.edu Mon Jul 8 15:36:28 2002 From: dreed at capital.edu (Dave Reed) Date: Mon, 8 Jul 2002 15:36:28 -0400 Subject: subclassing int and accessing the value Message-ID: <200207081936.g68JaSe25466@localhost.localdomain> Let's say I want to subclass int to write my own class for handling monetary values (i.e., represent them in cents, but print them in dollars and cents, but otherwise allow normal addition, subtraction of ints to work). For example, store 150, but print $1.50. First, I'm not certain this is the best way to do it (and it probably isn't), but it's really just a learning exercise for learning about subclassing built-in types. The following works so it appears to be possible. class myint(int): def __init__(self, v): int.__init__(self, ) i = myint(5) print i # prints 5 Now my question is, how do I access the actual value 5 internally so I can write my own __repr__ method that returns '$0.05'. I'm guessing it's using __getattribute__, but what attribute do I want to access? I haven't found any examples for subclassing numeric types, only dicts and lists at http://www.python.org/2.2.1/descrintro.html#subclassing. Thanks, Dave From donn at u.washington.edu Thu Jul 11 17:17:09 2002 From: donn at u.washington.edu (Donn Cave) Date: 11 Jul 2002 21:17:09 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: Quoth Alex Martelli : [... compared to PEP8 on Python code style] | ... It's _very_ different for | PEP 7, on C code style, where there _are_ a couple of points that | would make me reject a lucrative job offer if part of the | conditions was that I had to follow that style for a long time -- | and I'd bet that most experienced C'ers find some aspect there | on which they feel just as strongly, though quite likely on | different subjects and opposite directions from mine...:-). I don't know, it looks real close Berkeley KNF to me. Gets my vote, not that anyone's counting. I think I'd go with KNF on the placement of "else", but otherwise. Donn Cave, donn at u.washington.edu From aleax at aleax.it Fri Jul 12 05:56:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 09:56:31 GMT Subject: Python for data driven website? References: <3D2E51A0.730F521A@engcorp.com> <3D2E946D.2838329C@engcorp.com> Message-ID: Peter Hansen wrote: ... > By the way, "We have a preliminary version ... but it is far > from done. We want to do this right the first time - we expect > to spend a year working on it" makes me think that you guys ought > to spend a brief time investigating Extreme Programming and > considering whether you might benefit from a more iterative > approach with more frequent releases to get feedback on the > direction you are taking, as well as to help focus you on the most > important tasks so you don't get distracted on low business value > items for too much of the project. I think they might be better advised to consider Agile Development Ecosystems more generally -- they're quite a way from XP's sweet spot, so other Agile approaches might serve them better. I recommend both Cockburn's and Highsmith's book on the subject in AW's new series on Agile development. Read Highsmith first, is my advice. Then, with a 3-people project, some variation of Crystal Clear might well be optimal. You do have an excellent point, however: > No project like this should be worked on for three man-years > before its first release, at least not in this day and age! Yep, but getting customers interested enough to be willing to invest manpower is not a trivial problem. Getting customers directly involved is the #1 advantage of Agile approaches and also the hardest one to make into reality. Still, "getting everything right the first time" is definitely the wrong mindset "in this day and age". Rather, focus on implementing features of high business value first, and on the ability to perform major refactoring with confidence (through simplicity and an *abundance* of tests), are very important. Alex From ianb at colorstudy.com Tue Jul 16 14:23:21 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 16 Jul 2002 13:23:21 -0500 Subject: Webware 0.7/Singleton pattern In-Reply-To: References: Message-ID: <1026843801.2095.5.camel@lothlorien.colorstudy.net> On Tue, 2002-07-16 at 03:50, Alex Martelli wrote: > Michael Bub wrote: > ... > > WebApp built with Webware 0.7 (using Python 2.2 on a FreeBSD4.4 > > system), the second or third time the get_instance method is called, > > the one instance that was created by the singleton seems to be > > forgotten about (or rather, it seems as if the file that holds the > > class definition was imported and used for the very first time) and > > You may be serving hits in different processes -- that depends in > part on how you're using Webware... it can be installed to work > on top of CGI, and CGI by definition uses a new process each time. Even when using the CGI adapter with Webware, you still only have one process. The CGI program starts, and then connects to the persistent Webware AppServer. (Unless you are using OneShot, which can introduce all sorts of problems like this, since it does start new processes) It might be a case of a module being imported under two names, e.g., if /path and /path/context are both in sys.path, then when you do "from path.context import X" and "from context import X", you'll have two copies of the X module, and then two singletons. Ian From jonathan at onegoodidea.com Thu Jul 25 07:27:16 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 25 Jul 2002 12:27:16 +0100 Subject: how to count lines in a file ? References: <200207251015.40671.rjones@ekit-inc.com> Message-ID: On 25/7/2002 9:24, in article mailman.1027585535.11720.python-list at python.org, "Bo M. Maryniuck" wrote: > Umm... Richard, I just've played over all we talking about in not best way, > but in anyway I'm little hooked and I would like to know what's _exactly_ > going on: > > *bo at spectator:(~) python > Python 2.2 (#1, Dec 23 2001, 09:30:32) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import gc >>>> len(gc.get_objects()) > 844 >>>> a = open('/etc/passwd') >>>> len(gc.get_objects()) > 844 >>>> del a >>>> len(gc.get_objects()) > 844 >>>> #Huh? As noted earlier in the thread, files don't take part in gc. This is because they don't (at least for the moment) hold references to other objects. Generally only container objects (lists, dictionaries, tuples, instances, classes, etc.) take part in gc and show up in the gc statistics. -reference-counting-is-good-enough-for-some--ly y'rs, Jonathan From jerf at jerf.org Wed Jul 24 16:36:00 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 24 Jul 2002 20:36:00 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: On Wed, 24 Jul 2002 05:49:13 -0500, Alex Martelli wrote: > When your __init__ (or any other method) *just* > delegates to the superclass, and nothing else, > simply remove that method's definition from > your class -- inherit it rather than going to > the trouble of overriding just to delegate, > which buys you nothing. I know; I was trying to cut down the code I posted to just enough to show the "problem" I was wondering about. I figured it was PEBKAC, and lo, it was. My *real* metaclass does more. I did get the request for more information, which I'll get to a bit later tonight when I have the code at hand. The reasons I'm using it are a bit complicated, but it's a cool and very simple use that could be extremely useful if one was building a framework with some sort of automatic, pickle-based persistance. (Which I sorta am, though it's not meant to be a framework, that's just how the design came out...) From jonathan at onegoodidea.com Tue Jul 2 04:01:53 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 02 Jul 2002 09:01:53 +0100 Subject: What is ""? References: <45e6545c.0207012303.5a0e44fd@posting.google.com> Message-ID: On 2/7/2002 8:03, in article 45e6545c.0207012303.5a0e44fd at posting.google.com, "Seo Sanghyeon" wrote: > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> from types import ModuleType as module > >>> MyModule = module() > >>> MyModule > > >>> dir(MyModule) > [] > >>> > > What is this? You have constructed a new module dynamically. 'ModuleType' is the type of module objects. Calling this instantiates a new module object. The new module object is anonymous because you didn't give it a name, and "built-in" because it didn't get loaded from anywhere. It's dir is empty because no names have been set in the module's dictionary. >>> MyModule.__name__ = 'MyModule' >>> MyModule.__file__ = 'MyModule.py' >>> >>> MyModule >>> >>> def hello(): print 'Hello World' ... >>> MyModule.hello = hello >>> >>> dir(MyModule) ['__file__', '__name__', 'hello'] >>> >>> MyModule.hello() Hello World >>> This creates a module 'MyModule' exactly* as if you had written a file called 'MyModule.py' containing the 'hello' function and then imported it. Python lets you pretty much make anything dynamically that you like, including modules and classes. Jonathan * OK, not quite exactly... ;-) From dkuhlman at rexx.com Sun Jul 7 19:43:21 2002 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 07 Jul 2002 16:43:21 -0700 Subject: Embeding python i C++ References: Message-ID: Jardar wrote: > I have just started looking at using python as a > scriptinglanguage. I have successfully created extensions to the > python interpretter so there is noe problem calling C++ > functionality from python (used SWIG for creating wrappers). I > have also sucessfully called a python function from C++. The > problems starts when I want to pass a C++ object to a python > function. Passing simple strings og intergers are easy, but I can > find out how to pass whole objects. Can anybody help me out here. > > Thanks in advance > > Jardar What kind of object? If it is a C++ array, then convert it to a tuple or a list using the functions in the "Python/C API Reference Manual". For example, see http://www.python.org/doc/current/api/tupleObjects.html and http://www.python.org/doc/current/api/listObjects.html Similar C APIs are available for strings, longs, dictionaries, etc. In short, you can only pass *Python* objects from your C++ code to your Python code. If none of the existing Python types is what you want, it is also possible to implement new Python types in C/C++. Then you can, in your C/C++ code, create instances of your new type and pass them to your Python code. See "Defining New Types": http://www.python.org/doc/current/api/newTypes.html That's a bit more complex. But, if it is what you want, you will find a pattern for doing so in the source code distribution of Python. Look at Python-2.2.1/Objects/xxobject.c. You might also consider implementing a class in Python, passing the class object to your C++ code, creating an instance of the class in C++, then passing the instance back to your Python code. Whew! Actually, I don't know how to do this. But, it seems do-able and some of the needed functionality is described in "7.5.2 Instance Objects" at: http://www.python.org/doc/current/api/instanceObjects.html After your C/C++ code has created an instance of the Python class, here is a bit of C code for calling a method on that instance: char * name; /* Does the instance have an attribute "endElement"? */ if (PyObject_HasAttrString(instance, "endElement")) { name = "some value for Python"; /* Call the method, passing a string argument. */ result = PyObject_CallMethod(instance, "endElement", "s", name); if (PyErr_Occurred()) { PyErr_Print(); } /* if */ } /* if */ Hope this helps. - Dave -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman From gerhard.haering at gmx.de Sat Jul 20 15:47:25 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Jul 2002 19:47:25 GMT Subject: unloading imported modules References: Message-ID: Chris Liechti wrote in comp.lang.python: > xeon at dacreations.cjb.net (xeon) wrote: >> Is it possible in python intepreter to unload imported modules? or are >> there ways to refresh the loaded functions if ever the module is >> updated, other than restarting the intepreter? > [...] maybe autoreloading interests you too. here comes the little > bit log URL.... (one line, blah balh ;-) > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf- > 8&th=2ae8aac3beeb9859&seekm=mailman.1005899002.5050.python- > list%40python.org&frame=off Trick of the day learnt on #python: http://tinyurl.com/r22 http://makeashorterlink.com/?H56C21F41 Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From renzo.tomaselli at tecnotp.it Tue Jul 9 07:21:32 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 9 Jul 2002 04:21:32 -0700 Subject: adding methods on the fly References: <878dc260.0207080702.2be7ba9f@posting.google.com> Message-ID: <878dc260.0207090321.14e06bbe@posting.google.com> Alex Martelli wrote in message news:... > Py_CompileString (careful about underscore placement!-) won't let you > easily build a function (or unbound-method) object, which is what you > need (though you can get there eventually, but it's a long way 'round). Fairly disappointing. Since I plan to store such used-defined methods into a OO database, I would expect it being much more efficient to store them in a precompiled form. I still wonder why it's so hard (from a C/C++ perspective) to walk from a "def foo(self): pass" string to a callable object to be added to a class. > That being a given -- i.e., given that the client-code of your > extended objects is going to be Python, anyway -- why not take > the easy way out, and have said extensible objects be a Python > shell around a C++ core? A thin Python shell, which you can add > with a small effort by inheritance in Python 2.2, or more easily and > portably (with a loss of performance) by automatic delegation, > lets you extend to your heart's content. So, why not...? Ok, I'm not forced to fit all in C++, after all I define the features my platform is going to offer. An extra layer in Python is acceptable, provided I hide it from common usage (e.g. adding/invoking methods). So let's see this "easy" way in more details. Let's assume I created a C++ extension in module myExt, which exports a type for each C++ class to be wrapped (and this type is defined so that it can be inherited from). Then I would need to defined an empty class like: #P1: wrapping import myExt class foo(myFoo): # one class per object to wrap pass myExt.hook(foo()) Then from time to time someone adds a new method to class foo: #P2: declaration def m1(self, args): do_something #P3: appending foo.m1 = m1 #P4: execution and run it from C++ or from Python. Now, the entire game is C++ driven. P1, P2, P3 can be merged together in a string(P2 is an user-defined string) and run through PyRun_SimpleString. Now new method is attached to class foo and it can be run through PyObject_CallMethod on the hooked class instance. I still prefer a PyClass_New/PyMethod_New/PyInstance_New sequence from C++, but here we are back to the point of feeding PyMethod_New with appropriate value from pass P2 above. This is the missing link about which I couln't find anything on the list (dealing with callables is general is a black hole). Missing precompilation is another missing feature of this solution. > Another possibility is to look at Boost Python, if the schedule for their > new release 2 (supporting Python 2.2 fully) is compatible with your > timing constraints Several people suggested me to look at Boost, but I feel it deals primarily with extending, while I'm on the opposite side. On the other hand I don't feel good to add an entire package only for the purpose of adding new Python methods on the fly. Renzo From phr-n2002b at NOSPAMnightsong.com Wed Jul 31 21:42:56 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 31 Jul 2002 18:42:56 -0700 Subject: html forms, dicts and lists References: Message-ID: <7xy9br4an3.fsf@ruckus.brouhaha.com> Kai Keliikuli writes: > I'm wanting to do more with html forms and their processing > than I'm able to using the cgi module, but I've had no luck > RTFMing or googling. I want to interpret the following html > form inputs like so > > form: > interpreted: d = {'a':{'b':'foo'}} Don't do that, for the usual reasons it's bad to use 'eval' or 'exec'. Even if you don't do it the obvious way with exec, you'll have to do complicated enough filtering to have a big chance of leaving some hole where a hostile client can take over your application. Just use ordinary form and field names and interpret them in your cgi. From tdelaney at avaya.com Tue Jul 2 20:01:33 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 3 Jul 2002 10:01:33 +1000 Subject: Performance question about math operations Message-ID: > From: Andrew P. Lentvorski [mailto:bsder at mail.allcaps.org] > > Please give me a *little* credit. I am aware that Python doesn't do > constant folding, etc. In the real code, those constants are > variables. > However, my point was that the floating point operations are > sufficiently > slow *even with constants* that they dominate the variable references. How could we give you that credit? Most people have never seen you here before, so we had to base our judgement on your level of understanding on the code you posted. That code showed no understanding of standard python optimisations and idioms, so everyone presumed you were a beginning Python programmer. If you have *real* code that demonstrates what you want to do you are more likely to get helpful responses. What you posted was at a beginner's level, and so you received responses targetted to a beginner. > What I was hoping to provoke was a discussion about hoisting > integer and > floating point dominated paths into a Python optimization. > Or possibly > looking at the efficiency of the dispatch table for FP and integer > dominated paths. There have been *many* discussions about this. For the most advanced projects, look at: http://sourceforge.net/projects/psyco/ http://homepages.ulb.ac.be/~arigo/psyco/ http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > Terry Reedy wrote: > > Use numerical Python extensions which works with arrays of unboxed > > floats and which only has to interprete +-*/ once each for entire > > Well, I tried that. I have used both Numeric and SciPy for a circuit > simulation engine and it works well; it fails for a layout editor. > Special data structures are required to handle the 2-D region querying > which is the hallmark of a VLSI layout editor. (10,000,000 polygons - > 10^4 difference in coordinate values (.1 um to 1cm)) In that case, you should have mentioned that fact. The standard response to "This is too slow in Python" is "Look at the Numeric extension". Is there any reason you can't perform the calculations in Numeric, then transform the result to the data structure you need? For speed you may find that you need to write a small C extension to Python, which can itself work with the Numeric package. The reason that Python is slow at numeric calculations is because it cannot assume that an object is indeed numeric when it performs the calculation. Psyco is an attempt to remove this restriction. Pyrex is another attempt, from a different angle (making it possible to write Python extensions in a Python-like language). Tim Delaney From m.faassen at vet.uu.nl Wed Jul 17 17:53:31 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 17 Jul 2002 21:53:31 GMT Subject: Fakes... References: Message-ID: Flash Callahan wrote: > approximately 6 billion(+or-6) of us fakes tend > to disagree with your contention that you and your ally > are the only self-aware sentient creatures on the planet. But of course you're all wrong, the Python Secret Underground has discovered that it is really true that From edream at tds.net Tue Jul 30 10:57:37 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 30 Jul 2002 14:57:37 GMT Subject: Leo.py: Some Thoughts References: <3D44EAA9.7010607@thomas-guettler.de> Message-ID: > you can embed other widgets, as well as images, in a Text > widget. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Jeez, how did I miss this???? Thanks so much, Fredrik, for pointing this out. Clearly, I can use the Tkinter PhotoImage or BitmapImage classes to insert images into text!! > what other capabilities do you need? Nothing from Tk. A way of representing the annotation itself and what it contains in plain text. That can probably be done by adding some tags somewhere to Leo's XML file format. Some minor magic is also needed to represent images when they aren't on the screen. I also need a command so the user can insert images in the first place...Trivial stuff. If you could see me you would be amused. I'm so excited I can hardly sit still in my chair :-) Fredrik, while you are being so helpful, is there some way to use an embedded window to render HTML or postscript? Anything else that might help? Again, many thanks for lifting the blinders from my eyes! Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From loewis at informatik.hu-berlin.de Wed Jul 31 09:02:18 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 31 Jul 2002 15:02:18 +0200 Subject: external binary reading standard in References: <3D479E31.4E46CFD5@iki.fi> Message-ID: Markus O Kaukonen writes: > How to execute a external (binary) program reading from standard input > in a python code ? > For example : /home/mok/my_prog.bin < my_input.txt > > My system is Linux and the binary is written originally in fortran 90 > (if that should matter). You want the standard input to be from a file, and you want to get the standard output in the Python script? I believe you need a pipe/fork/exec combination for that. It works roughly like that fdin, fdout = os.pipe() pid = os.fork() if pid==0: # child os.dup2(fdout, 1) fdin = os.open('my_input.txt',os.O_RDONLY) os.dup2(fdin, 0) os.execv('/home/mok/my_prog.bin', ['my_prog']) # parent fromchild = os.fdopen(fdin, "r") HTH, Martin From phr-n2002b at NOSPAMnightsong.com Tue Jul 9 23:20:41 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 09 Jul 2002 20:20:41 -0700 Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: <7xwus4i7zq.fsf@ruckus.brouhaha.com> William Park writes: > 3. Daytime Protocol (RFC-867, port 13): > date -u -s `telnet time.nist.gov 13 | grep UTC | cut -f2,3 -d' '` > > This is shell solution that I've been after. Woo hoo! I knew about RFC 868 but it didn't occur to me to use a telnet command in a pipeline. I thought telnet had to interact with the control tty. From ms at NOMAIL.de Mon Jul 15 09:22:32 2002 From: ms at NOMAIL.de (Michael Schmitt) Date: Mon, 15 Jul 2002 15:22:32 +0200 Subject: implementing large trees Message-ID: Hello. I'm trying to implement a large tree data structure, which does not fit into memory. Based on an in-memory implementation, which has two dictionarys, one for all nodes and one for all edges, the first idea was to use shelve to have disc-based dictionaries. But for usual tree operations (depth-first traversal, breadth-first traversal) the shelve based tree was much slower, than the tree using two dictionaries and relying on swapping. What is the "best" way to implement such a tree? Is it possible to improve performance without knowing how the tree is traversed? What about having a breadth-first and a depth-first cache, that prefetch nodes and edges after each access? Thanks for any hints. Michael From tjreedy at udel.edu Fri Jul 12 11:48:10 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Jul 2002 15:48:10 GMT Subject: Making code 2.1 compatible References: <3D2EED98.BD59D615@tds.net> Message-ID: <_SCX8.60622$Bt1.3211400@bin5.nnrp.aus1.giganews.com> "Edward K. Ream" wrote in message news:3D2EED98.BD59D615 at tds.net... > Is there a way to ask Python [2.2] not to allow 2.2 constructs? No. You can import the future, but not the past. Reason: the near future disappears when it becomes the present. The past grows without end. TJR From jonathan at onegoodidea.com Tue Jul 16 04:39:23 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 16 Jul 2002 09:39:23 +0100 Subject: implementing large trees References: Message-ID: On 15/7/2002 14:22, in article aguia9$bks$06$1 at news.t-online.com, "Michael Schmitt" wrote: > I'm trying to implement a large tree data structure, which does not fit > into memory. Based on an in-memory implementation, which has two > dictionarys, one for all nodes and one for all edges, the first idea was to > use shelve to have disc-based dictionaries. > > But for usual tree operations (depth-first traversal, breadth-first > traversal) the shelve based tree was much slower, than the tree using two > dictionaries and relying on swapping. > > What is the "best" way to implement such a tree? Is it possible to improve > performance without knowing how the tree is traversed? What about having a > breadth-first and a depth-first cache, that prefetch nodes and edges after > each access? Virtual memory is a wonderful thing. I'd focus on optimising your algorithms and layout to have as much locality of reference as possible and let VM do the caching for you. In particular I'd look at how you build the tree in the first place. If you construct it in a very random fashion so that adjacent edges and nodes are scattered all over memory then walking the tree will always result in poor locality of reference. Take a look at the VM stats. If: Number of Page Ins + Number of Page Outs ---------------------------------------- ~= Number of Passes Total Virtual Set Size then you're probably not going to do much better. If it's substantially larger than the number of tree walks you do then you're memory layout is a mess and it's striding. Unless you can get it laid out neatly you'll have trouble. Even if you write it to a file and try to implement your own intelligent loading, you'll just end up hitting the same problem with the disk cache. If you have a large number of passes, then you might want to consider building the tree in memory and traversing it once to write it out evenly and compactly to a file. This will have very poor performance, but the resulting file you can mmap back in and walk neatly. Jonathan From fredrik at pythonware.com Sat Jul 27 17:57:21 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 23:57:21 +0200 Subject: Two RE proposals References: Message-ID: <007201c235b8$9745bde0$ced241d5@hagrid> hi david, > > python already has string substitution. if it needs better string > > substitution, that should be solved outside the RE engine. > > why? I'm not suggesting a general solution. I thought about suggesting it, > but I figured there where probably more ! characters in general strings then > in re strings. And, there is ample precedent for characters that have no > special meaning outside of re strings. Oh yeah - and i'm not suggesting a > modification to Python, i'm suggesting a modification to re-language. you're suggesting a change to the RE language that will silently break existing patterns. > > besides, having library modules peek in your local namespace is > > really bad style. > > Damn - there goes inspect! I wonder what else displays bad style? > Introspection/reflection considered harmful? are you using inspect in production code? seriously? some of the problems I see with introspective interpolation include performance issues, future portability (we want more implementations, not less), and security issues. and the "yet another syntax" problem, of course. > > and your proposal will break existing code. > > Unsubstantiated. How can you make that assertion? ! and < and > have a meaning today. if someone uses them, the RE engine does things in a special way. after your change, the RE engine will (sometimes silently) interpret them in a different way. breaking people's code is bad. silently breaking code is even worse. > Aside from which, has no Python enhancement ever broken existing > code? there's always a cost/benefit ratio to take into account. as it stands, I'd say your proposal has little benefit (python already supports string interpolation) and some unknown cost (silent breakage, yet another way to do it, adding non-standard syntax to multiple RE implementations). > > the following approach works in all existing versions of Python, > > gives you syntax highlighting in all existing Python editors, etc: > > > > def i(*args): > > return string.join(map(str, args)) > > > > word = r"\w*" > > punct = r"[,.;?]" > > wordpunct = re.compile(i(word, punct)) > > > > if = r"if" > > term = r"something" > > num = r"\d*" > > op = r"[-+*/]" > > factor = i(num, "\s*", op, "\s*", num) > > expr = i(term, factor) > > if_stmt = re.compile(i(if, "\s*\(?\s*", expr, "\s*\)?\s*:")) > > Wow, you make Skip's example seem positively eloquent in contrast. if you have a problem with lists of variables and "literals", separated by commas, do you ever get anything done in Python? ;-) > > if you're doing lots of RE stuff, you can trivially extend this to > > support RE-oriented operations: > > > > if = literal("if") > > op = set("-+*/") > > factor = seq(num, ws, op, ws, num) > > > > (google for "rxb" for a complete implementation of that idea) > > looked - not impressed. Might be of interest to XSchema or Relax-NG people. > Not very re-like. intestingly enough, the rxb approach closely mirrors what the engine does on the inside. someone should really do a usability study, comparing perl-style REs with rxb/snobol etc. > > > 2. Make r"(a|b)*" mean any number of a's or b's. > > > > it does mean any number of a's or b's. but no more than a > > single a or b will end up in the group. > > Huh? Actually, re rejects the pattern, or if you try hard enough, goes > into an infinite loop. >>> import re >>> p = re.compile("(a|b)*") >>> p.match("ababa").groups() ('a',) >>> p.match("babab").groups() ('b',) >>> p = re.compile("((?:a|b)*)") >>> p.match("ababa").groups() ('ababa',) >>> p.match("babab").groups() ('babab',) does exactly what it's supposed to do. what Python version are you using, and what do your patterns and target strings look like? infinite loops are usually caused by careless use of the "*" operator; in a worst case scenario, you'll end up with what is essentially a bunch of nested loops, each looping over "the rest of the string". > > fixing the RE is done in a similar fashion: make sure the group > > matches everything you want to put in the group: > > > > r"((?:(a|b)*)" > > > > if you want lists of matching things, use findall. > > So hard to embed findall into an re pattern - what's your secret? if your string isn't regular enough, use findall on the matched group: p = re.compile("((?:a|b)*)") >>> p.match("ababa").groups() ('ababa',) >>> re.findall("(a|b)", "ababa") ['a', 'b', 'a', 'b', 'a'] or if you want to play with undocumented features, use a scanner object: http://effbot.org/guides/xml-scanner.htm > What do I do if I want a better Python? Do we wait for specific people to > make suggestions or can anyone join in? keep pushing. but expect pushback. in this case, I suggest checking the string interpolation PEPs and perhaps checking the newsgroup archives for similar ideas, and spend a little more time thinking about how to avoid breakage. the next step is writing a (pre) PEP and post it to the list. bonus points if the PEP covers alternative solutions as well. From keith_s at ntlworld.nospam.com Fri Jul 26 06:21:06 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Fri, 26 Jul 2002 11:21:06 +0100 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> <3D3EFC18.30705@ntlworld.nospam.com> Message-ID: <3D412292.1030608@ntlworld.nospam.com> Chris Liechti wrote: > this class isn't what you want... you need to supply a callable either name > that method __call__ and add a "return" of the result, or much simpler, > leave it away and use your "input" directly below. OK, so now I do: PyRun_SimpleString("interact('---Starting Python---', input)\n"); where my input function looks like: static PyObject * input(PyObject *self, PyObject *args) { char *string; if (!PyArg_ParseTuple(args, "s", &string)) return 0; gld::gMsgView()->printf(MSG_NONE, "%s", string); return PyString_FromString(""); } (I'm returning an empty string just to test the above). This goes into an infinite loop - I'd have expected it to output the prompt '>>>' once, then wait for a non-null string. Any ideas what's wroong? I've looked at the implementation of builtin_raw_input() and can't find any clues to help. - Keith From david.levy at xrce.xerox.com Tue Jul 23 03:41:45 2002 From: david.levy at xrce.xerox.com (David Levy) Date: Tue, 23 Jul 2002 09:41:45 +0200 Subject: SOAP.py and complex types References: <3D3BDD02.3997B185@xrce.xerox.com> Message-ID: <3D3D08B9.5052411C@xrce.xerox.com> thanks that's cool but he is not using the SOAP interface actually ! one the HTTP GET (url passed parameters) one so that just helps me for calling Amazon but no others complex web services ... :( Fredrik Lundh wrote: > David Levy wrote: > > > I am using Python to call Web Services, with SOAP.py (0.9.7) library > > However I can't figure how to use it when input messages requires user > > defined types like the one for the new Amazon web service : > > http://soap.amazon.com/schemas/AmazonWebServices.wsdl > > > > does anyone know how to do it ? > > dunno, but it looks like mark pilgrim might have figured > it out: > > http://diveintomark.org/projects/#pyamazon > > -- _____________________________________________________________ David Levy Xerox Research Centre Europe 6, ch. de Maupertuis F - 38240 Meylan Email david.levy at xrce.xerox.com http://www.xrce.xerox.com From jdhunter at nitace.bsd.uchicago.edu Fri Jul 26 10:53:39 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 26 Jul 2002 09:53:39 -0500 Subject: boost: return pointer to base class References: Message-ID: >>>>> "Jacek" == Jacek Generowicz writes: Jacek> 1) Expose a C++ class hierarchy to python (using Boost) Jacek> 2) Allow all the exposed classes to be subclassed, with Jacek> correct overriding of virtual fuctions Jacek> 3) Expose a C++ function which returns a pointer to the Jacek> base class. In general, returning passing raw pointer in boost::python is problematic. Have you read http://www.boost.org/libs/python/doc/pointers.html? I was able to compile your code by replacing the raw pointer return with a shared pointer. Will this suit your needs? #include boost::shared_ptr rcbpta() { return boost::shared_ptr(new concrete()); } John Hunter From glongman at ilangua.com Wed Jul 3 11:45:34 2002 From: glongman at ilangua.com (Graeme Longman) Date: Wed, 03 Jul 2002 16:45:34 +0100 Subject: Regular expressions in python Message-ID: <3D231C1E.FBB4BE89@ilangua.com> Hi, I'm using the python module re to search through strings of html text but I have found that it is taking too long using the seach method. I am looping though a list of regular expressions and I find that it takes much longer when no match is found for the expression than it does when a match is found. Is this normal ? I have fixed the problem for now by using string.find() before searching the text but was wondering if anyone had any ideas on a better technique. Is there something else I should be using ? I am using '.*' and re.DOTALL in my expressions but that doesn't seem to be the problem. Thanks for any help in advance. Graeme From bhoel at web.de Sun Jul 21 15:56:45 2002 From: bhoel at web.de (Berthold Höllmann) Date: 21 Jul 2002 21:56:45 +0200 Subject: ANN: Pyrex 0.3.4 References: Message-ID: Matthias Baas writes: > On Fri, 19 Jul 2002 08:21:30 GMT, "Fredrik Lundh" > wrote: > >Matthias Baas wrote: > For the sake of understanding, I tried to use this macro, but it takes > an argument. What's that argument supposed to be? > I had a look in the Python source and also read about the macro > USE_DL_EXPORT. Do I have to define that myself before including > Python.h (but DL_EXPORT was defined even without defining > USE_DL_EXPORT myself)? Well, whatever I tried, I didn't really manage > to compile the module that way.... > > - Matthias - > looking into Modules/python.c I find extern DL_EXPORT(int) Py_Main(int, char **); So I guess the macro takes the return value of the defined function as argument. Greetings Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From claird at starbase.neosoft.com Tue Jul 9 16:58:17 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 9 Jul 2002 15:58:17 -0500 Subject: expect module and/or functionality? Or SSH wrapper module? References: Message-ID: <12FA856FE2F2C586.CC065FAE6BEA5B91.D5D063F757FFD03B@lp.airnews.net> In article , Donn Cave wrote: >Quoth claird at starbase.neosoft.com (Cameron Laird): >... >| If not, no, you can't Expect with pure Python; there's no >| practical way to get the pseudoterminal munging right without >| calls into the C run-time library that Python itself can't >| access. > >| I'm working on techniques to use standard distribution instal- >| lations of (Tcl-based) Expect and (pure) Python to achieve >| general results. The idea is that many hosts--essentially >| all Linuxes, for example--are already equipped with these >| executables, so all you'd need to install are your pure-Python >| scripts. I don't have these ready yet, though. > >That will be interesting. > >There is actually some pseudotty support in posixmodule. Not >sure if anyone has ever managed to make any real use of it - >opening a pseudotty is only the start of your problems - but >on some platforms (quite a few more than come with Expect), >you can at least open a pseudotty. Expect is a big step up >from there, though. > > Donn Cave, donn at u.washington.edu I'll keep you posted on my progress. Also, it was a grievous error for my previous follow-up to fail to mention PySSH. That's the *real* starting point I should have recommended. PLEASE be aware that you don't have to have Expect on the host where you want to use it. makes exactly that point at greater length. In particular, it's some- times possible to control a platform even without being able to program ptys there. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From shalehperry at attbi.com Fri Jul 19 17:53:28 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 19 Jul 2002 14:53:28 -0700 (PDT) Subject: Python 2.3 In-Reply-To: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: On 19-Jul-2002 Rhymes wrote: > > When Python 2.3 will be released? > > I've read the "what's new" and i'm waiting generators and true > division :-) from __future__ import generators (-: From shagshag13 at yahoo.fr Wed Jul 17 12:00:50 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 17 Jul 2002 18:00:50 +0200 Subject: how to ask google, altavista or another search engine... References: Message-ID: "John Hunter" > If you register (free) with google at > > http://www.google.com/apis/ > > you can use pygoogle > thanks for that ! i just have registered ! but i'm also looking for others search engines wrappers like altavista or metacrawler, etc. s13. From phr-n2002b at NOSPAMnightsong.com Tue Jul 30 06:42:44 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 30 Jul 2002 03:42:44 -0700 Subject: signature for a file ? References: <7xeldlh6o8.fsf@ruckus.brouhaha.com> Message-ID: <7xy9bt8pjv.fsf@ruckus.brouhaha.com> "Shagshag13" writes: > > same MD5 checksum, it's basically certain that the files are > > identical. > > thanks for this, (so no need to use SHA or CRC ?) SHA and MD5 do pretty much the same thing. SHA is a little newer and preferred for high security uses, but that's not really what you're doing, so it doesn't matter much. MD5 is a bit faster. CRC's are sort of the same idea, but they're easier to fool. If you use a 32-bit CRC and have a lot of files (say 100 thousand), chances are some two different files (i.e. contents not the same) will have the same CRC. From huaiyu at gauss.almadan.ibm.com Tue Jul 30 18:37:53 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 30 Jul 2002 22:37:53 +0000 (UTC) Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> <3d46c6a2$1_1@hpb10302.boi.hp.com> Message-ID: Daniel Fackrell wrote: >"John Roth" wrote in message >news:ukddqtelmp6eda at news.supernews.com... >> The reason I say "indenting 2" is that you need two >> dedents to make it work: one to close the def, which does >> not have it's own indent, and one to finish off the expression >> in which the def is imbedded. > >Again, the problem is that Python must assume that when it sees code >indented further than the previous line, a single indent is intended. It >has no way of knowing how many indents you mean unless something is actually >indented to each level along the way. I don't quite get the idea why it has to indent 2. See examples below. >In addition to that, indentation is currently ignored inside (), {}, [], >strings, and on lines following an escaped newline. Some of that could >change, perhaps, but it seems to me that it might break existing code. > >I do see merit in this discussion, though, because I see class and def >statements as really being a shorthand for doing two things at once, namely >creating a function and then binding it to a name. > >Admittedly, there are probably cases where the second part does not apply >all that well. Perhaps a case where you want a list or dict of functions >would be one such case. Binding to the name simply adds a step along the >way. Passing a callable object as a parameter to another callable object >would probably be another such case. Here's an example to exand on the idea. a = { 'func1': def (x,y): lots of things more things return x+y 'func2': def (x,y): lots of things more things return x-y 'func3': def (x,y): lots of things more things return x-y } For vertical scoping, it is not necessary to separate items with commas. >The issue quickly becomes readability, though. Would you want to be able to >do a complex multi-line def or class statement inside an assignment creating >a list, for example? And how would you do that without indentation? > >funcList = [ Insert idea here ] This does not look too bad, although it does take a while to get used to. For simple functions still lambdas look better. curries = [ def (x): return def (x,y): return x+y def (x): f = def (x,y): return x-y return f lambda x: lambda y: x*y, class: def __init__(self, x): self.x = x def __call__(self, y): return x/y ] Huaiyu From andreas at kostyrka.priv.at Tue Jul 30 05:34:13 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 30 Jul 2002 11:34:13 +0200 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) In-Reply-To: References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: <1028017189.1316.27.camel@vaio2> Am Sam, 2002-07-27 um 09.11 schrieb Alex Martelli: > The lambda solution doesn't work. At all. It gives you a SyntaxError > if you try it! Well, I usually type sys.stdout.write in a lambda without even thinking to much :) > > lambda cannot include a statement. print is a statement. Oooops...!-) > > So, if you structure your code with lambda, the moment you want > to add a print statement, boom -- can't do. You have to restructure Why would I want to add a print statement for debugging. (Admittingly I've done this before, but these days are long gone) With python it's trivial to define an automatic instrumentation with the tracing support. Actually, print statements are used usually by people to lazy to do it right. Usually, when you get to your first hard problem in a small piece of old code (say 25kloc, deployment started in 1996, and development never stopped) where you need much instrumentation to get a feel how certain things are done. (Well the app contains at least 3 seperate layers of db abstraction layers, each one on top of the older one ;) ) > your code to use def instead. When you remove the print after it's > done its debugging-help job, will you restructure once again to > take the def away in favor of lambda... and again NEXT time you > need to have a statement there too, etc, etc...? What a lot of > purposeless code churning...! Again, why would I do that? lambda x: x -> lambda x: (x,sys.stdout.write("x=%d\n" % x))[0]) > Use def and avoid all of this silly self-imposed useless work. Use the best tool for the task. lambda are quite nice for small wrapper functions that rearrange arguments. Basically, lambda can sometimes substitute for the code block objects (like in smalltalk). So IMHO, there is nothing wrong with lambda. Just don't use a fork to eat soup. At least do not complain about the experience to c.l.p ;) Andreas From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 03:30:50 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 00:30:50 -0700 Subject: Python robot web client? Message-ID: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> Are there any Python robot web clients around, sort of like Perl LWP? I mean something fancier than urllib, that parses the HTTP headers and remembers any cookies. It would also be great if it parsed the HTML enough to find the form fields, links, and so forth. I guess I can implement what I need, but thought I'd ask first if something like it is already available. Thanks. From trentm at ActiveState.com Wed Jul 10 16:33:57 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 10 Jul 2002 13:33:57 -0700 Subject: os.path and Windows UNC paths In-Reply-To: <9ecef7534b.tim@worthy.demon.co.uk>; from tim@worthy.demon.co.uk on Wed, Jul 10, 2002 at 07:02:44PM +0100 References: <9ecef7534b.tim@worthy.demon.co.uk> Message-ID: <20020710133357.E22074@ActiveState.com> [Tim Howarth wrote] > I've been trying to use os.path.exists and os.path.isdir on > Windows(2000) UNC paths with Python 2.2 but it doesn't seem to behanve > sensibly. > There is a bug for this already: http://python.org/sf/513572 I tend to use this function: def _isdir(dirname): """os.path.isdir() doesn't work for UNC mount points. Fake it. # For an existing mount point (want: _isdir() == 1) os.path.ismount(r"\\crimper\apps") -> 1 os.path.exists(r"\\crimper\apps") -> 0 os.path.isdir(r"\\crimper\apps") -> 0 os.listdir(r"\\crimper\apps") -> [...contents...] # For a non-existant mount point (want: _isdir() == 0) os.path.ismount(r"\\crimper\foo") -> 1 os.path.exists(r"\\crimper\foo") -> 0 os.path.isdir(r"\\crimper\foo") -> 0 os.listdir(r"\\crimper\foo") -> WindowsError # For an existing dir under a mount point (want: _isdir() == 1) os.path.mount(r"\\crimper\apps\Komodo") -> 0 os.path.exists(r"\\crimper\apps\Komodo") -> 1 os.path.isdir(r"\\crimper\apps\Komodo") -> 1 os.listdir(r"\\crimper\apps\Komodo") -> [...contents...] # For a non-existant dir/file under a mount point (want: _isdir() == # 0) os.path.ismount(r"\\crimper\apps\foo") -> 0 os.path.exists(r"\\crimper\apps\foo") -> 0 os.path.isdir(r"\\crimper\apps\foo") -> 0 os.listdir(r"\\crimper\apps\foo") -> [] # as if empty contents # For an existing file under a mount point (want: _isdir() == 0) os.path.ismount(r"\\crimper\apps\Komodo\latest.komodo-devel.txt") -> 0 os.path.exists(r"\\crimper\apps\Komodo\latest.komodo-devel.txt") -> 1 os.path.isdir(r"\\crimper\apps\Komodo\latest.komodo-devel.txt") -> 0 os.listdir(r"\\crimper\apps\Komodo\latest.komodo-devel.txt") -> WindowsError """ if sys.platform[:3] == 'win' and dirname[:2] == r'\\': if os.path.exists(dirname): return os.path.isdir(dirname) try: os.listdir(dirname) except WindowsError: return 0 else: return os.path.ismount(dirname) else: return os.path.isdir(dirname) -- Trent Mick TrentM at ActiveState.com From emile at fenx.com Tue Jul 9 17:38:07 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Jul 2002 21:38:07 GMT Subject: Python tutorial References: <3d2a9b39.94944531@news.skynet.be> Message-ID: <3JIW8.450828$352.70678@sccrnsc02> Henk > Is there any Python tutorial out there which happens to be written in > Dutch? > Good question! It's well known that all good pythoneers speak dutch, but apparently not all write in it. I'm not sure how far this will get you, but I only found this one link: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-vertaling.html Perhaps there's more? -- Emile van Sebille emile at fenx.com --------- From edream at tds.net Fri Jul 12 10:54:21 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 12 Jul 2002 14:54:21 GMT Subject: Making code 2.1 compatible Message-ID: <3D2EED98.BD59D615@tds.net> Hi, Is there a way to ask Python not to allow 2.2 constructs? Having Python complain when producing .pyc files would be good enough. Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From max at alcyone.com Wed Jul 10 02:26:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Jul 2002 23:26:05 -0700 Subject: A better self References: Message-ID: <3D2BD37D.8CF82AE@alcyone.com> Matt Gerrans wrote: > In keeping with that concept, '..' would be referring to the base > class > (equivalent to java's "super"). I think that's definitely mixing metaphors. For one thing, which base class? Python supports multiple inheritance. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From mgerrans at mindspring.com Sun Jul 14 16:29:14 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sun, 14 Jul 2002 13:29:14 -0700 Subject: Fakes... References: Message-ID: [snipped harangue] > ... With 6 billion people... [snipped diatribe] > ... 99.9999999% of the > population. I know this because I've searched, and in > my search have so far only found one true ally... Well, I didn't have time to peruse this rant, but since you posted this to comp.lang.python, I skipped to the relevant (loosly speaking!) part: >>> round((1.0-99.9999999/100)*6*math.pow(10,9)) 6.0 Looks like good news: you only have 4 more like yourself to find -- You probably have better odds in high-population areas like China, India and Africa than you do in comp.lang.pytyon... From djaquay at yahoo.com Wed Jul 10 10:45:40 2002 From: djaquay at yahoo.com (David Jaquay) Date: Wed, 10 Jul 2002 07:45:40 -0700 (PDT) Subject: wxPython wxTreeCtrl EVT_TREE_KEY_DOWN Message-ID: <20020710144540.50316.qmail@web10005.mail.yahoo.com> In wxPython, I'm using wxTreeCtrl. I've setup a EVT_TREE_KEY_DOWN handler as such: EVT_TREE_KEY_DOWN( self, treeID, self.OnKeyDown ) In OnKeyDown, I have: def OnKeyDown( self, event ): key = event.GetKeyEvent().GetKeyCode() if key == WXK_DELETE: print 'in here', type( event ), event.__class__, event.__dict__ item_ctl = event.GetItem() item_ob = self.tree.GetPyData( item_ctl ) item_txt = self.tree.GetItemText( item_ctl ) print item_ctl, item_ob, "'" + item_txt + "'" But item_txt is always empty, and item_ob is always None, even though I'm on a good tree node when I press key. What might I be doing wrong here? Any ideas? The output from pressing the delete key is: in here wxPython.controls2.wxTreeEventPtr {'this': '_bfffe6f0_wxTreeEvent_p', 'thisown': 0} None '' Thanks lots, Dave __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com From bogus@does.not.exist.com Mon Jul 29 18:18:36 2002 From: bogus@does.not.exist.com (chris) Date: Mon, 29 Jul 2002 18:18:36 -0400 Subject: pretty basic: get variable name from list of strings? Message-ID: in the specific, if I have a list animals = ['horse_0', 'horse_1'] horsenames = ['smokey', 'silver'] how do assign variables with those strings as names? ie, I want horse_0 = "smokey" horse_1= "silver" but if I write animals[0] = "smokey", it replaces the value, it doesn't assign it. What I want is like assign() or eval() in other languages. you can imagine i am trying to iterate over large indexes of animals[i] = 'horse_' + str(i) and then assign them from a value list or even screw the variable list and instead iterate over the value list 'horse_' + str(i) = horsenames[i]. but i'm missing the key command to tell python "treat this string like code and not a string." thx, chris From jdhunter at nitace.bsd.uchicago.edu Thu Jul 18 11:35:40 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 18 Jul 2002 10:35:40 -0500 Subject: Fail pyton build. What to do References: Message-ID: >>>>> "edadk" == edadk writes: edadk> Hi, I am build python 2.1.1 on Solaris/Intel 8 and get the edadk> error meassage below. [I do not need the audio stuff at edadk> all. Can I shut it off for instace.] edadk> What can I do? I haven't built python on that platform before, but my guess is that just turning off one feature that you don't want won't work. If one thing is broken, it's often the case that something else is as well. In this case it may simply be that you need to find where sun/audioio.h is on your system and explicitly set it in your include path. If you have the GNU findutils installed, you can do locate audioio.h If not, try searching for it with find find /usr -name audioio.h find /opt -name audioio.h If you find it on your system, you can inform python of it's whereabouts with ./configure --includedir=/the/path/to/dir/that/contains_sun If the dir is, for example, /opt/include/sun/audioio.h, you would do: ./configure --includedir=/opt/include Warning, I just tried this to test it and contrary to my expectations, /opt/include was not included with a -I flag in my test make. I do not know if this is a problem with the 2.1.3 configure script or my misunderstanding of how the --includedir flag works. You can always use the brute force, hand edit the Makefile approach after configure to manually add the -I/opt/include flag to the CFLAGS line, if necessary. John Hunter From greg at cosc.canterbury.ac.nz Fri Jul 19 20:23:01 2002 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 20 Jul 2002 12:23:01 +1200 Subject: Dict in binary pickle causes exception Message-ID: <3D38AD65.98564CB7@cosc.canterbury.ac.nz> When I try to unpickle a pickle containing a dictionary that was written in binary format, I get the following exception: TypeError: dict objects are unhashable The same thing happens whether I use pickle or cPickle to do the unpickling. Is this a known limitation, or a bug? The non-binary format handles dictionaries just fine, and I don't see why the format should make a difference to what is picklable. Also, I can't find any mention in the documentation about any additional restrictions when using the binary format. I'm using MacPython 2.2. Greg From zopestoller at thomas-guettler.de Wed Jul 3 05:01:07 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 03 Jul 2002 11:01:07 +0200 Subject: Syntax Error at end of file Message-ID: <3D22BD53.7020507@thomas-guettler.de> Hi! I get the following error-message: """ File "", line 254 ^ SyntaxError: invalid token """ This wrror occurs at the end of the file. I think it is because a left a (, ' or " open. Is there a tool which can give me the line of the opening character? I programmed a lot and don't want to scan a lot of lines for an not closed paranthesis thomas From vvainio at tp.spt.fi Thu Jul 4 10:02:14 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 4 Jul 2002 07:02:14 -0700 Subject: REPEAT... UNTIL ? References: Message-ID: beej at piratehaven.org (Beej J?gensen) wrote in message news:... > (The other side of the coin is that my only argument for more looping > primitives is that while-1 loops are ugly-looking, and don't make for > the most readable code. Some people disagree or feel it's less > important. And personally I always feel like I'm undergoing some kind > of algorithmic failure when I code one; like I must not be doing the > Right Thing. But in Python, it is.) Strangely enough, while 1 - loop is quite often the most intuitive way to do things, yet it's (implicitly) frowned upon in many programming language cultures. The same applies to calling 'continue' instead of elif. Flat is good. This seems to be mostly a documentation issue. It would probably feel slightly less awkward if the keyword 'loop' was an alias for 'while 1', but that will never happen. -- Ville From b.maryniuk at forbis.lt Mon Jul 22 06:19:28 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 22 Jul 2002 12:19:28 +0200 Subject: ssh and Python In-Reply-To: References: Message-ID: <200207221219.28236.b.maryniuk@forbis.lt> On Sunday 21 July 2002 20:34, John Hunter wrote: > import os > h = os.popen('ssh -2 somehost.com ls') > print h.read() That's solves half of problem. How to automatically pass the password? Yes, you need a pipe to write in... -- Sincerely yours, Bogdan M. Maryniuck Microsoft is not the answer. Microsoft is the question. NO (or Linux) is the answer. (Taken from a .signature from someone from the UK, source unknown) From peter at engcorp.com Fri Jul 12 17:44:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Jul 2002 17:44:02 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> <120720020953486319%pecora@anvil.nrl.navy.mil> Message-ID: <3D2F4DA2.8EBA61D@engcorp.com> "Louis M. Pecora" wrote: > > In article <3D2E508C.DBDF9E52 at engcorp.com>, Peter Hansen > wrote: > > > > Just go and design + develope your own keyboard. > > > > Since you post without smileys, I can only assume you are serious? > > > > To which my response is: you can't be serious. :-) > > > > (Hint, the original was a joke... note the partial wink. I do > > hate underscores, but concluding from that that my best option > > is to design and develop my own keyboard is just bizarre.) > > Yes, I should have added a smilely. :-) Sorry. > > But my proposal is no more bizzare than yours suggesting we design our > own language or such. > > Both proposals are in smilely land. I hope you agree. ;-) No problem about the smileys, although you're mistaken about the origin of the suggestion that someone design his own language. It was Bo, to whom I was replying (humorously, I hoped) who suggested that, not I. As it appears he was also the origin of the 'develope' which I thought you first used, it seems we both made the wrong attributions! :-) Cheers, -Peter From fredrik at pythonware.com Thu Jul 18 11:06:20 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Jul 2002 15:06:20 GMT Subject: Sorting list of objects on arbitrary attribute References: <3D36AD49.2020305@mxm.dk> Message-ID: "Max M" wrote: > If something like it isn't included in the standard library, how come? from the "python best practices" collection: http://mail.python.org/pipermail/python-dev/2002-June/025940.html "It's easier to write appropriate code from scratch in Python than to figure out how to *use* a package profligate enough to contain canned solutions for all common and reasonable use cases." -- tim peters From mfranklin1 at gatwick.westerngeco.slb.com Tue Jul 30 07:49:23 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 30 Jul 2002 11:49:23 +0000 Subject: Pmw.MenuBar hotkeys In-Reply-To: References: Message-ID: <200207301049.g6UAnj011173@helios.gatwick.geco-prakla.slb.com> On Tuesday 30 Jul 2002 8:35 am, Matthias Huening wrote: > Martin Franklin wrote in > > news:mailman.1027968050.16442.python-list at python.org: > > On Monday 29 Jul 2002 6:23 pm, Matthias Huening wrote: > >> Hi, > >> > >> I seem unable to get the hotkeys to work with Pmw.MenuBar. > >> They should be activated with +hotkey, but nothing happens... > >> When a menu is opened, the hotkeys of the different menu items do > >> work. The problem is only with the hotkeys on the menu bar. Any > >> ideas? > >> > >> Matthias > > > > Matthias, > > > > Have you got a small example? I think I've had these working..... > > Okay, here is a minimal example. > (By the way: WinXP, Python 2.1, Pmw 0.8.5) > > Matthias > This last bit on information is the problem (Windows!!!!) I can get your example working on Linux without change but on windows (2000 in my case) I can't. I dug around google but can't find a solution, idle uses Tkinter Menu's and it works there but I don't understand the code! Sorry I can;t be of more help Martin From aahz at pythoncraft.com Wed Jul 10 18:54:41 2002 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2002 18:54:41 -0400 Subject: metaclass & __slots__ References: Message-ID: In article , Holden Caulfield wrote: > > But somehow I feel the addition of the "new" style classes and the >"automatic" call of "__new__" and "__init__" is really confusing. The >"__init__" seems redundant, since we actually have a true >"constructor". I guess, what I am trying to say is, with the scarce >documentation (and if you are lazy to browse through the source) it >seems like you need to know the distinction on what to override >(__new__ or __init__) for a class derived from a builtin. Thing is, historically Python has not had a constructor, just an initializer. Now that we have new-style classes with constructors, it's still necessary to bring forward idioms that worked with older versions of Python. It's possible that Python 3.0 might collapse this into a single method, but you're the first person I've seen complaining. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From bsder at mail.allcaps.org Tue Jul 2 18:41:29 2002 From: bsder at mail.allcaps.org (Andrew P. Lentvorski) Date: Tue, 2 Jul 2002 15:41:29 -0700 (PDT) Subject: Performance question about math operations Message-ID: <20020702141852.L2045-200000@mail.allcaps.org> Folks, Please give me a *little* credit. I am aware that Python doesn't do constant folding, etc. In the real code, those constants are variables. However, my point was that the floating point operations are sufficiently slow *even with constants* that they dominate the variable references. What I was hoping to provoke was a discussion about hoisting integer and floating point dominated paths into a Python optimization. Or possibly looking at the efficiency of the dispatch table for FP and integer dominated paths. Just to note, Perl is somewhere between 2-4 times faster than Python for the same code. That speedup moves the coordinate math from being the main bottleneck, to just one of many that are comparable. Furthermore, the C++ code uses actual variables, function calls, and doesn't have any optimizations enabled. In short, it is the *worst* possible performance C++ can deliver. I have included the C++ code for your edification. I *have* looked at the assembly. It really does all the calculations. Jonathan Hogg wrote: > Could you post the actual code, or is it too long/proprietary? How are > all the magic numbers arrived at? Does it really look as simple as you > suggested? The code is too long, but it really is *that* simple. Profiling has shown that the coordinate conversion is *the* bottleneck. Without removing it, no other optimization will have any real effect (Amdahl's Law). All of those constants are actually variables in the real code, but with the underlying math that slow, the variable references don't matter. And, yes, I have disassembled the byte code looking for slow instructions. The problem really appears to be fundamentally Python. Terry Reedy wrote: > Use numerical Python extensions which works with arrays of unboxed > floats and which only has to interprete +-*/ once each for entire Well, I tried that. I have used both Numeric and SciPy for a circuit simulation engine and it works well; it fails for a layout editor. Special data structures are required to handle the 2-D region querying which is the hallmark of a VLSI layout editor. (10,000,000 polygons - 10^4 difference in coordinate values (.1 um to 1cm)) I have to query the RTree for data(O(logn + k)), unpack all of the coordinates (O(k)), duplicate them in an array (O(k) time and space, wasted), keep track of their references (O(k) in time and space, wasted), apply the transform(O(k)), rip the values back out so they can be rendered as polygons(O(k)), and finally throw the array out. The overhead of two wasted streams of time and space of O(k) moving things around in Python swamps the slow math. Thanks for all the help. I appreciate all the different points of view. -a -------------- next part -------------- #include class DoublePair { public: double p0; double p1; }; class ScreenCalc { public: double x_origin; double y_origin; double zoomfactor; ScreenCalc() : x_origin(678), y_origin(456), zoomfactor(3.589) {}; class DoublePair c2s(double p0, double p1); }; class DoublePair ScreenCalc::c2s(double p0, double p1) { DoublePair dp; dp.p0 = (p0 - x_origin)*zoomfactor; dp.p1 = -((p1 - y_origin)*zoomfactor); return dp; } int main(void) { ScreenCalc sc; DoublePair dp,dp2; double p0 = 1; double p1 = 1; for(int i = 0; i < 1000000; i++) { DoublePair dp = sc.c2s(p0, p1); } dp2 = dp; } From gmuller at worldonline.nl Wed Jul 3 13:06:52 2002 From: gmuller at worldonline.nl (GerritM) Date: Wed, 3 Jul 2002 19:06:52 +0200 Subject: EuroPython 2002 diary References: Message-ID: "Michael Hudson" schreef in bericht news:lk7kkdylwd.fsf at pc150.maths.bris.ac.uk... > I've put the notes I took during the (fantastic!) EuroPython 2002 > conference online here: > > http://starship.python.net/crew/mwh/europython.html > > They're subjective and not comprehensive. > > Cheers, > M. > > -- > If you have too much free time and can't think of a better way to > spend it than reading Slashdot, you need a hobby, a job, or both. > -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq great report! This statement deserves to be QOTW: Tim found he was fighting buzzword compliance all over the place -- he had to discourage people from using XSLT where it was inappropriate, there was some team that spent over nine months implementing some J2EE solution which could have been done in 100 lines of C. thanks and regards Gerrit -- www.extra.research.philips.com/natlab/sysarch From robin at jessikat.fsnet.co.uk Wed Jul 3 14:53:36 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 3 Jul 2002 19:53:36 +0100 Subject: replacing instance __setattr__ Message-ID: Is there something intrinsically hard about overriding an instance's special methods? I'm using python 2.2 and expected that it would be easy to wrap an existing __setattr__, but it seems the class is searched first not the instance. Must I clone the class and set the method on that? ################# class A: def __setattr__(self,n,v): self.__dict__[n]=v print 'hello world' a=A() print 'getattr(a,\'__setattr__\'):',getattr(a,'__setattr__',None) a.b = 1 import new a.__dict__['_saved__setattr__'] = a.__setattr__ def bingo(self,name,value): print 'bingo wrapper',self, name, value self._saved__setattr__(name,value) a.__dict__['__setattr__']=new.instancemethod(bingo,a,a.__class__) print 'getattr(a,\'__setattr__\'):',getattr(a,'__setattr__',None) a.b=2 #I expected the instance method here ????????? getattr(a,'__setattr__',None)('b',5) ################### results in C:\>\tmp\xxx.py getattr(a,'__setattr__'): > hello world getattr(a,'__setattr__'): > hello world bingo wrapper <__main__.A instance at 0x007696A8> b 5 hello world -- Robin Becker From cliechti at gmx.net Wed Jul 24 12:30:49 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 18:30:49 +0200 Subject: Need a better way to pause a thread References: <4378fa6f.0207231456.3057babe@posting.google.com> <4378fa6f.0207240725.2e589b1e@posting.google.com> Message-ID: mnations at airmail.net (Marc) wrote in news:4378fa6f.0207240725.2e589b1e at posting.google.com: > However you did it the following way: >> #now you can feed your thread with work: >> q.put( (time.sleep, 1) ) >> q.put( (sys.stdout.write, "Hello its the thread speaking up") ) > > Basically it appears the format is the command placed in nested () > with things that would be passed thru as parameters being delimited by > commas. thats a tuple, you could also use a list instead. the function or method that is placed as first arg is not called (no braces) so that you get a callable which you can use later (in the thread) > Is this a general format that will work for all commands, or > is there a place I can check the format? There are several examples of > queues I've found but none showing all the ways you can pass commands > through. passing a callable with its argument seemed to be the simplest way. other reasonable formats would have been: (callable, [listofargs]) and/or (callable, [listofargs], {dictwithkeywordargs}) for which you could use: if len(whattodo) == 3: l[0](*l[1], **l[2]) if len(whattodo) == 2: l[0](*l[1]) else: l[0]() the * and ** syntax is a shortcut for the builtin function "apply". look there if you what more infos about that. don't know a place to look up exactly that, but i think its a solution many people here would have brought up ("do the simplest thing that could possibly work"). snipets for various problems may be found in the Python Cookbook (online: http://www.activestate.com/ASPN/Python/Cookbook/ or printed) chris -- Chris From marklists at mceahern.com Wed Jul 24 16:09:01 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 24 Jul 2002 15:09:01 -0500 Subject: Numeric data question In-Reply-To: Message-ID: There's not much point in quoting anything, I'm merely writing to suggest the original poster checkout Tim Peters' FixedPoint class. I use that for shoving money data into PostgreSQL and it works just fine. I don't have a link to it, but that's what google's for, right? Cheers, // mark - From loewis at informatik.hu-berlin.de Tue Jul 30 06:27:53 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2002 12:27:53 +0200 Subject: Unicode classes of characters in Pythons' re's like in Perl? References: Message-ID: Roman Suzi writes: > Reading XML Schema docs I found that there are some useful extensions > to regular expressions like an ability to specify class of characters. > For example, > > [\p{Lu}] > > will match any uppercase letters. > > Is the feature planned in Python re too? Python currently supports Unicode character classes by explicitly enumerating all characters, e.g. r=re.compile(u"[\u0400-\u04FF]") In addition, it extends the categories to Unicode, if the UNICODE flag is given: - \d (digit): Character has a 'digit value' property; covers all of Nd and most of No - \s (space): bidirectional type WS, B, S, or category Zs - \w (word): alpha (Ll, Lu, Lt, Lo, or Lm), decimal (has 'decimal value' property), digit, numeric (has 'numeric value' property), or '_' - (linebreak, currently not supported in sre_parse): Category Zl, or type B There has been talk about supporting the POSIX regular expression categories (alnum, cntrl, lower, space, alpha, digit, print, upper, blank, graph, punct, xdigit, plus any categories defined by LC_CTYPE); this is not implemented, yet. So far, nobody has proposed to support Unicode categories in SRE. You can easily implement this yourself by means of using unicodedata.category, e.g. import unicodedata, sys def gencategory(cat): start = end = None result = [u"["] for i in range(sys.maxunicode+1): c = unichr(i) if unicodedata.category(c) == cat: if start is None: start = end = c else: end = c elif start: # XXX: special-case ] and - if start == end: result.append(start) else: result.append(start + "-" + end) start = None result.append(u"]") return u"".join(result) print repr(gencategory("Lu")) It turns out that those categories are useless for XML, since the XML character classes (in XML 1.0) have been defined using a different Unicode versions (XML uses the Unicode 2.0 database). The same appears to be the case for XML Schema: They use the Unicode 3.1 database; Python 2.2 has the Unicode 3.0 database. So to implement XML Schema, you probably have to parse the specific version of the Unicode database yourself, and construct the re class from that. Regards, Martin From aleax at aleax.it Thu Jul 25 12:37:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 16:37:54 GMT Subject: xml processing : too slow... References: Message-ID: Shagshag13 wrote: >> p.parse('%s' % line, 1) >> >> should be satisfactory for checking this kind of "sort of >> well-formedness", unless there are yet more specs as yet >> unexpressed. > > that's why i had done : >>>> anotherline = '' + line + '' >>>> p.Parse(anotherline, 1) > Traceback (most recent call last): > File "", line 1, in ? > p.Parse(anotherline, 1) > ExpatError: junk after document element: line 1, column 0 > > but it still don't work, as much has: But ARE you making a new parser object p for each line you have to parse? I don't see the expat.ParserCreate call here. I've already indicated a few posts ago that you need that. >>>> p.Parse('%s' % line, 1) > Traceback (most recent call last): > File "", line 1, in ? > p.Parse('%s' % line, 1) > ExpatError: junk after document element: line 1, column 0 Try with a newly created parser each and evey time, as I said. >> How would that help you diagnosed e.g. >> of course not >> as not being well formed? This is not well formed because >> it lacks quotes around an attribute's value. Or: >> &either >> now THIS is not well formed because reference '&either' >> is not terminated with a semicolon. Etc, etc. > > that's right i didn't address this kind of thing... :( If you need to, then expat is most likely your best bet (rxp might be another, but I don't know enough about it to suggest it). If you don't care either way, expat is probably best anyway. If you HAVE to accept so-called "XML" that in fact has these or other kinds of non-well-formedness, it's obviously a different issue. Alex From tjreedy at udel.edu Sun Jul 28 18:09:18 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Jul 2002 22:09:18 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com><_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: "Tim Gahnstr?m /Bladerman" wrote in message news:bxX09.1437$HY3.398059 at newsc.telia.net... > ask a complete novice what he think this peace of code will do > > #Here is the program > x=3 > inc(x) > print x > > #Bellow is al the function deffinitions > def inc(x): > x= x+1 Your example is deceptive and biased because you use the same name for the global and local vars, which is known to be confusing to complete novices, let alone those with more experience. They will tend to think that they are the same thing and give the wrong answer on the basis of that misconception. Much better is def inc(temp): temp = temp+1 > You might have to tell him about assignment but not much else for him to > understand that this program will print 4 I tried your experiment with my wife, who is not even a novice w/r/t computer programming. She first refused to answer. When she (mis)interpreted 'inc(x)' as acting like a calculator key press, with an implicit 'x=' prefixed, she thought '4'. When I 'inlined' the function call and rewrote the program as x = 3 t = x t = t+1 print x she immediately said '3'. To get 4 correctly (rather than on the basis of misunderstanding), one would have to inline inc (mentally or actually) as something like x = 3 t = &x *t = *t+1 print x but no novice would think of this and few would grok it. (Those who do are, of course, passing beyond novicehood.) If you want to use Python as if it were a calculator, write your functions to return a value, run in interactive mode, and use '_' instead of 'x' as the name of the default and automatically displayed variable. All expressions get an implied '_=' prefix just like the implied 'x=' prefix of calculators: >>> def inc(t): return t+1 ... >>> 3 3 >>> inc(_) 4 Terry J. Reedy From fperez528 at yahoo.com Mon Jul 1 19:27:41 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 01 Jul 2002 17:27:41 -0600 Subject: Where is Source for Node Class? References: Message-ID: Harvey Frey wrote: > > I searched through the other .py files in xml/dom, but I can't find the > original node class that minidom is importing. > In [9]: import xml.dom In [10]: xml.dom.Node ? Type: class String Form: xml.dom.Node Namespace: Currently not defined in user session. File: /usr/local/lib/python2.2/site-packages/_xmlplus/dom/__init__.py Docstring: Class giving the NodeType constants. In [11]: @psource xml.dom.Node class Node: """Class giving the NodeType constants.""" # DOM implementations may use this as a base class for their own # Node implementations. If they don't, the constants defined here # should still be used as the canonical definitions as they match # the values given in the W3C recommendation. Client code can # safely refer to these values in all tests of Node.nodeType # values. ELEMENT_NODE = 1 ATTRIBUTE_NODE = 2 TEXT_NODE = 3 CDATA_SECTION_NODE = 4 ENTITY_REFERENCE_NODE = 5 ENTITY_NODE = 6 PROCESSING_INSTRUCTION_NODE = 7 COMMENT_NODE = 8 DOCUMENT_NODE = 9 DOCUMENT_TYPE_NODE = 10 DOCUMENT_FRAGMENT_NODE = 11 NOTATION_NODE = 12 Cheers, f. From fredrik at pythonware.com Mon Jul 29 12:03:59 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Jul 2002 16:03:59 GMT Subject: How to redirect output to browser - second request for help References: Message-ID: "A" wrote: > In other words I do NOT want to wait for downloading the > whole file and only after that open that downloaded file > in a web browser. browsers have no problem reading data incrementally from a web servers. something like this might work: # based on simplehttpserver-example-2.py from # O'Reilly's Python Standard Library import SocketServer import SimpleHTTPServer import urllib, string PORT = 1234 class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): path = self.path ... convert the path in some way ... file = urllib.urlopen(path) # or use httplib while 1: data = file.read(1024) if not data: break ... process the string in some way ... ... for example data = string.upper(data) self.wfile.write(data) self.wfile.flush() httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy) print "serving at port", PORT httpd.serve_forever() use the webbrowser module to point your browser to localhost:1234. From jcc at ibdosnorte.com Wed Jul 10 03:27:52 2002 From: jcc at ibdosnorte.com (=?ISO-8859-1?Q?Juan_Carlos_CORU=D1A?=) Date: 10 Jul 2002 00:27:52 -0700 Subject: Message Queueing References: Message-ID: jcc at ibdosnorte.com (=?ISO-8859-1?Q?Juan_Carlos_CORU=D1A?=) wrote in message news:... > Hi all, > > I'm new to this group but not to python. > > I'm testing different solutions to implement message queueing between > Zope (http://www.zope.org), that is written in python, and the > Navision ERP (http://www.navision.com), that supports COM (I will try > to develop a Visual Basic dll to interface with the selected message > queueing system). So, I need a message queueing system with bindings > to python and visual basic/COM. > > At the moment I have checked the following MOMs: > - Spread (http://www.spread.org): Does not implement message queueing. > Active project. > > - Open3 (http://www.open3.org): Does not have python bindings yet and > uses JMS that is very complicated. No news on their web since January, > is it active? > > - Isectd (http://pweb.netcom.com/~tgagne/index.html): Does not > implement queues, and seems to be not very active. Not visual > basic/COM bindings. > > - Jabber (http://www.jabber.org): queues? > > - MUSCLE (http://www.lcscanada.com/muscle/index.html): Does not > support queueing. Does not have Visual Basic/COM bindings. Active > project. > > - OpenQueue (http://openqueue.sourceforge.net/): Last update on July, > 2000. > > - OSE (http://ose.sourceforge.net/): Only libraries. Must make a big > effort to implement such a solution. > > - SwiftMQ (http://www.swiftmq.com/): uses JMS, not open source. > > - XMLBlaster (http://www.xmlblaster.org/): uses CORBA and xml-rpc. I > tested it some time ago with poor results. Maybe someone can give me a > better opinion. > > - XmlMom (http://www.xmlmom.org/): Young project. Last update May. > Robustness? I tried to test it, but since it requires a lot of third > party libraries, that I must install apart, I gave up. Maybe, someone > can tell me about this program. > > > In my opinion, Open3, XmlMom and XMLBlaster are the best options. > I have tested Open3 and developed some programs in python that > implements part of JMS, since Open3 uses JMS. And, now before > continuing the development of the python bindings to open3, since it > implies to create a JMS implementation in python, I like to hear the > opinions of people in the same situations. Sorry, XmlMom includes all the necessary third party libraries ready to build. From jepler at unpythonic.net Tue Jul 16 16:43:27 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Jul 2002 15:43:27 -0500 Subject: Simple Pickle Question! In-Reply-To: <20020716203711.99600.qmail@web20805.mail.yahoo.com> References: <20020716203711.99600.qmail@web20805.mail.yahoo.com> Message-ID: <20020716204327.GA3124@unpythonic.net> You must "seek" the file to the beginning to read it again from the beginning. Here's an example without the use of pickle: f = open("test_readwrite", "w+") f.write("hi there") # f.seek(0) print `f.read()` If you uncomment the 'seek' line, you'll get some text in f.read(). Otherwise, you'll get an empty string (EOF). Pickle doesn't seem to handle premature EOF well.. (the missing key is probably the empty string) Jeff From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 10:43:31 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 09:43:31 -0500 Subject: Searching for email address In-Reply-To: <3D46A4BD.A894DC59@ilangua.com> (Graeme Longman's message of "Tue, 30 Jul 2002 15:37:49 +0100") References: <3D46A4BD.A894DC59@ilangua.com> Message-ID: >>>>> "Graeme" == Graeme Longman writes: Graeme> In the process of translating our client's sites. Just a Graeme> script to find all the email addresses so that the email Graeme> addresses aren't included for translation. Tim Roberts wrote on this group a few days ago about a 'multi-thousand byte full expression to match a valid RFC822 e-mail address' from *Mastering Regular Expressions 2nd Ed.*. So you may want to check the O'Reilly site and see if you can download the src code for the book. John Hunter From dpinol at hotmail.com Tue Jul 9 06:28:08 2002 From: dpinol at hotmail.com (=?ISO-8859-1?Q?Daniel_Pi=F1ol_Laserna?=) Date: 9 Jul 2002 03:28:08 -0700 Subject: pythoncom from jython References: <46585325.0207080040.1ac2fffd@posting.google.com> Message-ID: <46585325.0207090228.7b5fc9e2@posting.google.com> Gerhard H?ring wrote in message news:... > * Daniel Pi?ol Laserna [2002-07-08 01:40 -0700]: > > Is it possible to use pythoncom from jython? > > No. > > > Ideally, I'd like to build a com component in python (this works with > > win32 extensions), and from there make calls to java classes (this > > need jython). > > Do you really need to combine COM and Java? Use a COM <-> Java bridge, > then. Googling with the keywords "java com bridge" finds you some > alternatives. > > Gerhard Yes, but only Jintegra and TIBCO offer the bridge in the direction I need it: A COM client using a java server. And they're not free. From pinard at iro.umontreal.ca Tue Jul 9 07:52:34 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 09 Jul 2002 07:52:34 -0400 Subject: Making computer into server for free In-Reply-To: <1b8c5fe1.0207090113.79c03593@posting.google.com> References: <1b8c5fe1.0207090113.79c03593@posting.google.com> Message-ID: [Comcol] > Python does have SimpleHTTPServer and CGIHTTPServer which may be of use > to you - see the global module index for more info. I've never used them > myself, so I don't know how good they are or whether they're suitable > for your purposes. I used them and they well prove the concept they advance. You can get a working server in minutes (a dozen lines), which does a fair amount of good job. However, in real practice, you should use them as starting points, and modify them a bit: 1) to correct a few tiny bugs, 2) to add some elementary facilities (like CGI scripts in GET mode, or some authentication), and 3) to customise the behaviour along your own habits or desires. These will extend the initial minutes into a few days. :-) My opinion is that 1) and 2) improvements should nicely go in Python distributions. (Oh, I would have submitted these if "they" only had a sensible mean for receiving bug reports -- like plain emails, or at the very least, a bug tracker offering a reasonable email interface!) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From aleax at aleax.it Sun Jul 7 07:45:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 11:45:45 GMT Subject: structs in python References: Message-ID: Kevin O'Connor wrote: > Hello, > > I often find myself using Python tuples in the same way I might use C > structs. For example, I might store a "point" as "p = (x, y, color)". > > Unfortunately, this quickly becomes cumbersome when the code starts to > make > frequent references to tuple positions instead of member names. For > example, one would see code like "delta = (p1[0] - p2[0], p1[1] - p2[1])". > Ideally, this code would read something more like "delta = (p1.x - p2.x, > p1.y - p2.y)". > > Clearly, the use of classes makes the code much more readable, but > unfortunately the declarations necessary to instantiate a class is often > too much of a hassle for small and infrequently used objects. > > It would be useful if there were a simple way of declaring a class with > only member variables (and no methods); an object more akin to a C struct. > > What if a syntax like the following were permitted: >>>> p = ( .x = 10, .y = 11, .color = 'blue') >>>> print p.x > 10 >>>> I think you're looking for the recipe which I described in the Cookbook as Bunch. > I know this concept is not unique - I've seen implementations of a "class > Struct" that implements the above using Python's **kw syntax (Eg. "p = > Struct(x=10, y=11, color='blue')" ). However, I have not seen wide spread > adoption of it, and I have not seen an attempt to standardize an > implementation. What sort of implementation standardization might possibly be necessary, or even helpful? class Bunch: def __init__(self, **kw): self.__dict__ = kw How can you possibly get simpler than this? As for "widespread adoption", I guess the occurrence of classes with no behavior, just state, isn't all that frequent when one does OOP. It does happen, and when it happens Bunch is fine -- as long as issues of amount of memory consumed don't interfere. __slots__ is OK, to save memory, when you have many instances with just a few data fields each (and the same field names in each instance), but it does admittedly demand more sophisticated implementation than Bunch, presumably via a metaclass. > My intention here is not really to propose any changes, but instead to > query the community's feelings on this topic. Do other people find code > that uses tuples a bit cryptic? Would others like a named initializer? > Is this a recurring request with obvious problems? I just don't see what the lack of classname and extra leading dots in your proposed : >>>> p = ( .x = 10, .y = 11, .color = 'blue') add to current usage such as p = Bunch(x=10, y=11, color='blue'), I guess. Alex From showell at zipcon.com Tue Jul 16 14:31:33 2002 From: showell at zipcon.com (Steve Howell) Date: Tue, 16 Jul 2002 14:31:33 -0400 Subject: Python YAML (was Re: XML overuse? (was Re: Python to XML to Python conversion)) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> <20020716151830.A10625@prim.han.de> <20020716142712.A70366@doublegemini.com> Message-ID: <003001c22cf7$030504c0$471e09d1@pavilion> > | > | It does and it's very interesting. It does sound a lot like > | http://yaml.org to me, though (They even have an RFC). > | Don't you think YAML might be a superset of your ideas? > > Yes, Steve Howell even has a python implementation of it... > http://yaml.org/python/PyYaml_14jul2002.tgz > > I'm sure he'd love your comments/contributions. > Yes indeed. It's still alpha software, but it's quite usable for basic YAML applications, such as making config files and creating test drivers. It's not robust enough to use as your primary serializer, but it's getting there. From tim at bladerman.com Sun Jul 28 15:23:51 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sun, 28 Jul 2002 19:23:51 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> <_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: "Martin v. Loewis" > "Tim Gahnstr?m /Bladerman" writes: > > > when it comes to calling functions it will look like this > > > > def setTo3(x): > > x=3 > > > > a=2 > > setTo3(a) > > Others have already suggested that this will be impossible to > implement, but I guess I can't stop you from trying, so I won't. > > Instead, I suggest that this is already possible with a slightly > different notation I must say thankyou verry much!!! Not maybe for the solution, but for the effort to see solution instead of just trying to spot things that make it "impossible" It is fairly rare that you stumble upon such people (just try to talk to a random university professor :-)) > class Reference: > def __init__(self, value): self.value = value > def assign(self, value): self.value = value The solution you outlined will ofcourse work for this particular example, but the problem is that I want all this mess to be invissible to the user. But maybe I can use it anyway. As I have said several times, I havn't yet gotten aquainted with everything yet som maybe this is not possible. The thing I have on my mind is (maybe this is what you meant to) that maybe I can change the parser a little so that it sees everything as a subclass of Refference. Then I just change the asignmentpart of the interpreter to use .assign() instead of whatever hapens now. I really have a hard time to explain what I mean here but I think I want a statement like this: a=2 to be parsed to a.assign(Refference(2)) Do you think a solution like that be possible? Anyway, even if this doesn't work out I am very gretfull for your effort to see a solution to a tricky problem. A problem might ofcourse be that this will screw the possibilities to use the python library wich is not an option... Tim From aleax at aleax.it Fri Jul 26 06:10:00 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 10:10:00 GMT Subject: redirect to > and to console ? References: Message-ID: Gerhard Haering wrote: ... > print>> sys.stderr, "foobar" > > will work fine. I'd use the print>> form, because it has the advantage > that it annoys the Martellibot, among others ;-) If you were _really_ keen on annoying me, you'd be using print>> sys.stderr, (lambda x, y: x+y)("foo", "bar") or other deeper-yet obfuscations. "print>>" on its own is small potatoes -- gotta add a useless lambda or two and perhaps a list comprehension abuse to really start me fuming. Alex From spam at ob_scure.dk Mon Jul 8 05:12:11 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Mon, 08 Jul 2002 11:12:11 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> <3D282FF8.6040602@ob_scure.dk> <7x3cuvsnc7.fsf@ruckus.brouhaha.com> <3D2864DE.6030608@ob_scure.dk> <7xvg7qj19k.fsf@ruckus.brouhaha.com> Message-ID: <3D29576B.5010509@ob_scure.dk> Paul Rubin wrote: > Thomas Jensen writes: > If you're doing all these single row selects without many updates, > and you're not doing many joins, it really sounds more and more like > an SQL database isn't the best tool for your task. I agree, however the data needs to end up in a SQL database, since we have quite a lot of code (ASP code and COM components) depending on it beeing a SQL database (some doing quite complex joins, etc). >>Before going on with the distributed approach, I will probably write a >>"proof of concept" demo. Should this demo show, that it is not worth >>the effort, I will put it aside for now. > > Fair enough. You could just check the CPU load on your SQL server > right now, as your single client runs. 25-50% but thats not a realistic measure, since the client makes a huge amount of small selects, which probably makes network latency play some role. > What kinds of calculations are these really? The only one you've All kinds, ranging from complex financial calculations to simple AVG, MIN, MAX. Sometimes the output of a calculation is smaller (byte-wice) than the input, sometimes larger. > described so far is selecting a bunch of rows and computing the SD of > the numbers on one column. It may be fastest to do that with a server > sided stored procedure. I agree, and indeed we considered writing the entire job using Stored Procs. We ditched the idea because: * MSSQL7 is not integrated with SourceSafe (AFAIK?) * We generally like the idea of seperating data and code. * (eh, other stuff I don't remember right now :-) Actually part of the calculations are already written in SPs (for some realtime calculations), but to our surprise it didn't show the performance one would expect. >>I really see all this distribution talk as one among several >>optimization strategies. > > OK, that's good, as long as you see there's a range of approaches. > Sometimes all someone will have is a hammer and everything looks like > a thumb ;-). Hehe, that's right :-) > If your data layout is simple enough you might just store it in a > fixed-width record format, then mmap() it into memory and crunch it > with a C program (or even a Python program). That approach is > generally simple and fast. It will probably outperform any SQL > approach by orders of magnitude. Please see above why this wouldn't work. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From sandeep182 at hotmail.com Wed Jul 10 20:46:19 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: Thu, 11 Jul 2002 00:46:19 GMT Subject: How can I retrieve the ID of the last record I added? References: <20020710141641.1fbadb68.spam@oblomov.org> Message-ID: "oblomov" wrote in message news:20020710141641.1fbadb68.spam at oblomov.org... > On Wed, 10 Jul 2002 18:34:43 +0900 > Ian Parker wrote: > > > In article , Brian > > writes > > >Oops. I just realized you're accessing both MySQL as well as MSSQL. > > >My comment about @@IDENTITY applies to MSSQL. I haven't been exposed > > >to MySQL yet. :) > > > > On MySQL there's a function LAST_INSERT_ID([expr]) to return the value > > of the last auto-increment field on that connection. > > The correct way would (of course?) be to retrive the OID of the last inserted record on the connection and then SELECT the data you are looking for. I hope this doesn't sound too naive.... How do I retrieve the OID of the last inserted record? From vchen at meetingmaker.com Fri Jul 26 14:35:26 2002 From: vchen at meetingmaker.com (Victor Chen) Date: Fri, 26 Jul 2002 14:35:26 -0400 Subject: automating control-D Message-ID: <003201c234d3$35d9b880$e503010a@int.meetingmaker.com> Hi, I'm fairly new a python stuff, working on my first python script. I was wondering if anyone knows how I can represent control-D as output using python. Firstly, I do not know the special string used to represent the control key and secondly, I would have to automate both the control and the d characters be pressed together. Any help is appreciated. Thank you. Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at aleax.it Mon Jul 8 17:41:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 21:41:55 GMT Subject: adding methods on the fly References: <878dc260.0207080702.2be7ba9f@posting.google.com> Message-ID: Renzo Tomaselli wrote: ... > I mean a function declaration in a string. In short, what I miss is a > way to transform it into a callable object to be added to a class. > Whether such class is just a wrapper on my C++ object or a Python > derived class depends on issue below. > I'm lost here between PyRun_String and PyCompile_String, which seem > the only places where I can start from code strings to add methods on Py_CompileString (careful about underscore placement!-) won't let you easily build a function (or unbound-method) object, which is what you need (though you can get there eventually, but it's a long way 'round). With PyRun_String, passing an appropriate, initially empty dict as the locals argument, you can execute a statement held in a string such as "def somename(self, whatever): return whatever", and find in said locals dict under key "somename" the resulting function object. However, you can't add attributes to a normally-coded C (or C++) type -- that's another issue yet. >> Yes, as long as that C-coded type IS specifically coded as to support >> being inherited from. Once again, it all depends on how you code at >> the C level. > > Could you please explain this topic a little further ? How do we > enable a C type to be inherited from by a Python class ? You need a few things, starting with Py_TPFLAGS_BASETYPE among the flags, but not ending there -- allocation / newing / initialization are the key part. For perspective, I would suggest you study subclassable built-in objects, such as Objects/tupleobject.c -- tuple_new and tuple_subtype_new are the key spots. Then, examine the alternative strategy in Objects/listobject.c -- since list objects are mutable, they need no special alloc or new, but can handle all needs in list_init and the functions it, in turn, calls. Objects/dictobject.c shows yet another strategy, and Objects/fileobject.c a pretty similar one. Offhand, I suspect listobject's strategy would be sufficient for your purposes, but, if not, the one used by dicts and file objects will most likely be. >> One way to avoid depending on how the C-level code is written is to >> use wrapping and automatic delegation in your Python class -- that ... > Ok, got it. The overall issue is dealt with in the opposite way I'm > interested in: almost all involved discussions on this list handle > about estending Python by C/C++ while I need to extend C++ by Python. You're not going to be able to add to C++ classes methods on the fly in ways that let other C++ code call the new methods, anyway. That being a given -- i.e., given that the client-code of your extended objects is going to be Python, anyway -- why not take the easy way out, and have said extensible objects be a Python shell around a C++ core? A thin Python shell, which you can add with a small effort by inheritance in Python 2.2, or more easily and portably (with a loss of performance) by automatic delegation, lets you extend to your heart's content. So, why not...? > And possibly by adding just functions (methods), no extra class stuff > or modules. Oh, we can do that, too -- at ten times the effort, and without any benefits whatsoever, but, hey, one thing I learned as a freelance is that, when the customer insists after you've explained that, it's best to accept the money the customer is so insistent to push into your hands (I charge by the hour, of course). This way you get the extra of saying "see, I had told you that" when the problems do develop:-) > Thanks for any suggestion, Let's see, I'm going to spend a week's vacation in Trentino anyway, so, if you need further help implementing things your way rather than in the easy way, I'm willing to charge you just my hourly rate -- no extra for the trip to/from Bologna. Can't get much fairer than that... If you want a serious suggestion, though, it's to re-think the idea that you *need* to have the extensible object itself be the one that is implemented in C++, rather than a thin Python wrapper around it. It CAN be done, but, what benefits do you propose to obtain from such a contrarian approach...? Will they repay substantial additional effort...? Another possibility is to look at Boost Python, if the schedule for their new release 2 (supporting Python 2.2 fully) is compatible with your timing constraints. I'm not privvy to the details of the new release, whose webpages claim to have been revised on Nov 5, 2002 (!), but in the previous v1 the Boost guys had basically implemented a custom metaclass (...and by the hard and complicated rules that were needed in older Pythons, no less...) that should make it easier to implement your exact specs, once one understands it well enough to know what to tweak. Boost Python can surely be recommended for the dyed-in-the-wool, hard and pure C++ hacker. I used to qualify (and I'm still a C++ MVP for Brainbench), but I've since seen the light and left an otherwise-excellent but deeply C++-centered job in order to do Python full time instead. Of course, just like one who used to smoke heavily then quit, this may leave me, at times, slightly intolerant of typical C++ complications ... :-). Alex From fredrik at pythonware.com Wed Jul 3 09:50:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jul 2002 13:50:13 GMT Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) References: Message-ID: Simon Brunning wrote: > > From: Mike C. Fletcher [SMTP:mcfletch at rogers.com] > > I'm actually doing something very similar for SimpleParse > > Interesting project. But you might want to call it something > else - there is already a SimpleParse. See > From talsit at talsit.org Sat Jul 6 10:40:00 2002 From: talsit at talsit.org (tALSit) Date: Sun, 7 Jul 2002 00:40:00 +1000 Subject: swig or something else.... Message-ID: <3d26f83a@dnews.tpgi.com.au> Hi, I'm trying to interface a system i made in C++ with python using swig. Ok, i've got it working, but I find it pretty ugly. Actually, way ugly. Given a C++ class: class cNode { public: cNode (const std::string & name); set (const std::string & attr, const std::string & value); // etc }; Swig generates a series of _functions_, not a class with methods, so in python I have to do this: obj = my_module.new_cNode ("someName") my_module.cNode_set ("attrib", "value") Instead of something more like this: obj = my_module.cNode ("someName") obj.set ("attrib", "value") Is this a limitation of swig, python or am I doing it wrong? Because if it's a swig limitation, I might be able to do a workaround for the 3-4 classes i need interfacing. If it's python, well, it doesn't matter. But if it's me, please advise! Thanks!! From loewis at informatik.hu-berlin.de Wed Jul 10 09:27:54 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 10 Jul 2002 15:27:54 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: Piet van Oostrum writes: > So should the UTF-8 encoding raise an exception then on encountering an > unpaired surrogate rather than generating an illegal UTF-8 sequence? > Tr28 says: It probably should. Please file a SF bug report. Regards, Martin From dale at riverhall.NOTHANKS.co.uk Sat Jul 27 07:15:17 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 27 Jul 2002 12:15:17 +0100 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> <7xeldq1zzp.fsf@ruckus.brouhaha.com> <7xptxawajw.fsf@ruckus.brouhaha.com> <7xy9byyrnr.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >I'm still not clear on why you need challenge-response anyway though. >Suppose the client just puts HMAC(current date/time, secret key) into >the URL along with the date/time in hex. Then use the HTTP Referer >header to figure out who the client is (or put that in the URL too) >and authenticate the URL. By examining the date/time you can reject >old/stale URL's. Thanks. I'll chew this over. I may be back.. :-) -- Dale Strickland-Clark Riverhall Systems Ltd From i.linkweiler at gmx.de Thu Jul 4 13:37:15 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Thu, 04 Jul 2002 19:37:15 +0200 Subject: REPEAT... UNTIL ? References: Message-ID: <3D2487CB.9000102@gmx.de> > > >Just like the GOTO, or any other syntax from another language they belong to >other languages and not python. A good coder learns to program in the idioms >of the language they are using. Or they just write in the same style >everywhere and their perl, C, java, whatever looks like their first language. > > I know that I can use a while loop with break instead of repeat-until. I am using it, but I just think a repeat-until looks better. If nobody else has this opinion: Let's forget my stupid question <8-) Ingo From dsavitsk at e-coli.net Fri Jul 19 20:55:45 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sat, 20 Jul 2002 00:55:45 GMT Subject: Python Sets (no not those sets) References: <7f2b571b.0207191546.67583b88@posting.google.com> Message-ID: most tellingly, clicking on Tim Peters gives this ... Category: Arts > Performing Arts > Impersonators while clicking on Mark Hammond gives this ... Category: Arts > Music > Bands and Artists -d "Tim Randolph" wrote in message news:7f2b571b.0207191546.67583b88 at posting.google.com... > Check out: > > http://labs1.google.com/sets?hl=en&q1=Tim+Peters&q2=Fredrik+Lundh&q3=Alex+Ma rtelli&q4=Guido+van+Rossum&q5=&btn=Large+Set > > It's worth putting this URL back together if needed. > > Or go to: > > > http://labs1.google.com/ > > and type in: > > Tim Peters > Fredrik Lundh > Alex Martelli > Guido von Rossum > > It's an amazing technology. > > > > Tim From fperez528 at yahoo.com Tue Jul 2 13:37:14 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 02 Jul 2002 11:37:14 -0600 Subject: Performance question about math operations References: Message-ID: Andrew P. Lentvorski wrote: > I have a VLSI layout editor written in Python.??At?its?core,?it?has?to > redraw a lot of polygons.??This?requires?a?lot?of?coordinate?conversion > mathematics.??Essentially?the?following?loop: > [snip] Before jumping to writing C extensions, use Numeric (http://www.pfdubois.com/numpy/). Chances are it will give you enough speed (close to C) without ever dropping out of python. Doing any 'real' math-oriented work in python is almost guaranteed to need Numeric at some point, so you might as well start using it now. It will save you a lot of time. cheers, f From markus.vonehr at ipm.fhg.de Thu Jul 11 02:45:48 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 11 Jul 2002 08:45:48 +0200 Subject: Is this possible in python? References: Message-ID: <3D2D299C.70D65BEA@ipm.fhg.de> Hi, an easy way is to use python and Tkinter. you could subclass the canvas widget to create your line chart like I did. Use a method to set the points, to redraw them, to interpolate etc. Instantiate Profile in your main program. spline.py (implemented in python from Numerica Recipes) example: from Tkinter import * import math import spline import Numeric # defines class Profile(Canvas): __CHART_MIN_X = 1 __CHART_MAX_X = 790 __CHART_MIN_Y = 10 __CHART_MAX_Y = 110 def __init__(self, parent = None, **kw): self.W = kw['W'] self.H = kw['H']+20 kw_corrected = {'height':self.H, 'width':self.W, 'bg':"white"} Canvas.__init__(self, parent, kw_corrected) self.root = parent self.__CHART_MAX_X = kw['W'] self.__CHART_MAX_Y = kw['H']+self.__CHART_MIN_Y self.spec = [] # initial spectrum values for i in range(512): self.spec.append(int(math.sin(i/50.0)*((self.__CHART_MAX_Y-self.__CHART_MIN_Y)/2))+\ (self.__CHART_MAX_Y-self.__CHART_MIN_Y)/2) # draw chart grid for i in range(6): self.create_line(self.__CHART_MIN_X+1, self.__CHART_MIN_Y+i*((self.__CHART_MAX_Y-self.__CHART_MIN_Y)/5), self.__CHART_MAX_X-2, self.__CHART_MIN_Y+i*((self.__CHART_MAX_Y-self.__CHART_MIN_Y)/5), fill="black") for i in range(6): self.create_line(self.__CHART_MIN_X+1+i*((self.__CHART_MAX_X-self.__CHART_MIN_X)/5), self.__CHART_MIN_Y, self.__CHART_MIN_X+1+i*((self.__CHART_MAX_X-self.__CHART_MIN_X)/5), self.__CHART_MAX_Y, fill="black") # self.Redraw(1) def Redraw(self, factor): # delete old spectrum my_tuple = self.find_all() for item in range(len(my_tuple)): if self.itemcget(my_tuple[item], "fill") != "black": self.delete(my_tuple[item]) # draw new spectrum for i in range(len(self.spec)-1): self.create_line(i+self.__CHART_MIN_X, self.__CHART_MAX_Y - int(self.spec[i]*factor), i+1+self.__CHART_MIN_X, self.__CHART_MAX_Y - int(self.spec[i+1]*factor), fill="red") def set(self, data): # set new spectrum self.spec = [] for i in range(len(data)): self.spec.append(data[i]) def value2screenY(self, y): return (self.__CHART_MAX_Y-y)-self.__CHART_MIN_Y py thon schrieb: > > I need a visual (gui) based app that can take a series of data point > and plot them on a graph like a line chart. Then I would like to > reshape the curve created above by moving the data points with the > mouse. (all using spline interpolation). Then re-output the correct > data to a textfile. I would like to know what part of this can > python perform. > > Thanks for your time From mcherm at destiny.com Mon Jul 22 16:55:59 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 22 Jul 2002 16:55:59 -0400 Subject: A better self Message-ID: <3D3C715F.6090403@destiny.com> >> >> Many people have suggested doing something like the following (which is >> reasonable) to eliminate self. from mathematical expressions: >> >> t, x, y, z=self.t, self.x, self.y, self.z >> result=sin(t)*x**y+sqrt(z) # A pretend formula > > Yes, this was suggested earlier. I don't consider it a great solution > to the problem. [...] it is rather silly to have > lines like: > > t, x, y, z=self.t, self.x, self.y, self.z > > in every one of many member functions, often with the same variables. > You look at that code, with all those redundant lines of negligible > content, and it yells out to you: something is missing here that > should make this silly copying unnecessary in order to have expressions > that are easy to read/understand. I agree. Something is missing here. Your problem is that you really aren't dealing with "objects", per se, you have these "formulas" in your mind. So why don't we use the closest Python equivalent? # WARNING: Untested code below def pretendFormula(x,y,z,t): return sin(t) * x**y + sqrt(z) def MyClass: def pretend(self): return pretendFormula(self.x, self.y, self.z, self.t) Notice how this has an additional advantage... it allows you to use short, simple names for the variables within the formula (the traditional to write formula), while still allowing longer, more descriptive names within the object: ... return pretendFormula( self.position.x, self.position.y, self.position.z, self.time ) And while you're at it, you can give a descriptive name to the formula itself. Can't we get the best of both worlds? -- Michael Chermside From phr-n2002b at NOSPAMnightsong.com Tue Jul 2 19:11:31 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 02 Jul 2002 16:11:31 -0700 Subject: Running scripts within scripts References: <3d2225d8$1@post.usenet.com> Message-ID: <7xznx9wwrg.fsf@ruckus.brouhaha.com> "Todd" writes: > Is it posible for a python to call a second without importing a module? I > don't really want to call os.system and have to include paths. Just call a > second script in the same directory as the parent one. You could say os.system("./other-script.py") which doesn't need to include any paths. From romany at actimize.com Wed Jul 31 11:57:22 2002 From: romany at actimize.com (Roman Yakovenko) Date: Wed, 31 Jul 2002 17:57:22 +0200 Subject: How to put a bitmap in a wxPanel ? Message-ID: <7647A9F4B298E74DB6793865DA67285004B35F@exchange.adrembi.com> Hi. One of the basic controls (in basic control panel) is static bitmap. You can put this control on panel. Use "Bitmap" property to set desired bitmap. Also you may insert you bitmap to code, see img2py.py file in wxPython\tools folder. Roman. -----Original Message----- From: Marcus Vinicius Laranjeira [mailto:m.laranjeira at datacraft.com.br] Sent: Wednesday, July 31, 2002 4:06 PM To: python-list at python.org Subject: How to put a bitmap in a wxPanel ? All, I am using the boa constructor, and I need to put the logo of my company in the wxPanel. This bitmap will be static and it will be there just for decoration purposes. Anyone can help me ? Cheers, Marcus -- http://mail.python.org/mailman/listinfo/python-list From lyle at knology.net Sat Jul 6 12:19:35 2002 From: lyle at knology.net (Lyle Johnson) Date: Sat, 6 Jul 2002 11:19:35 -0500 Subject: swig or something else.... References: <3d26f83a@dnews.tpgi.com.au> Message-ID: "tALSit" wrote in message news:3d26f83a at dnews.tpgi.com.au... > Hi, I'm trying to interface a system i made in C++ with python using swig. > Ok, i've got it working, but I find it pretty ugly. Actually, way ugly. > Is this a limitation of swig, python or am I doing it wrong? You're doing it wrong ;) Read the SWIG documentation on generating shadow classes for Python, which will give you the result you're looking for. More specifically, if you process your SWIG interface file with the "-shadow" command line option, e.g. swig -c++ -python -shadow my_module.i you should end up with both the C++ wrapper source code (something like "my_module_wrap.cxx") and a shadow class module (something like "my_module.py"). Hope this helps, Lyle From erno-news at erno.iki.fi Mon Jul 22 08:28:57 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 22 Jul 2002 15:28:57 +0300 Subject: ssh and Python References: Message-ID: In article , "Bo M. Maryniuck" writes: | On Monday 22 July 2002 13:12, Erno Kuusela wrote: || use a rsa key with ssh-agent (or without passphrase if you need || it to run unattended). | But sometimes you just need to pass a password. hmm? you can always use a rsa key, unless the administrator has disabled rsa keys (which would be silly since hardcoding passwords is less safe). -- erno From fredrik at pythonware.com Wed Jul 17 18:46:25 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Jul 2002 22:46:25 GMT Subject: get a list printed in hexadecimal notation References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C8D@hendrix.empolisuk.com> Message-ID: <5tmZ8.47870$n4.11773379@newsc.telia.net> Fran?ois Pinard wrote: > > > print [type(x) == type(1) and hex(x) or x for x in l] > > A tiny detail. I guess that `type(x) == type(1)' is better written > `isinstance(x, int)' under Python 2.2. and as "isinstance(x, type(1))" for versions before 2.2, and as "type(x) is type(1)" for versions before 1.5. (replace type(1) with types.IntType where appropriate) From phr-n2002b at NOSPAMnightsong.com Wed Jul 17 01:39:04 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 16 Jul 2002 22:39:04 -0700 Subject: Session ID & Security References: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> Message-ID: <7xn0sqkj5z.fsf@ruckus.brouhaha.com> Paul Rubin writes: > Here's a simple way: pick some secret, unguessable, constant string, like > "H5LV9-GRDP5-9FG5T-HLUDN". Call it K. > > Now to generate an authentication cookie, simply compute the HMAC of > some session identifier, along with some non-repeating data. For > example, let S = the username + IP address + exact login time and the > auth cookie is the HMAC of S with key K. Actually, rather than mess with this stuff it's simpler (and preferable) to use a securely generated random string as the session ID, if you can manage it. Unfortunately there's no platform-independent way to do it. Linux and *BSD systems provide a system device for the purpose of supplying secure random strings. Cygwin also simulates this device on Windows using the Windows CAPI cryptGenRandom function. It's on various people's todo list to write an extension module that lets non-Cygwin Windows users do something similar. If you're using Linux or *BSD, writing something like: from binascii import hexlify def gen_session_id(): return hexlify(open("/dev/urandom").read(16)) should return a thoroughly unguessable 32-digit hex number without your having to mess around with HMAC, generating unique initial state, maintaining secret magic constants in your code, etc. This is the way to go if it works for you. From bokr at oz.net Wed Jul 17 13:41:31 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2002 17:41:31 GMT Subject: get a list printed in hexadecimal notation References: Message-ID: On 17 Jul 2002 17:01:10 GMT, bokr at oz.net (Bengt Richter) wrote: >On Wed, 17 Jul 2002 12:07:55 +0200, Oliver Eichler wrote: > >>Hi >> >>Is it possible to print a mixed list with strings and numbers and having the >>numbers printed as hexadecimal notation? >> >>something like: >> >>>>>l = ('spam',10,15,'more spam') >>>>>print l >>('spam',0xA,0xF,'more spam') >> >>or similar... >> >>The only way I could think of is to write my own print function. Is there an >>easy way? >> > >>> def hexiseq(seq): > ... if isinstance(seq,int): return hex(seq) > ... if isinstance(seq,tuple): lb,rb = '(', ')' > ... elif isinstance(seq,list): lb,rb = '[', ']' > ... else: return repr(seq) > ... ret = [] > ... for x in seq: ret.append(hexiseq(x)) > ... return lb + ', '.join(ret) + rb > ... > >>> hexiseq(('spam',10,15,'more spam')) > "('spam', 0xa, 0xf, 'more spam')" > >>> hexiseq(('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)) > "('spam', 0xa, 0xf, 'more spam', ['nested', 0xffff, 'spam'], 'spam', 0xff)" > > >>> print hexiseq(('spam',10,15,'more spam')) > ('spam', 0xa, 0xf, 'more spam') > >>> print hexiseq(('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)) > ('spam', 0xa, 0xf, 'more spam', ['nested', 0xffff, 'spam'], 'spam', 0xff) > Or a little tighter: >>> def hexiseq(seq): ... if isinstance(seq,int): return hex(seq) ... if isinstance(seq,tuple): lb,rb = '(', ')' ... elif isinstance(seq,list): lb,rb = '[', ']' ... else: return repr(seq) ... return lb + ', '.join(map(hexiseq,seq)) + rb Regards, Bengt Richter From tim.one at comcast.net Mon Jul 15 01:34:20 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 15 Jul 2002 01:34:20 -0400 Subject: sorting many arrays from one... In-Reply-To: Message-ID: [Jonathan Hogg] > Oh well, in that case you can trim another couple of % off the calls with: > > Index: listobject.c > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v > retrieving revision 2.116 > diff -r2.116 listobject.c > 783c783 > < res = PyEval_CallObject(compare, args); > --- > > res = PyObject_Call(compare, args, NULL); > > Since PyEval_CallObject just does some unnecessary typechecks on the > arguments. Cool! I checked it in. On this box it gave a 2.4% speedup when sorting lists of ints via list.sort(__builtin__.cmp), which is likely a best case for it (a single type check costs as much as comparing two ints). > Or being even more aggressive: > > Index: listobject.c > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v > retrieving revision 2.116 > diff -r2.116 listobject.c > 783c783 > < res = PyEval_CallObject(compare, args); > --- > > res = (*compare->ob_type->tp_call)(compare, args, NULL); > 1297a1298,1302 > > } > > if (compare && compare->ob_type->tp_call == NULL) { > > PyErr_Format(PyExc_TypeError, "'%s' object is not > callable", > > compare->ob_type->tp_name); > > return NULL; > > i.e., pull the remaining typecheck out to 'listsort'. But I don't > much like this one as it gains only a tiny amount over the one above, > seems quite a bit more obtuse (or is there a neater callable check > macro?), and also subtly changes the semantics (sorting an empty list > with a non-callable fails - though perhaps it should). I'm glad you're not going to fight to the death for it, because I'd fight to the death to keep it out . > ... > Yeah, I've had a short wander through the innards of cmp. It's a bit of a > convoluted one, but necessarily so. I don't see how the calls can be made > more optimal and cmp has to be the way it is, so I don't think > '.sort(cmp)' can be made any faster without checking to see if 'compare' > *is* 'cmp' and then not bothering to make the calls ;-) There's a ~20% speedup remaining to be had, via abusing the immutability of tuples and *reusing* the args tuple across docompare() calls, skipping the PyTuple_New(2) and later decref. Allocating and deallocating the args tuple each time through is a real expense. This is tricky to get right, though, because docompare() needs to be reentrant, and allocating a dedicated tuple per call cuts off a world of subtle problems. I'm not going to pursue this one. From wilk-spamout at flibuste.net Sat Jul 27 14:43:34 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Sat, 27 Jul 2002 20:43:34 +0200 Subject: PythonWin ODBC: DSN-less connecting string References: Message-ID: <20020727204334.347e534b.wilk-spamout@flibuste.net> Le Fri, 26 Jul 2002 16:49:11 -0700 "Jimmy Retzlaff" ?crivait: > Gabe Newcomb [mailto:Gabe.Newcomb at noetix.com] wrote: > > > I'm unable to find the right combination of options to build a > DSN-less > > connection string with which I can connect to a database using the > odbc > > module. Has anybody out there found the right way to do this? > > The current odbc module in win32all doesn't support DSN-less > connections. A while back I submitted a patch to Mark Hammond to add > support for this - hopefully it'll make it into the next release of > win32all. > > In the meantime I'd be happy to send a copy of my patched odbc.pyd > compiled for Python 2.2/2.2.1, or I can also send odbc.cpp if you'd like > to compile it yourself for another version of Python. do you mean you could become the new maintainer of odbc ? :) -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From gerhard.haering at gmx.de Wed Jul 17 23:14:04 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 18 Jul 2002 03:14:04 GMT Subject: SSL support in 2.2.1/win References: <3d362ab9@duster.adelaide.on.net> Message-ID: Gerald Squelart wrote in comp.lang.python: > I've downloaded and installed python 2.2.1 on my win2k machines, and > tried my first program... And I was disappointed to see that SSL > support is not enabled by default. Yeah. Me too. There's hope that this will change for 2.3. I compiled a SSL enabled socket.pyd and made it available at http://www.cs.fhm.edu/~ifw00065/pyssl/ Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From ods at fep.ru Tue Jul 23 12:53:42 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Tue, 23 Jul 2002 20:53:42 +0400 (MSD) Subject: how to count lines in a file ? In-Reply-To: Message-ID: On Tue, 23 Jul 2002, Shagshag13 wrote: S> hello, S> S> i need to count lines in a file (that i *can't* keep in S> memory, so can't use readlines()) fp = open(filename) it = iter(fp) try: while it.next(): count += 1 except StopIteration: pass -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From wangzhao_wz at hotmail.com Thu Jul 18 05:37:52 2002 From: wangzhao_wz at hotmail.com (zhao) Date: Thu, 18 Jul 2002 12:37:52 +0300 Subject: Problem with installing PyQt! References: Message-ID: Hi, Thanks for your help. I run "python setup.py install" in c:\python22\tools\idle and it install the library in "build\lib\idlelib" and "build\lib\idlelib\Icons", but a Error appears: file 'idle' does not exist. What happened? Why should we run the command "python setup.py install"? Can you write the process step by step? (sorry) I try to convert .ui file into .py using 'pyuic example.ui -o example.py', but an empty file was generated. why? Thank you very much! "d2002xx" wrote in message news:c73a070e.0207170932.23d1c3de at posting.google.com... > > Hi, > > I have installed python2.2.1 and Qt Non commercial(evaluation 3.0.4) for > > windows. And I try to install PyQt3.2.4 in my computer, but just got > > Example, Tutorial and Documentation, no executed application PyQt in it. > > Why? > > PyQT is not a executed program, it's mainly a library. If you have run > "python setup.py install", it should install the library(s) in subdir > "site-packages" in python library directory. From erict at millfilm.co.uk Fri Jul 5 12:12:45 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Fri, 05 Jul 2002 17:12:45 +0100 Subject: XML dom node comparaison Message-ID: <3D25C57D.EFB60B5A@millfilm.co.uk> There is a method "isSameNode" in the node interface that I cannot make to work. Does someone used it ? I am actually checking if there is any tools to let me compare hierachy node. Its not hard to do, but if it does exist already, I will be happy to use it. Thanks From aleax at aleax.it Thu Jul 4 12:47:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 4 Jul 2002 18:47:18 +0200 Subject: metaclass & __slots__ Message-ID: <02070418471803.27180@arthur> phoebe_1 at att.net (Holden Caulfield) writes: ... """ I am trying to get a hang of the metaclass and some new features in """ Excellent idea!!! Metaclasses are still under-used, so far. """ v2.2. But, I am running into a problem or it is a limitation, I guess. I just need clarification. Here is the code, it is an extension of """ Yes, I fully agree you just need a little bit of clarification -- you seem to be very, very close to grasping the metaclass issues fully, and only need to look at them from a slightly different angle for them all to click into place and make sense to you, I suspect. No limitation involved, and, to give the punch line away, all the problem is that your class MX is calling its superclass's __init__ too early -- it just needs to delay that a little bit. But, let's get into details: """ Basically, I am trying to set "property" attributes AND also limit the attributes set by using "__slots__". It looks like because the Metalcass statement is executed in the end of the class statement, hence the class methods seems to have a "early" binding to the __slots__ variable. Is this behaviour normal? """ There is no such thing as a 'Metaclass statement' . Rather, when your class statement's body binds an attribute named __metaclass__, as you do here, Python knows to use the value of that attribute as your new class object's type, i.e., metaclass. (Otherwise, Python uses other ways to decide what metaclass to use, but they don't matter here). There's no issue of early or late. Statements in a class body are executed one after the other as usual, when the class statement itself executes, *before* the metaclass comes into play: i.e., in your example: class X(object): __metaclass__ = MX __slots__ = ['z'] def __init__(self): self.x = 1 self.z = 2 def _get_x(self): return self.__x def _set_x(self,v): self.__x = v two bindings, to names __metaclass__ and __slots__, then three def statements (which bind function object to names __init__, _get_x, _set_x). The results of these bindings go into a dict, so it really makes no difference in the end which binding was executed earlier and which one was executed later, unless you bind more than one value to the same name (in which case the later binding "overrides" the earlier one) or similar second-order effects, none of which applies here. All the statements in class body boil down to constructing a dict and then the metaclass gets to work on that dict. So, what your MX's __init__ gets as its dict argument: class MX(type): def __init__(cls,name,bases,dict): is a dictionary with five items, as bound in the class's body. Add a "print dict" statement here to double check -- no rocket science involved, really, although it may SEEM there's some!-) So, now it's entirely up to your code in the body of MX.__init__ what happens. So let's examine what you actually do there to initialize object cls, which is the class X you're creating: super(MX,cls).__init__(name,bases,dict) so you first delegate everything to type, which is MX's superclass, with the dict exactly as build by the class statement. type.__init__ is responsible among other things for building the descriptors as specified by __slots__, so of course what rules is the value of dict[__slots__] at this point -- when you call type.__init__ -- not any changes that you might further make to that entry, right? props = {} slots = getattr(cls,'__slots__', []) print slots for v in dict.keys(): vs = v.startswith if vs("_get_") or vs("_set_"): props[v[5:]] = 1 for v in props.keys(): fget = getattr(cls,"_get_%s" % v, None) fset = getattr(cls,"_set_%s" % v, None) setattr(cls,v,property(fget,fset)) slots.append("_%s__%s" % (name,v)) setattr(cls,'__slots__',slots) So all of these statements may affect X.__slots__ in some ways, but since type.__init__ has already worked with its original value, that in turn has no effect on the descriptors of X. You do have some effect on the descriptors of X by the setattr in the for loop in which you instantiate the property built-in, but that's another issue. So, if you've followed so far, I hope the solution is reasonably obvious: what you want to do is alter your dict argument (don't bother getting or setting attributes on cls -- work with the dict arguments directly, possibly taking the bases into account if you need to) and THEN call type.__init__ with the _modified_ dictionary object. More generally, in your __init__ (whether of a metaclass or any other class): call the superclass's __init__ AFTER you have performed modifications to the arguments, if you need to change the arguments and the superclass's __init__ is going to take some action based on them. Metaclasses are no different (in this or most other respects) from any other class. Alex From fredrik at pythonware.com Wed Jul 3 12:59:17 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jul 2002 16:59:17 GMT Subject: Who is the user?? References: Message-ID: Kristian Sons wrote: > is there a possibility to find out, wich user startet the python-script?? import getpass user = getpass.getuser() From phr-n2002b at NOSPAMnightsong.com Wed Jul 17 01:05:22 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 16 Jul 2002 22:05:22 -0700 Subject: Session ID & Security References: Message-ID: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> Jan Felix Reuter writes: > Now I'm concerned about security, because with this sheme an attacker could > easily get access to a user's session by just guessing its ID. After some > research I found out about Message Authentication Codes and the hmac python > module. How does one use it? Do I apply the algorithm to every message (cgi > output?) and place the hash in another cookie or appended to the session ID > string? So, if the client sends back a hash that differs from the last hash > the server has send, the session is discarded, is that how you do it? Here's a simple way: pick some secret, unguessable, constant string, like "H5LV9-GRDP5-9FG5T-HLUDN". Call it K. Now to generate an authentication cookie, simply compute the HMAC of some session identifier, along with some non-repeating data. For example, let S = the username + IP address + exact login time and the auth cookie is the HMAC of S with key K. Note that using shelve for holding session data shared between multiple threads or processes is of dangerous unless you're using a fancy dbm underneath (like Sleepycat). Someone really should implement a session management scheme sometime using shared memory instead of messing around with stuff like shelve. > Hashing all the output seems a bit overkill to me. Wouldn't a simple random > number suffice? I get the feeling that I misunderstood the whole MAC thing. Maybe it's overkill, but you can never have too much overkill. ;-) From m.bohlen at tu-bs.de Sun Jul 7 18:08:24 2002 From: m.bohlen at tu-bs.de (Marc) Date: Mon, 08 Jul 2002 00:08:24 +0200 Subject: make cvs pserver/ssh(2) connection with python References: <20020707.223646.680466996.4043@tu-bs.de> Message-ID: <20020708.000822.654887343.4043@tu-bs.de> Im Artikel schrieb "Chris Liechti" : > [posted and mailed] > > "Marc" wrote in > news:20020707.223646.680466996.4043 at tu-bs.de: >> I am searching a way to make a cvs pserver or/and a ssh(protocol >> Version 2) connection with python under Linux/Unix. I've tried to >> control the cvs pserver >> connection by a python frontend which uses the normal cvs binary, but >> it won't work without using the 'normal console interaction' for input >> (maintainly the cvs login). >> I can get the inputstream, but I can't write correctly to the >> outputstream. I get the password query, but the answer fails. Perhaps >> someone have experience in writing a frontend for interactive programms >> under Linux/Unix and can help me. > > do you use popen? something like that: >>>> i,o = os.popen2("cat - >tmp") >>>> i.write("hello") >>>> i.close() >>>> o.close() At this time I use this: os.popen(command) The Problem isn't the reading and writing input-/outputstream, it's the timing(I think). I make a 'cvs login' then I'll be asked for the cvs password and the answer of this question fails. Perhaps I've to use the tty or ptty module of python, but I don't know how. I'm searching a way to handle his problem. I hope someone had similar problem (i.e. by writing a frontend for ftp,telnet,ssh,... (for interactive applications)). the Python version is 1.5.2 (I think! It is a pool with 20(?) workstations, different OS (Linux and Solaris, different versions)). I think popen2 is available python-version>2 and if it exists another way (as upgrade Pyhon) to solve the problem I'll use that way. Insteat, if you know a way to solve my problem by useing popen2 please give me a short example. From altis at semi-retired.com Tue Jul 9 02:26:08 2002 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 8 Jul 2002 23:26:08 -0700 Subject: uncaught TypeError exception in re module or redemo.py Message-ID: Hi, I ported the tkinter redemo.py code to PythonCard today. While doing the port I was trying various regular expression patterns and came across an uncaught exception in the recompile method: def recompile(self, event=None): try: self.compiled = re.compile(self.regexdisplay.get(), self.getflags()) bg = self.promptdisplay['background'] self.statusdisplay.config(text="", background=bg) except re.error, msg: self.compiled = None self.statusdisplay.config( text="re.error: %s" % str(msg), background="red") self.reevaluate() The except block catches various re errors, but it is possible to type a pattern that will generate a TypeError. It is simple to simply catch the TypeError with an additional except, but I'm wondering whether this should actually be caught in the re module and turned into an re.error like other invalid patterns? Here's an example chopped down to just the compile and the resulting TypeError exception. >>> re.compile('([a-') Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\sre.py", line 178, in compile return _compile(pattern, flags) File "C:\Python22\Lib\sre.py", line 226, in _compile p = sre_compile.compile(pattern, flags) File "C:\Python22\Lib\sre_compile.py", line 430, in compile p = sre_parse.parse(p, flags) File "C:\Python22\Lib\sre_parse.py", line 623, in parse p = _parse_sub(source, pattern, 0) File "C:\Python22\Lib\sre_parse.py", line 318, in _parse_sub items.append(_parse(source, state)) File "C:\Python22\Lib\sre_parse.py", line 583, in _parse p = _parse_sub(source, state) File "C:\Python22\Lib\sre_parse.py", line 318, in _parse_sub items.append(_parse(source, state)) File "C:\Python22\Lib\sre_parse.py", line 424, in _parse if this[0] == "\\": TypeError: unsubscriptable object >>> I'm using Python 2.2.1 on Windows 2000, so this might be fixed in the 2.3 alpha builds, I haven't tried them yet. ka --- Kevin Altis altis at semi-retired.com From jb at cascade-sys.com Thu Jul 11 00:20:25 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 10 Jul 2002 21:20:25 -0700 Subject: COCOMO - appropriate for languages like Python? References: <3D2C605D.82FB3008@mitre.org> Message-ID: <3D2D0789.B88D8D0F@cascade-sys.com> Mike Brenner wrote: > > JB wrote: > > From a schedule estimation standpoint, LOC (however you choose to count > them) appears to be a pretty good estimator to use for a fixed staff and fixed > > project sizes. How the prediction varies as you change staff or project sizes is > something you'll have to measure or guess at yourself. > > IMO, the following measurements apply to most Python efforts more than lines of code: The issues you raise are valid, though I think most can be restated in terms of a LOC productivity factor. > - Most software has achieved the status of "maintenance" rather than "development". Thus, millions of lines of code might require, say, a one-line change. Some of those one-line changes take a month of research and testing, while others take a few seconds. The lines of code changed (and the lines of code in the whole project) only correlate to new code, not to code under maintenance. To my mind, this is simply saying the average cost per new LOC is rather high in these circumstances and also the standard deviation also is high. IIRC, COCOMO has a way to take this into account. > - Software Maintenance time primarily increases as backlog increases (e.g. programmer overtime which the company intends to not pay, other work awaiting action, inadequate functional testing, deferred regression testing which detects reappearance of prior bugs, incomplete impact analysis of past and present changes, incorrect documentation, and the age of parallel development paths). For example, parallel development paths that last more than a few days (fractured baselines) start to take on lives of their own, and become more expensive to merge into a single "golden" baseline as they age. Increased backlog = increased project size. Per COCOMO, this => increased cost per new LOC or (more likely) decreased LOC per unit cost. However, IIRC, COCOMO does not have a parameter to calibrate for this particular criterion. Ha! Reminds me of one place I worked. The company lumped telephone tech support and software QA into a single group. QA schedules were pretty much fixed and when the phone rang it had to be answered, so this created a feedback loop in the ongoing software quality -- if it started to dip, phone calls went up, causing it to spiral further downward, due to even less QA resource. > - Software Maintenance time decreases as the technology factor (the part of the COCOMO model that applies to software maintenance rather than to new development) increase. Thus, to save time, get better tools for: Agreed. Per COCOMO, better tools => lower cost per new LOC. > - Software Maintenance time increases with the number of data integrity problems possible in the languages and tools used (coding bugs, data design flaws, data flaws, network design flaws, rifts, and sabotage). tools, problem domain complexity => increased cost per new LOC > - Software Maintenance time positively correlates to the amount of time that maintenance organization last maintained that type of code (after subtracting the time it takes to open up the configuration, which relates to how long since a project last opened that code). staff experience, staff domain experience => lower cost per new LOC > - Software Maintenance time negatively correlates with syntactic standards. "Good" standards can help even without a tool, e.g., by improving readability. "Bad" standards hurt no matter what. Good vs. bad is somewhat subjective. Whether good is worth the cost is debatable, though i've seen so many horror stories in code formats that I suspect some minimum standard always is in order. So I'll say "good" standards => lower cost per new LOC but the difference may be marginal. If you're going to enforce a standard, having a pretty print tool is best. > For example, a rule like "indent each level 3 spaces" slows down software maintenance and development in two ways. I agree. This is an example from one of the worst standards I ever encountered. > - When management decides to use a metric, and the programmers become aware of that metric, then the programmers take whatever action required to make that metric reach 100%. For example, if management pays the programmers by the line of code, the lines of code will increase. Having all the underlying metrics lying around begs the issue of why not use them to judge programmer performance? Some organizations have tried to do this and, yes, programmers immediately respond by inflating the metrics. Most promoters of cost modeling strongly recommend against doing this, precisely because it interferes with and distorts the result of future predictions. Furthermore, while measuring lines of code may be useful in predicting future lines of code, this is absolutely no way of measuring a person's contribution to the organization. Also the metrics work because they measure and predict gross, aggregate performance of a group on a project, not details about individuals. The primary intended usage of models such as COCOMO is to predict future project costs. That is, you calibrate the model with existing data in order that your future predictions about future projects will be more accurate. In order for this to work you generally need to assure programmers that the metrics specifically will NOT be used for performance measurement. The theory relies on people NOT changing their way of doing things and you generally need buy-in and full cooperation from the developers for it to work. Thus you need to be open and honest and consistent about how the metrics will be used and how they will not be used. Your concern here is valid but nobody I know of advocates abusing metrics this way. > - When management (personal, government, corporate, academic) requests non-applicable metrics like lines of code (a metric which makes sense only at development time) or McCabe Cyclomatic Complexity (a metric which makes sense only at testing time since it counts test paths and dings programmers for good stuff like nested SWITCH/CASE statements and BREAKs) to describe maintenance effort, consider get rid of that entire levelly management. I rather think LOC is a valid metric in all circumstances (although I agree it may be less reliable and thus less useful in some extreme cases). Cyclomatic Complexity metric was devised to abstract the code's underlying complexity away from purely lexical issues such as LOC which are more easily perverted by the developer. To my knowledge, none of the more complex metrics have shown themselves to be any better than simply counting LOC. And they're much harder to measure. So, IMHO, anything more complex than LOC is not worth the bother. > - Without an accepted standard definition of "lines of code", one cannot know whether to count every line in every IMPORTed module, or just those the INVOKED lines, or just those lines that do the invoking. For example, do we count every line in the python runtime module STRING.PY or just the lines in STRING.PY that our modules call, or just the lines in our module that call STRING.PY? These different counting strategies differ by orders of magnitude. I personally would count the import statements but not any of the imported lines. My view is that you have a list of modules written by a programmer and Linux' "wc" command tells you the lines of code. You don't get credit for an imported module unless you write it. More generally, I'd envision a CVS system that tracks lines changed, as in larger projects, different people ultimately work on the same modules. What about comments and blank lines? I say count 'em. Comments certainly CAN be as valuable as code. I also think blank lines as a form of code paragraphing are very important. If it was being abused, I might count multiple consecutive blank lines as a single one. While it is true that the definition of "LOC" can vary widely it is only important that you use the same definition across the domain of projects you wish to analyze (typically your own company or organization). Different definitions can produce consistent results so long as the definition is consistently applied to all the data. Of course, if you're trying to compare your projects to Boehm's or somebody else's, then it's probably apples and oranges. Even if you count LOC precisely the same way as the other org, numerous other variations are likely to account for an even bigger differences. The interesting thing about Boehm's work is that he has data for so many projects that the results likely do apply to your project in a more general level, in that the shapes of the curves likely will be similar, even if baseline and rates may vary. How do *I* use all this? Really. First off, I'm certainly not a big COCOMO fan. I've never actually used the full model for anything and don't rely on metrics or modeling much in real life. I read the book and it had some interesting insights. Some of the most important results from Boehm are the general results which pretty much apply to all projects. E.g., the vital importance of hiring only the best people and keeping project steps manageable (overall cost increases extra-lineraly with size). Boehm's not the first to say this but what's interesting is he says ALL the other factors are decidedly less important. Beyond that what I take away from this entire subject is that LOC is one easily computed, moderately useful, crude measurement of programmer productivity. It's better than nothing and I am unconvinced that anything more complicated is at all worth the extra effort. I usually use LOC to double-check my own progress. Typically a project seems to be taking longer than it should, I'll do a WC, and sure enough, it's working out to be like twice or 3X code than I expected. It's on occasion proved helpful with clients. E.g., I had a client complain about my bills and I was able to show that my company's contribution to his project was approximately twice the LOC as were in the original application; thus we were actually a bargain, since he paid many times as much to get that first 1/3. Counting lines is not the solution to all problems but it is yet another tool that has proven to be of some use to me on some occasions. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From dreed at capital.edu Mon Jul 8 16:23:43 2002 From: dreed at capital.edu (Dave Reed) Date: Mon, 8 Jul 2002 16:23:43 -0400 (EDT) Subject: subclassing int and accessing the value In-Reply-To: References: Message-ID: <200207082023.g68KNh904370@fourier.capital.edu> > From: "Mark McEahern" > Date: Mon, 8 Jul 2002 15:10:21 -0500 > Content-Type: text/plain; > charset="iso-8859-1" > X-Priority: 3 (Normal) > X-MSMail-Priority: Normal > Importance: Normal > X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000 > Content-Length: 609 > > > Now my question is, how do I access the actual value 5 internally so I > > can write my own __repr__ method that returns '$0.05'. I'm guessing it's > > using __getattribute__, but what attribute do I want to access? > > Short answer: Look no farther than self. ;-) > > E.g., > > class money(int): > > def __init__(self, *args): > super(int, self).__init__(*args) > > def __str__(self): > return "$%1.2f" % (float(self) / 100) > > x = money(5) > > print x Ugh, that's too simple :-) Thanks! Is there a long answer? :-) > If you're looking for a way to represent money, you may want to use a fixed > decimal class. I'm using Tim Peter's FixedPoint class. Yes, I need to give this some more thought. If I actually end up using this, it will need to interface with a database (MySQL or PostgreSQL) so I need something that will be easy to back and forth between the SQL representation and the Python representation. I got your reply before I even saw my message show up on the list - I must be near the bottom of the send list. Thanks, Dave From phr-n2002b at NOSPAMnightsong.com Thu Jul 4 04:27:19 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 04 Jul 2002 01:27:19 -0700 Subject: [OT] What is Open Source? References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <7x65zv5254.fsf@ruckus.brouhaha.com> mertz at gnosis.cx (David Mertz, Ph.D.) writes: > "Clark C . Evans" wrote previously: > |I don't. I firmly believe that copyright and patent are > |fundamentally good ideas (trademark is the best of the three). > |They are a contract between the public as a whole to a inventor/author. > > The only problem with this belief is that it is completely, totally, > 100% wrong. A copyright is, quite simply, a legally enforced artificial > monopoly--not a contract. These are quite different things. I think Clark was using contract in a metaphorical sense, describing a deal made with authors on one side, and society as a whole on the other. In what's called the "copyright bargain", society agrees to grant limited temporary monopolies, in exchange for increased "progress in science and the useful arts". There is some really terrific reading on the legal history of copyright in the Amicus Curiae briefs to Eldred vs. Ashcroft linked from . If you're not aware, Eldred vs. Ashcroft is a case currently before the Supreme Court that aims to get the most recent copyright extension (Sonny Bono Copyright Term Extension Act, passed in 1998 by Disney lobbyists trying to stop Mickey Mouse from ever entering the public domain, and extending all copyrights by 20 years) thrown out on the grounds that it doesn't promote progress. I especially recommend Malla Pollack's brief which is short and forceful. For patents, Fritz Machlup's 1958 "Economic Review of the Patent System" is terrific, but I don't know if it exists online. It's a report to the Subcommittee on Patents, Trademarks, and Copyrights of the Senate Judiciary Commitee, 85th Congress 2d Session. One of these days I'll get a hardcopy and scan it. Some excerpts are here: http://swpat.ffii.org/papri/machlup58/index.en.html From peter at engcorp.com Fri Jul 12 04:33:49 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Jul 2002 04:33:49 -0400 Subject: Python for data driven website? References: <3D2E51A0.730F521A@engcorp.com> Message-ID: <3D2E946D.2838329C@engcorp.com> Micah Mayo wrote: > > > > > You don't need to say any more than that to elicit the correct answer > > at this point, which is "what are your requirements?". > > > > You need to get a handle on what you actually need to accomplish, [...] > > > Definatly reliabilty/scalability. [...] Don't limit yourself to those, or the others I suggested. You need to go back to the "old guy" (I bet he's, what, 26? :-) and get the group to define all the other dimensions along which your potential solutions must be measured. Security? I can't believe I didn't mention security in the previous message. You're talking about customers who will probably be sending private information over the web, right? Need to know about authentication and encryption issues, presumably... some solution really fall down in this area. Keep listing those "ilities" until you run out. If you miss a key one, you may end up with a square peg and spend the next year hammering it into a little round hole. By the way, "We have a preliminary version ... but it is far from done. We want to do this right the first time - we expect to spend a year working on it" makes me think that you guys ought to spend a brief time investigating Extreme Programming and considering whether you might benefit from a more iterative approach with more frequent releases to get feedback on the direction you are taking, as well as to help focus you on the most important tasks so you don't get distracted on low business value items for too much of the project. No project like this should be worked on for three man-years before its first release, at least not in this day and age! -Peter From jepler at unpythonic.net Fri Jul 5 14:30:26 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 5 Jul 2002 13:30:26 -0500 Subject: replacing instance __setattr__ In-Reply-To: <20020705182727.GA2269@unpythonic.net> References: <20020705182727.GA2269@unpythonic.net> Message-ID: <20020705183026.GB2269@unpythonic.net> Uh, scratch that -- obviously I missed the point of this conversation. Jeff On Fri, Jul 05, 2002 at 01:27:33PM -0500, Jeff Epler wrote: > On Fri, Jul 05, 2002 at 04:45:45PM +0000, Alex Martelli wrote: > > This doesn't impede your abilities to customize an instance, without > > affecting other instances of the same class: > > > > def changeSpecial(inst, name, function): > > class Customized(inst.__class__): pass > > setattr(customized, name, function) > > inst.__class__ = Customized > > why not > def changeSpecial(inst, name, function): > method = new.instancemethod(function, inst, inst.__class__) > setattr(inst, name, method) > > >>> def f(self, x): print x > ... > >>> class C: pass > ... > >>> c = C() > >>> changeSpecial(c, 'f', f) > >>> c.f(3) > 3 > > No setting of the __class__ attribute here, which is something that > gives me more willies than calling new.instancemethod and doing a > setattr on the instance... > > Jeff > > > -- > http://mail.python.org/mailman/listinfo/python-list From nafai at twistedmatrix.com Fri Jul 5 17:28:40 2002 From: nafai at twistedmatrix.com (Travis B. Hartwell) Date: Fri, 05 Jul 2002 21:28:40 GMT Subject: Link checking, POST logins, and cookies Message-ID: <87vg7tsw69.fsf@twistedmatrix.com> Hi all, I am in need of a link checking program for a web application I am developing. I have looked at linkchecker (http://linkchecker.sf.net), but it doesn't quite do what I need. Our web application requires users to log into the website via a page that uses POST logins. Then, a cookie is stored in the session to keep them logged in. Here's the problem. I have successfully been able to log into the website with a script I wrote with Webunit (http://webunit.sf.net/), and I would have liked to tie the two together since webunit can do the logins, cookies, and keep the session. Unfortunately, I saw no straightforward way of doing this. I e-mailed the author about this (he was quite prompt and helpful, thanks!), but unfortunately they are incompatible. He gave me a suggestion to try with the beta version of linkchecker, but alas, it didn't work. This leaves me with this question...has any one else done this? I'm sure this is a common thing, would it not be? Any help or pointers would be appreciated. Travis From jonathan at onegoodidea.com Mon Jul 1 16:47:14 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 01 Jul 2002 21:47:14 +0100 Subject: New style classes as exceptions (Was: exception handing) References: <7V%T8.69851$F16.33443@atlpnn01.usenetserver.com> Message-ID: On 1/7/2002 18:02, in article 7V%T8.69851$F16.33443 at atlpnn01.usenetserver.com, "Steve Holden" wrote: > I fail to see how the example above claims to "subclass from Exception". Seems pretty clear to me: >>> class FooError( StandardError, object ): ... pass ... >>> issubclass( FooError, Exception ) 1 >>> f = FooError( "No foo." ) >>> f <__main__.FooError object at 0x40a310> >>> print f No foo. >>> isinstance( f, Exception ) 1 >>> Looks like an Exception, walks like an Exception, but unfortunately can't be raised. > It > certainly doesn't seem to be a very good idea to use object as one of the > bases, since this is *known* to cause problems. Yes, the main problem being that it just doesn't work ;-) > Instead see, for example: > > >>> class MyError(IOError): > ... pass > ... I think it's obvious that the answer is Well Don't Do That. But ... > I think it's currently a feature, but it will doubtless become a bug if this > situation continues for too long... ... as you say, if new-style classes are the future, and certainly the present now, then it doesn't make much sense to not be able to raise them. Jonathan From marklists at mceahern.com Sat Jul 13 02:07:27 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 13 Jul 2002 01:07:27 -0500 Subject: switch recipe? In-Reply-To: Message-ID: [Tim Peters] > Then that's where we differ: I don't consider an empty sequence to be "an > error" in any sense of the word. For the same reason, range(10, > 10) doesn't complain in Python, or string[i:i], etc -- doing nothing > gracefully is important because there's sometimes nothing that needs > be done . I think I'll continue to scratch my head and profit from that observation for quite some time. Thank you. Profit--or better yet, lose. My misconceptions, that is. So where I've ended up is a place I'm sure there's some fancy name for--but I don't know it. I have two iterators, one is finite, the other is a repeating alternator. I want to walk through both of them at the same time, which means I'll stop when the finite one is done. (If I need to stop sooner, I can use a sentinel on the finite one--but I'd rather ignore this variation for now). I want to apply some function to the items from each iterator and then yield the result--which suggests a third iterator. I guess I wonder whether there's a pattern here that anyone has named--or if there's a pattern that better expresses what I can only dimly see and express. I have trouble naming things, so again, any tips on names is helpful. In the following, I would express weave_items with the following pseudo code: for item, alternate in iterator, alternator: yield weave_item(item, alternate) Instead, I have to explicitly call next(), which will raise StopIteration if I happened to pass in an alternator with no args. Because I have no way (as far as I can tell) of asking alternator, "Do you have any more bananas?" That is, I can't peek into it (unless I wrap it in a class or something, I suppose): from __future__ import generators def repeating_alternator(*args): """Return a repeating alternator for args.""" while args: for a in args: yield a def weave_items(iterator, alternator, weave_item): """Iterate over iterator, applying weave_item to each item with its pair in alternator. """ for item in iterator: yield weave_item(item, alternator.next()) def color_item(item, color): template = "<%(color)s>%(item)s" return template % locals() Well, that was a bunch of poorly strung together thoughts. But it's late. And just think, I squeezed all of this out of someone's question about how they could squelch the "extra" space emitted by print foo. Perhaps Liebniz was right. Cheers, // mark - From mis6 at pitt.edu Sat Jul 27 19:26:06 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 27 Jul 2002 16:26:06 -0700 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: <2259b0e2.0207271526.1214228@posting.google.com> I know a print statement cannot stay in a lambda function, however as a newbie I ask : why ? Michele From wilk-spamout at flibuste.net Mon Jul 29 03:59:51 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Mon, 29 Jul 2002 09:59:51 +0200 Subject: order of test Message-ID: <20020729095951.4cfad491.wilk-spamout@flibuste.net> hi, can we be sure of the order of a test expression ? i mean that t=["one","two"] x=10 if x<2 and t[x]=="oups": will never throw an exception if t[2] will be tested before x<2 thanks -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From altis at semi-retired.com Thu Jul 18 19:38:16 2002 From: altis at semi-retired.com (Kevin Altis) Date: Thu, 18 Jul 2002 16:38:16 -0700 Subject: examples of a safe Unpickler? Message-ID: The Security section of the pickle module documentation: http://www.python.org/doc/current/lib/pickle-sec.html talks about creating a safe unpickler. We're exploring using pickles as a basic storage format with PythonCard and I would like to be able to load a file without any chance for a rogue pickle file becoming a security problem. It is expected that users will exchange pickled data files via email, download them from web sites, etc. so while the data written by a given app will always be simple data types, there is no way of knowing that about the pickle when it is loaded. I just want to store built-in data types, lists, and dictionaries, no custom classes or functions. This is an alternative to using something like XML, where the overhead of loading and parsing a large file to turn it back into say a list of dictionaries can take quite a long time and thus is unacceptable for primary storage. So, are there examples of an unpickler (preferably based on cPickle for speed)? It is not clear to me from the documentation what I actually need to do. The docs seem to imply that if an object is not marked as __safe_for_unpickling__ then an UnpicklingError exception might be thrown just using the default Unpickler, but if so, I would need an example or two of a pickle with a security problem to test this. Throwing an exception would be fine. It would be nice if there was a separate UnpicklingSecurityError exception. Thanks, ka --- Kevin Altis altis at semi-retired.com From gmfawcett at operamail.com Wed Jul 10 10:08:25 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 10 Jul 2002 07:08:25 -0700 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> <3D2BBA06.4040808@something.invalid> Message-ID: <3d799735.0207100608.73300d02@posting.google.com> Greg Ewing wrote in message news:<3D2BBA06.4040808 at something.invalid>... > Graham Fawcett wrote: > > > I suppose that one could add a distutils.command.pyrexc as a > > subcommand of "build_ext" to handle the .pyx compilation. That way the > > os.system() call in the build script could be avoided. I've never > > written a distutils command, but perhaps I'll give that a try. > > > I've been too busy fixing bugs to look into this > myself, but that definitely seems to be the way > to go. If anyone wants to have a go and contribute > the result, it'll be much appreciated! I've posted a first-blush version to the list, under the subject "Pyrex and Distuils: an enhanced build_ext command". Cheers, -- Graham From dfackrell at DELETETHIS.linuxmail.org Tue Jul 23 11:33:55 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Tue, 23 Jul 2002 09:33:55 -0600 Subject: Make me beautiful (code needs help) References: Message-ID: <3d3d7763$1_3@hpb10302.boi.hp.com> "Mark" wrote in message news:HVd%8.6582$I4.1825 at nwrddc03.gnilink.net... > Ok, I have the following data: > > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] > > That is, I want to get the successive differences into their proper place. > I don't care what is in the question mark spot. I'll figure that out later. > > Here's my current code: > > for i in range(len(data["A"])): > try: > data["new"].append(data["A"][i] - data["A"][i-1]) > except OutOfBounds: > data["new"].append("?") > > Now, the other problem, is that in general, I want to fill data["new"] with > an arbitary function of the values in data["A"]. As a dumb example, I > might want to fill data["new"] with copies of the mean (average) of > data["A"]. So, in some cases, the new values are relative to the current > location (ie i and i-1) and in other they are absolute (ie all of them). > > I can certainly hack through this, but I'm looking for something pretty. I > know python is up to it. > > Regards, > Mark How about this for the narrow case? If you really want the new list to be the same length as the original one, you can pad at the start or end: A= [1, 2, 4, 10, 50] new = [] for i in range(len(A)-1): new.append(A[i+1] - A[i]) -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From martin at v.loewis.de Sun Jul 21 16:36:21 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Jul 2002 22:36:21 +0200 Subject: XML with Python - supposed to be simple? ;) References: Message-ID: "Vladimir Cherepanov" writes: > As a complete newbie to both XML and Python, I've been trying to > create (any!) XML document using DOM API in PyXML package. Very > simple task isn't it? No, XML is difficult; it becomes more difficult the closer you get to it. Creating documents with DOM is indeed tricky. I recommend that you use plain print statements, like print "" which creates a nicely well-formed XML document. If you insist on using the DOM, I recommend that you read the DOM spec first (from www.w3.org). You'll then learn that you can create Document instances by invoking createDocument on the DOMImplementation. For minidom, you get the DOM implementation by calling xml.dom.minidom.getDOMImplementation(). Regards, Martin From oliver.eichler at dspsolutions.de Fri Jul 19 02:19:13 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Fri, 19 Jul 2002 08:19:13 +0200 Subject: get a list printed in hexadecimal notation References: Message-ID: Bengt Richter wrote: > >>> l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255) > ^ ^^^^^ ^ > >>> print [isinstance(x,int) and hex(x) or x for x in l] > ['spam', '0xa', '0xf', 'more spam', ['nested', 65535, 'spam'], 'spam', > ['0xff'] I never do such complicated things at home ;) But you are right for more complex lists the one liner won't fit. Oliver From dhzhang at fnal.gov Tue Jul 30 12:58:00 2002 From: dhzhang at fnal.gov (Dehong_Zhang) Date: Tue, 30 Jul 2002 11:58:00 -0500 Subject: how to change the colormap? Message-ID: Hi, Could the experienced forks tell me how to do this? I would like to change "white" to "black"/(0, 0, 0) before dumping a canvas to a postscript file. Thanks much and best regards, Dehong From aleax at aleax.it Sat Jul 27 11:01:20 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 15:01:20 GMT Subject: Guide to the python interp. source? References: Message-ID: <4By09.127744$Jj7.2947734@news1.tin.it> Tim Gahnstr?m /Bladerman wrote: ... >> > Things I want to change is for example, everything should be "call by >> > refferense", >> That may be very hard. If you want things like this: >> >> def f(x): >> x += 1 >> >> i = 2 >> f(i) >> i --> 3 >> >> then you have problems. > > That is exactly what I want to have, that is more intuitive I think and I > don't think it must be that hard either. It is not a speed issue so it It's hard to believe that you can hold such opinions if you understand Python. Or if you have really thought about the issues, such as -- what happens when two or more arguments are involved and interact? E.g., they're the same variable, or an index and an indexing that uses it, etc...? def f(x, y): x = 23 y = 45 and: i = 7 f(i, g[i]) We understand that you keenly want i to be 23 as "more intuitive" (I've never seen a programming beginner tackling Java or Python as a first language expect that -- the "intuitiveness" appears to come entirely from the way some OTHER languages behave:-), but what should "intuitively" be the item of g that is affected? In CBR languages, it's invariably g[7] that gets the 45, and THAT baffles every beginner I've ever met. Affecting g[23] would be "call by NAME" and indeed very intuitive, but such a living hell to implement that since Algol-60's demises I doubt any language has gone down that route. > must not be a true CBR. I will probably figure out some ugly hack to make > it seem like CBR. > Maybe look into value/copy return as Alex Martelli mentioned. What I want > is not really CBR but the, from Ada known "in out parameters" or the > Pascall "var parameter". Ada and Pascal have value semantics. x = y makes a COPY of the stuff held in a "box" named y, into a "box" named x. Python has no boxes, it has post-it notes -- reference semantics. That changes everything... Alex From slhath at charter.net Sun Jul 28 21:29:48 2002 From: slhath at charter.net (Scott Hathaway) Date: Sun, 28 Jul 2002 20:29:48 -0500 Subject: conditional importing Message-ID: How can I do a conditional import? I am creating a database wrapper class that is similar to adodb in PHP. I have the following class: from mx.ODBC import Windows as db1 import MySQLdb as db2 class adodb: # global vars global db1,db2 # class level vars dbType = 'odbc' db = db1 def __init__(self,dbType='odbc'): self.dbType(dbType) def dbType(self,dbType): global db1,db2 self.dbType = dbType if(dbType=='odbc'): self.db = db1 if(dbType=='mysql'): self.db = db2 return self.db Is this the best way to do a conditional import? Also, if there is an error in loading one of the two modules at the top, what is the best way to catch that? I could put try ... excepts around each one, but is there a better way? By the way, when I am finished with this class, I will post a link to the group so that if anyone else wants to use it, they can. It allows you to access the fields in the database by name instead of position of the field. It also has a function that allows you to pass a dictionary with key-values pairs that match your database and it automatically decides whether to do an insert or an update and then returns the appropriate SQL statement. Thanks, Scott From raimo-news at mail.com Wed Jul 31 11:46:01 2002 From: raimo-news at mail.com (Raimo Tuisku) Date: Wed, 31 Jul 2002 18:46:01 +0300 Subject: Window does not resize it's components References: Message-ID: On Wed, 31 Jul 2002 18:11:52 +0300, Martin Franklin wrote: >> I want. How can I make them fit precisely in the window borders even if > Is this Tk(inter) ? Yes(If there are others, tell more ;)). > If so then when you .pack() these widgets add a few extra arguments Well, I'm using grid at the moment but maybe the pack will work also. > expand=1 or 0 - expand widget if parent size grows fill=NONE or X or > Y or BOTH - fill widget if widget grows in=master - use master to Oh, I did not notice these. From whisper at oz.net Tue Jul 9 18:10:59 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 9 Jul 2002 15:10:59 -0700 Subject: A better self Message-ID: I notice that in every discussion of self, there's always a '.' in there. So, why not make a leading '.' mean self? AFAIK, it's otherwise currently illegal. The only drawback that I can think of is that it's less visible as a first argument for class defs. class foo(): def __init__(., me, me2, me3) .a = me .b = me2 .c = me3 def fee(.) print .a, .b, .c def bar(.) .fee() What I like about it is that it's resonant with the use of '.' to denote members/components of modules (i.e: sys.path) and suggests that the identifier is a member of the local "capsule" (or class scope if you prefer). I see it as answering the needs of both camps: it's easy to typy, unobtrusive and yet supports the "belt and suspenders" crowd who are not comfortable with an implied self. Before you all react (programmers can be SO conservative), please think about it! David LeBlanc Seattle, WA USA From aleax at aleax.it Fri Jul 5 16:56:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 20:56:05 GMT Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> <3d260494$0$12308$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Boudewijn Rempt wrote: ... >> auxdict.setdefault(count, []).append(name) ... > I really should read the documentation for each new release... I If you intend to use or need to support that release, that's a good idea. Or, read the Python Cookbook, which will be launched in 3 weeks at OSCON -- it covers many such novelties in the context of complete recipes... I think it's a good way to learn about them (and, of course, I _am_ utterly unbiased...:-). > had completely missed the arrival of 'setdefault'. Probably means > that I'm stuck in the 1.5.2 ages or something :-(. I also have an article in the latest (July 2002) Linux Magazine about the many benefits obtained from upgrading from 1.5.2 to 2.2, though in the callouts, and here and there even in the text, they did manage to mangle many of my "2.2"'s to "2.0", thus probably making the point of the article a bit confused for most readers... Alex From whisper at oz.net Fri Jul 5 19:44:11 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 5 Jul 2002 16:44:11 -0700 Subject: StandaloneZODB on Python 2.2.1/Windows? Message-ID: Neither the bundled 1.0 distro or the latest CVS seem to want to work for me on Windows 2kpro sp2 with Python 2.2.1 Crashes with a pointer exception on trying to run anything. Anyone had any success with this platform? David LeBlanc Seattle, WA USA From bokr at oz.net Sat Jul 13 02:06:19 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2002 06:06:19 GMT Subject: making zip with list comprehensions References: Message-ID: On Tue, 09 Jul 2002 11:06:54 +0100, Jonathan Hogg wrote: >On 9/7/2002 10:56, in article oryW8.234$xm1.54155 at news0.telusplanet.net, >"Ian McMeans" wrote: > >> I was idly trying to replicate zip's (the function) behavior using list >> comprehensions, but I couldn't do it. >> >> Can anyone? I came up with these, but they're ugly. >> >>>>> [(x,y) for x in ['a','b','c'] for y in ['d','e','f'] if >> ['a','b','c'].index(x) == ['d','e','f'].index(y)] >> [('a', 'd'), ('b', 'e'), ('c', 'f')] >> >> This is ugly because it loops far too many times =) >> >>>>> [ (['a','b','c'][x], ['d','e','f'][x]) for x in range(3)] >> [('a', 'd'), ('b', 'e'), ('c', 'f')] >> >> This isn't so bad. Does anyone have better suggestions? >> >> > >Best I could come up with is: > >>>> xs = [ 'a', 'b', 'c' ] >>>> ys = [ 'd', 'e', 'f' ] >>>> >>>> [ ( x, yi.next() ) for yi in (iter(ys),) for x in xs ] >[('a', 'd'), ('b', 'e'), ('c', 'f')] >>>> > >I think the lack of a clean way of doing lockstep iteration is exactly why >'zip' was invented ;-) > Well, >>> [(x,y) for x,y in map(None, xs, ys)] [('a', 'd'), ('b', 'e'), ('c', 'f')] is generated as a list comprehension, though it's kind of silly, considering >>> map(None, xs, ys) [('a', 'd'), ('b', 'e'), ('c', 'f')] ;-) Regards, Bengt Richter From hamish_lawson at yahoo.co.uk Thu Jul 18 14:59:00 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 18 Jul 2002 11:59:00 -0700 Subject: slicing and parallel assignment: inconsistent behaviour?? References: Message-ID: <915a998f.0207181059.47f35482@posting.google.com> Toby Donaldson wrote: > >>> B = range(10) > >>> B[1:5], B[5:10] = B[5:10], B[1:5] > >>> B > [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] > > This works as I expect. But if I leave out the 10s in the slice > indices, I get this: > > >>> A = range(10) > >>> A[1:5], A[5:] = A[5:], A[1:5] > >>> A > [0, 5, 6, 7, 8, 1, 2, 3, 4] To make things clearer, let's create a list A that has the numbers 0 to 9, and another two lists B1 and B2 each with 10 stars: >>> A = range(10) >>> A [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> B1 = ['*'] * 10 >>> B1 ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'] >>> B2 = ['*'] * 10 >>> B2 ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'] Now we'll modify B1 and B2 by assigning slices from A. We'll take each slice of A sequentially rather than in parallel. First we assign A[5:10] to both B1[1:5] and B2[1:5]. Note that the size of the slice from A has 5 elements, but the size of the LHS slices for B1 and B2 is only 4. Thus the size of B1 and B2 are both increased to 11. This increase in size is the crucial factor. >>> B1[1:5] = A[5:10] >>> B1 ['*', 5, 6, 7, 8, 9, '*', '*', '*', '*', '*'] >>> B2[1:5] = A[5:10] >>> B2 ['*', 5, 6, 7, 8, 9, '*', '*', '*', '*', '*'] Now we come to assign the A[1:5] slice. To see the difference between assigning to [5:10] and to [5:], we will do the former for B1 and the latter for B2. Because B1 and B2 are now both 11 elements long, B1[5:10] is not the same size as B2[5:]. Thus the 4 elements of A[1:5] replace *5* elements in B1[5:10] but *6* elements in B2[5:] - B1's last element (B[10]) is not involved. >>> B1[5:10] = A[1:5] >>> B1 ['*', 5, 6, 7, 8, 1, 2, 3, 4, '*'] >>> B2[5:] = A[1:5] >>> B2 ['*', 5, 6, 7, 8, 1, 2, 3, 4] Hamish Lawson From jonathan at onegoodidea.com Sun Jul 14 04:18:52 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Sun, 14 Jul 2002 09:18:52 +0100 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <7x65zj60ku.fsf@ruckus.brouhaha.com> Message-ID: On 14/7/2002 2:46, in article agql4s$np5pt$1 at ID-125932.news.dfncis.de, "Christopher Browne" wrote: > Furthermore, what I'm trying to have as an underlying "theme" in the > "music" is that it might very well be easier to build a Lex/Yacc > grammar using C and link it in than to fight your way through > designing the XML-based system. There may be more "elegant" options > than Lex/Yacc; the underlying theme is that that doesn't prevent the > "design-the-grammar-from-scratch" approach from being more manageable > than XML. Do you find using XML-parsing libraries a fight? Certainly in Python I have found using the XML libraries to be astonishingly simple. The thing is, using lex and yacc (or whatever your favourite parsing framework may be) may possibly be easier if you're already comfortable with it. But in order to use them you need to design a syntax. The resulting syntax is useful only to programs that have a parser for that syntax. With XML, the data can be imported, queried, and translated by anyone or any program with a basic XML toolkit. As I tried to show before, with tools like XPath, one can extract useful information out of any XML file. And to answer Fran?ois' earlier point about not being able to use "standardised" meaningfully with regard to XML. I consider XML to be "standardised" not because the W3C said so, but because parsing, validating, querying, and transforming frameworks are available for nearly any language off-the-shelf, editors support it, and database and data manipulation tools support it. I'm afraid Pickle doesn't come close in this regard (and isn't human readable anyway). CSV is probably closer but it doesn't support complex enough structure for me. ASN.1 might be a contender but also isn't human readable and doesn't have the same availability of tools. And certainly, any random syntax I might come up with will have support no further than I write. People like to scoff at so-called "Enterprise" computing, but in large organisations every new file format that someone comes up with represents a new maintenance headache. I don't want to have to reverse engineer file formats and come up with custom parsers every time I need to make two different systems interoperate. Jonathan From rnd at onego.ru Tue Jul 23 02:17:48 2002 From: rnd at onego.ru (Roman Suzi) Date: Tue, 23 Jul 2002 10:17:48 +0400 (MSD) Subject: Anybody using 4suite for xslt processing? In-Reply-To: Message-ID: On Mon, 22 Jul 2002, John Hunter wrote: It is interesting that sometimes Distutils create an rpm which makes directory in site-packages with a needed package inpenetrable to anyone except root. I remember several times I needed to change permissions back to allow others to access it. Probably xslt dir has wrong permissions. (What happens? Does root's umask interfer? The problem arises when I am trying to do python2 setup.py bdist_rpm with some packages and then install i386.rpm from dist subdir.) Another question about 4Suite xslt processing is: how to allow it to live with PyXML correctly? PyXML docs say I need without-xslt and without-xpath optins to have non-conflicting setup... >>>>>> "Marko" == Marko Faldix writes: > > Marko> In diretory Python22\Lib\site-packages\Ft\Lib there is a > Marko> file __packageInfo__.py that says: version = "0.12.0a2" > >Mine is 0.11.0 > > Marko> What do you have in your directories, which path contains a > Marko> class with appendstylesheeturi? > >I have the Ft dir, but I also have the _xmlplus dir. When I use a >recursive grep on *.py files in my site-packages tree for >appendStylesheetUri, I get three matches: > >./Ft/DbDom/transformDbDom.py >./_xmlplus/xslt/Processor.py >./_xmlplus/xslt/_4xslt.py > >It appears that the xslt/Processor.py is the one you want. Why you >don't have it, I don't know. > >John Hunter > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.2 From mgilfix at eecs.tufts.edu Wed Jul 31 11:01:58 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 31 Jul 2002 11:01:58 -0400 Subject: Cookbook: Associating multiple values with each key in a dictionary In-Reply-To: <20020730215002.A2145@bork.demon.nl>; from egbert@bork.demon.nl on Tue, Jul 30, 2002 at 09:50:02PM +0200 References: <20020730171536.A992@bork.demon.nl> <20020730131414.C7503@eecs.tufts.edu> <20020730215002.A2145@bork.demon.nl> Message-ID: <20020731110157.D26901@eecs.tufts.edu> On Tue, Jul 30 @ 21:50, Egbert Bouwman wrote: > On Tue, Jul 30, 2002 at 01:14:14PM -0400, Michael Gilfix wrote: > > > > I'm not really sure why you prefer the list method. Is there something > > that you can't accomplish with the nested dictionaries? > > When I need > { 'boys': ['mike', 'egbert'], 'girls': ['laura','lisa'] } > it hurts me when I have to build: > { 'boys': {'mike' : 1, 'egbert' : 1}, 'girls': {'laura' : 1,'lisa' : 1} } > > That adds an extra layer of complexity when i construct it, > I have to remember or document that the values can be thrown away, > and I have now sets of keys, while I need sets of values. This is exactly the kind of situation that python classes dream of. Check out the following class (which is very pythonic) and lemme know if this does what you'd like: Contents of t.py: class mydict: def __init__ (self): self.nested_dict = { } def append (self, key, value): if not self.nested_dict.has_key (key): self.nested_dict[key] = { } self.nested_dict[key][value] = 1 def __getitem__ (self, key): return self.nested_dict[key].keys () Python 2.1.3 (#1, Apr 9 2002, 20:09:43) [GCC 2.95.3 20010315 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import t >>> f = t.mydict() >>> f.append ('foo', 'mike') >>> f.append ('foo', 'egbert') >>> f.nested_dict {'foo': {'egbert': 1, 'mike': 1}} >>> f['foo'] ['egbert', 'mike'] By exploting __getitem__, I get the exact behavior you want while I'm guaranteed that each item will be unique. AND, it'll be fast too. This is also relatively straight-forward. The __getitem__ protocol method allows you to use the object how you want while keeping its internals separate. > Of course that all changes when I really need the values, ie when > they don't have some dummy value anymore. But in that case > we simply have a nested dictionary, which is not our subject now. I'm sure you can extend this interface to do whatever you like :) > As an afterthought: is it necessary that lists are slower than > dictionaries ? Cannot they be subjected to some hash machine as well ? > At least in some cases, ie when you search in lists ? Lists are not necessarily slower than dictionaries. They can be just as fast for things like list appends. But lists are made for storing sequences of objects and with each append, you extend the sequence. A dictionary (or hash table if you prefer) has the advantage that each key maps to the same location (and quickly), whereas in a list, you only have an index number to reference locations in the list. Thus hashing is a better fit for the unique problem because you always look in the same place, while in lists you have to search the entire list to be sure that your item is unique. Hope that makes sense. If you have little experience with hash tables, I suggest taking the time to read some literature, as they are very common in nearly all CS problems and let you do some pretty cool tricks. -- Mike From peter at engcorp.com Fri Jul 12 09:41:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Jul 2002 09:41:21 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> <3D2E8F10.B9B4EFD2@alcyone.com> <3D2E91ED.B061D0EB@engcorp.com> <3D2EA00F.582923B3@alcyone.com> Message-ID: <3D2EDC81.15FDD23F@engcorp.com> Erik Max Francis wrote: > > Peter Hansen wrote: > > > It always helps when the smileyless posts contain actual humour, > > no matter how subtle. Like yours, unlike the other. > > Sheesh. Even with a smiley, you still get pissy. I didn't think *any* of the posts were pissy yet, except Louis' comment that I ought to just develope (sic) my own keyboard. Strange how lack of face-to-face contact tends to destroy the friendliness of a thread, and the posters. From marvelan at hotmail.com Thu Jul 25 14:04:21 2002 From: marvelan at hotmail.com (M) Date: 25 Jul 2002 11:04:21 -0700 Subject: if(debug), optimized away? Message-ID: I would like to use something like this when running in debug mode: if(debug): if(items > 9): print "fatal error..." do_some_check_foo(42) ... If I set debug=0, is this code optimized away as in most C/C++?? compilers? The reason for asking is that I would like to have A LOT of debugging code and would like to avoid the performance penalty when not runing in debug mode. Are there other, perhaps more Pythonish, ways of doing the same thing? /M From duncan at NOSPAMrcp.co.uk Mon Jul 8 09:59:50 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 8 Jul 2002 13:59:50 +0000 (UTC) Subject: Properties - when and why References: Message-ID: "Arthur Siegel" wrote in news:mailman.1026132261.447.python-list at python.org: > Alex writes - > >>The obvious solution for this case is to keep your original >>get_V method intact and to code V_homogeneous the simple way: > >>def V_homogenous(self): >> V = self.V >> return array((V.x,V.y,V.z,1.)) > > > Are you in fact saying that your suggested solution avoids multiple > calls to the calculation that determines the value of self.V? He is saying that. self.V calls self.get_V(), and the object it returns is bound to V. Further references to V will use the value that was returned and not the attribute. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From JoeSalmeri at comcast.net Wed Jul 24 19:40:55 2002 From: JoeSalmeri at comcast.net (Joe Salmeri) Date: Wed, 24 Jul 2002 23:40:55 GMT Subject: Python + Win32ALL + ASP = Problems accessing Request/Response/Session/Application objects References: <_ko%8.247434$iB1.13124073@bin4.nnrp.aus1.giganews.com> <3D3E6BCD.4010809@mxm.dk> Message-ID: Hopefully Mark Hammond will see this, I'm sure he will be able to provide the answer (he always does!) "Max M" wrote in message news:3D3E6BCD.4010809 at mxm.dk... > Joe Salmeri wrote: > > > How are the ASP Request/Response/Session/Application objects accessed in a > > module that is imported in an ASP file WITHOUT passing them in as paramaters > > to each of the functions defined in that module? I have attempted to track > > down the creation of those objects but have been unable to trace them to the > > source of their creation. > > > You would probably be better of in the long run if you used a facade to > cover your code in. > > You would then only output finished html from the facade object. > > <% > > class PageFacade: > > def __init__(self, message='blah blah'): > self.message = message > > def blah(self): > return self.message > > def update(self, req): > self.message = req.Form('message') > # 'insert message into theTable ' > > f = PageFacade() > save = Request.Form('save') > if save: > f.update(Request) > > %> > > > here is some code that reads <%= f.blah()%> > > > This has a lot of advantages. Especially if you are writing database > driven websites. > > regards Max M > From skip at pobox.com Thu Jul 25 11:48:34 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 25 Jul 2002 10:48:34 -0500 Subject: Speed up Python by up to 5% ? In-Reply-To: References: Message-ID: <15680.7634.425684.630761@12-248-11-90.client.attbi.com> Edward> In short, this is a very tight loop. But can't it be improved? Edward> The byte code is littered with SET_LINENO opcodes. Has anyone Edward> considered moving the test: Edward> if (things_to_do || --tstate->ticker < 0) Edward> { /* handle periodic things */ } // not usually executed. Edward> out of the main loop an into the case for SET_LINENO? This wouldn't work if the byte code being executed was generated by a "python -O" session. In this situation, there are no SET_LINENO instructions at all. Edward> Are typical opcodes much more expensive than the simplest Edward> SET_LINENO case? I wrote a simple program based on dis to count Edward> the static occurrences of bytecodes. The results of running Edward> this program on most of the modules of Leo are as follows: ... You might try defining the DYNAMIC_EXECUTION_PROFILE and DXPAIRS macros then recompiling the interpreter (I think only the sys module and ceval.c need to be recompiled). When you run the interpreter you can call sys.getdxp() to get the dynamic opcode frequencies. If you've defined both macros, you'll get dynamic opcode pair info. Without DXPAIRS you'll get just the straight frequencies. About a year ago I wrote an XML-RPC server to which people could post opcode frequency info (and retrieve it by version), but nobody bit on the idea. Here's the entire client-side code necessary to register this info: def rle(l): import types newl = [] lastel = None count = 0 for elt in l: if elt == lastel: count = count + 1 continue elif lastel is not None: if isinstance(lastel, types.ListType): lastel = rle(lastel) newl.append([lastel, count]) lastel = elt count = 1 if isinstance(lastel, types.ListType): lastel = rle(lastel) newl.append([lastel, count]) return newl def send_instruction_counts(appname, email): if not hasattr(sys, "getdxp"): return dxpserver = xmlrpclib.ServerProxy("http://manatee.mojam.com:7304", encoding="utf-8") dxpserver.add_dx_info(appname, email, sys.version_info[:3], rle(sys.getdxp())) atexit.register(send_instruction_counts, "musi-cal", "skip at pobox.com") I would probably do the data compression a bit differently today (pickle the rle() output, then gzip it for transport). -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From lac at strakt.com Fri Jul 5 01:46:34 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 05 Jul 2002 07:46:34 +0200 Subject: [OT] What is Open Source? (fwd) In-Reply-To: Message from Paul Rubin of "04 Jul 2002 18:28:42 PDT." <7xwusbyncl.fsf@ruckus.brouhaha.com> References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> <7xwusbyncl.fsf@ruckus.brouhaha.com> Message-ID: <200207050546.g655kYLM015752@ratthing-b246.strakt.com> > mertz at gnosis.cx (David Mertz, Ph.D.) writes: > > |I think Clark was using contract in a metaphorical sense, describing a > > |deal made with authors on one side, and society as a whole on the > > |other. In what's called the "copyright bargain", society agrees to > > |grant limited temporary monopolies, in exchange for increased > > |"progress in science and the useful arts". > > > > Well... I suppose Clark's use is a metaphor. But it is an extremely > > *bad* metaphor, one that does far more to conceal what's going on than > > reveal. > > Is it a worse metaphor than "the copyright bargain"? That phrase has > been around for decades or centuries and is generally considered apt. > > > The problem with Clark's metaphor is that it very strongly insinuates > > something exactly opposite to the true legal/ethical structure. By > > pretending that you "contract" for "intellectual property", you create > > the illusion that IP is something inherently in your possession. I can > > actually hold my bushel of corn, and as long as I hold it someone else > > can't. By pretending IP has the same nature, one falsely > > naturalizes--us Lukacsian's say "reify"--the "thing" that one "has." > > I have a worse problem with "IP" than with "copyright bargain". The > copyright bargain is one that society (through its elected legislature) > supposedly made with authors. The current problem is that the legislature > acted in the interests of lobbyists rather than the electorate. > -- > http://mail.python.org/mailman/listinfo/python-list Actually, this current bargain is one that society made with the Publishers, not with the Authors. From an author's point of view, supplying content to multiple publishers simulataneously would be no problem as long as the author got paid for each copy -- and highly desirable in some cases, where your publisher won't promote your book aggressively, and you believe that you could get more work out of a different publisher. There is protection for the author from having a thief claim your work as his or her own, but that is not the same thing. The Publishers claim that they need the monopoly profits, because they need the rents to support investing in Authors at all. Should we believe them? Laura Creighton From Neruocomp at yahoo.com Fri Jul 12 16:26:39 2002 From: Neruocomp at yahoo.com (David Noriega) Date: Fri, 12 Jul 2002 20:26:39 GMT Subject: Executing outside command Message-ID: <3YGX8.82020$eF5.2553773@twister.austin.rr.com> How would I have python execute a command like ogg123? David M Noriega From cce at clarkevans.com Wed Jul 3 13:35:10 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Wed, 3 Jul 2002 13:35:10 -0400 Subject: tzset() Message-ID: <20020703133510.A22032@doublegemini.com> On Thu, 16 Jun 1994 at 13:01:14 +0200 Guido van Rossum wrote: | The most pragmatic way to solve this is probably to add a function | tzset("string") to the time module which forces TZ="string" in the | process's current environment and then calls the C tzset() again (and | reinitializes the Python variables that describe the timezone). | This is a great idea; was it ever done? Best, Clark From vonWedel at lfpt.rwth-aachen.de Tue Jul 23 05:27:25 2002 From: vonWedel at lfpt.rwth-aachen.de (Lars von Wedel) Date: Tue, 23 Jul 2002 11:27:25 +0200 Subject: SMTP for SOAP in Python Message-ID: <3D3D217D.A5572039@lfpt.rwth-aachen.de> Hi folks, I saw a couple of libraries to support SOAP c/s in Python. However, all of them rely on HTTP as a transfer protocol as far as I have seen. Are there any libs using SMTP? Doing my own implementation of SMTP transport, which would be the best choice of SOAP library in terms of matureness and extensibility? >From SOAPpy in the pywebsvcs module it seems, that the biggest part is the data type handling, whereas the actual data transport is a fairly small piece of the overall code. Thus, an SMTP extension should be easy or am I overlooking some details? Lars -------------- next part -------------- A non-text attachment was scrubbed... Name: vonWedel.vcf Type: text/x-vcard Size: 323 bytes Desc: Card for Lars von Wedel URL: From robert_kuzelj at yahoo.com Sun Jul 7 11:47:44 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 7 Jul 2002 08:47:44 -0700 Subject: class/instance context [was: "my brain hurts" or is isinstance broken?] Message-ID: hi, it seems i made my self not very clear. i'll try it once again. first i'll do some rehasing so that you are not bothered with it. ;-) - classes are objects - i know that! - so are metaclasses - i know that! - instances cant be destingiushed from classes - at least not explictily - i know that! - i dont like that! - there is a workaround for that - i can live with that workaround! - i dont like it! ok? concerning the simplistic factory-example: - it can besolved by a different design - know that! - there are at least len(thread_messages) + 1 solutions to this particular problem. - we dont need to go thru all of them ;-) the whole point of this discussion (at the moment) is that the question if something is a class or an instance is depending on the context. so one more rehashing for the context of defining the overall pythonsystem - every class is an object - i know that - i like that - it makes modifiying this system very easy - i am playing around with that at the moment - i realy realy love it. for every other system this premise might (and i am purposefully saying _might_) not hold true. i think it only makes sense to further discuss this issue if you are able and willing to subscribe to the point that context is very very important. let me explain why i think that python 2.2 has a bug (even so i'll admit it's a minor one - as there exists a workaround). sometime ago i had to write a generator for generating java-sources out of an uml-model from a modelling-tool. that was togetherj which is written completely in java. usually in such tools if they are scriptable you have such objects like an UMLModel, UMLPackage, UMLClass, UMLINterface UMLRelation and so on. some of those tools realy have the whole UMLMetamodel within them accessible for scripting. usually when accessing modelinformation you write this kind of code (for e.g in rational rose) meths = System.getModel().getPackage("foo").getClass("Bar").getMethods() for m in meths: generateClassMethod(m) in togetherj this explicit typeinformation wasnt available. one had a space full of generic elements at hand and the code ended looking like that elems = System.getElements() for model in elems: if model.getType(UMLType.MODEL): packages = model.getElements() for pack in packages: if pack.getType(UMLType.PACKAGE): classes = pack.getElements() for cls in classes: if cls.getType(UMLType.CLASS): methods = cls.getElements() for meth in methods: if meth.getType(UMLType.METHOD): getenerateClassMethod(meth) upon encoutering this model i realy went nuts at first. i thought these togetherguys must have been druged when doing this. after diving further into their system it became obvious what these guys did. because of the generic behaviour of there core-object (Element) it was very easily for them to add a new UML-concept and have it displayed either as a graphical icon (box or whatsoever) or as a propertywindow. somethin like the following was all they needed to do to make an Java-Interface editable. class InterfacePropertyWindow(BasePropertyWindow): def __init__(self, element): ... def getType(self): return UMLType.INTERFACE (made of course in java ;-) ) so from their point of view this was really cool and necessary. from my context it was a load of sh*t. i had to write an awfull lot of delagationcode that implemented a decent interface to the uml-model. i guess the same applies to python 2.2. for the purpose of implementing metaclasses and having access to the metalayer there is no need to destiguish between classes and instances. for all the other people this might not necessarely be true. even if you personally think it is a bad design to have a typecheck - i personally think this heavily bound to the context. so i hope it might have become clear why i do think that the absence of the possibility to know about a classinstance is a bug. ciao robertj From tdelaney at avaya.com Tue Jul 23 01:26:33 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 23 Jul 2002 15:26:33 +1000 Subject: distutils cygwin bdist_wininst Message-ID: > From: Michiel Jan Laurens de Hoon [mailto:mdehoon at ims.u-tokyo.ac.jp] > > > c:\\python22\\python setup.py --compiler=mingw32 > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: option --compiler not recognized > > > $ python setup.py --compiler=mingw32 > > $ python setup.py bdist_wininst That should be python setup.py build --compiler-mingw32 Tim Delaney From jocdeveloper at hotmail.com Wed Jul 31 23:58:08 2002 From: jocdeveloper at hotmail.com (joc) Date: Thu, 1 Aug 2002 04:58:08 +0100 Subject: wxPython and Py2exe probs References: Message-ID: I found my answers and thought I would post them for anyone else who gets in the same mess. Solving problem 2 actually helped me solve problem 1 ;) 2. to be able to write to standard out (the command line) I wrote the following code ## ----------- # NDPrint.py import sys def ndprint( *stuff ): for s in stuff: sys.__stdout__.write(str(s)+' ') sys.__stdout__.write('\n') if __name__ == '__main__': ndprint(1,2,'\thelp', 'me') ## ------------ and changed all my print statements to ndprint (you need to use brackets () as well) after importing NDPrint.py sys.__stdout__ holds the file pointer to standard out which I assume wxPython grabs for sending output to a window. 1. I then wrapped a try/except around the call to wxPythons app.MainLoop() which printed the traceback using my ndprint() above. The reason my app was quitting immediately now became apparent and was a problem with shelve not finding a dbm module. I added --includes=dbhash to the command line calling of py2exe and everything works swimmingly. Don't you love it when there's a happy ending? Joc "joc" wrote in message news:ai6815$b5d$1 at news5.svr.pol.co.uk... > I have 2 questions regarding wxPython and Py2exe > > 1. When I try to compile a python script with Py2exe I get the following > warnings:- > > The following modules were not found: ( I have bunched them to be easier > to read) > > cmndlgsc, imagec, clip_dndc, windows3c, filesysc, eventsc, windows2c, > controlsc, misc2c, controls2c, os.path, stattoolc, windowsc, mdic, gdic, > sizersc, printfwc, streamsc, framesc, miscc > > The exe file runs OK but another script where I try the same just quits out. > Both > scripts run fine with python. (the other script generates more warnings > because it > is a lot bigger). > > Is my version of python (2.2 on win XP) not set up correctly? > I have tried using 'python setup.py py2exe --includes imagec' but that > didn't > help as py2exe complains that there is no module named that. > > 2. I cannot read the error messages because wxPython redirects them to a > window, which shuts before I can read any output if the program quits. > Is there a way to get wxWindows to stop this behaviour and to have my print > statements and error messages output to standard out? > > TIA > > Joc > > From opengeometry at NOSPAM.yahoo.ca Mon Jul 15 16:25:51 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 15 Jul 2002 20:25:51 GMT Subject: Radians vs. Degrees References: <3D33016C.8030804@cox.net> Message-ID: Jef wrote: > Hi All, > > I'm new to this NG so please bear with me :-) I'm writing an addon > for the Quake2 editor named QuArK and could use some advice from the > math/coding gurus out there. > > My problem is that I'm trying to create a torus (donut) and the C > code I'm looking at uses DTOR to convert degrees to radians and I see no > mention of it (DTOR) in Python. My question is whether I need this in > Python Yes, everything is in radian. > or does Python automatically convert to radians during calculations? No, you have to do that yourself... rad/pi = deg/180 > Also, do the FOR loops work the same as in C++ (e.g. FOR(x=0, x<360, > x++))? If not, any suggestions on how to do this? In Python, it would go like for i in range(360): ... -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From mgilfix at eecs.tufts.edu Fri Jul 26 10:53:52 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 26 Jul 2002 10:53:52 -0400 Subject: Which gui for slow (133 Mhz) pc In-Reply-To: <3d42636b.4941993@news.utanet.at>; from scrutinizer@gmx.at on Thu, Jul 25, 2002 at 08:54:43PM +0000 References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> <3d42f3dc.5866543@news.utanet.at> <3d42636b.4941993@news.utanet.at> Message-ID: <20020726105352.A2854@eecs.tufts.edu> On Thu, Jul 25 @ 20:54, Francesco S. wrote: > > GUI stuff always comes down to your needs really. But pretty much > >all the toolkits out there can accomplish the same thing, and at > >roughly the same speed (which is pretty decent to being with) for most > >applications. > > I don't want to write "applications" now, at first I want to learn and > maybe write some tiny utilities for myself and play around. Ah, k. The nice thing about GUI toolkits though is that once you've learned one, making a switch to another is relatively easy. You tend to know what to look for and what to expect from widgets and the only major difference is usually found in the layout algorithms... > Hm, again, the three alternatives: > Porbable is not the question now. > > Please correct me, if I'm wrong. > > 1) Tkinter: It is in startup time pretty good, and well documented , > stable and straightforward. Sure. But if I were just playing around to learn GUIs, I personally wouldn't opt for Tkinter. The GUI set isn't rich enough (although there are extensions you can get to obtain richer widgets - I forget where). > 2) wxPython is fast (after starting) and has many sophisticated > widgets. Yep. I don't find the startup time that painful on my PII 400.. > 3) PyQt: It is "professional" and powerful and is praised from the > most people here in this newsgroup. Agreed. PyQt is the base GUI toolkit that's used in KDE. If you've had some experience with different window managers, I suggest just deciding whether you like the look of KDE or GNOME better. If you like KDE, use PyQT, otherwise use GTK which is also a well developed toolkit. -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From brueckd at tbye.com Tue Jul 9 16:43:41 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 9 Jul 2002 13:43:41 -0700 (PDT) Subject: Why self? In-Reply-To: <090720021439257166%pecora@anvil.nrl.navy.mil> Message-ID: On Tue, 9 Jul 2002, Louis M. Pecora wrote: > Yeah, I may be one of those complainers. I have tried to learn the > language well and really like it, but for some reason this self. thing > really bugs me. (I _am_ seeing a therapist :-) ). I write a lot of > scientifc code and I just think > > > self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) > > is a LOT uglier than > > y= x**2 * t/z + a * FFT(tseries) s = self s.y = s.x**2 * s.t/s.z + s.a * FFT(s.tseries) From wolfson at midway.uchicago.edu Fri Jul 26 13:57:02 2002 From: wolfson at midway.uchicago.edu (Ben Wolfson) Date: Fri, 26 Jul 2002 17:57:02 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <16Q%8.116512$Jj7.2728704@news1.tin.it> Message-ID: On Thu, 25 Jul 2002 12:00:33 GMT, Alex Martelli wrote: >AND because the "you" is actually redundant if I understand >"slang grammar" correctly (isn't the great song's title just >"Ain't Misbehavin'" without any pronoun?-). But that's by the >by. "Ain't" can be used with any subject in incorrect English, actually. I don't know "Ain't Misbehavin'", but the subject of the song "Ain't Superstitious" is "I", frex. That does mean, though, that if you just say "ain't" without a subject, it will probably be understood to be "whatever it is we're talking about right now ain't _____". -- BTR You're going to set me up as a kind of slovenly attached pig that Jack Kornfeld can slice down in his violent zen compassion? -- Larry Block From dstuart at orsys.com Wed Jul 31 09:51:38 2002 From: dstuart at orsys.com (Doug Stuart) Date: Wed, 31 Jul 2002 08:51:38 -0500 Subject: pyexpat error Message-ID: <3D47EB6A.344FE6FE@orsys.com> **** Post for FREE via your newsreader at post.usenet.com **** "Martin v. Loewis" wrote: > Doug Stuart writes: > > > I am attempting to compile python with the Expat library included. > I am > > running Solaris 7 and python 2.2.1. Originally, I did the > > 'configure-make dance' for python, then was told that I needed to > add > > the Expat library. I did the 'configure-make dance' for Expat > (version > > 1.95.4). I then went to redo my python doing a configure, make > clean > > and make. During the build of the pyexpat extension I get an > warning > > from line 1518 of Modules/pyexpat.c saying that subscript has type > > char. It then removes the library because 'an error occurred." In > the > > setup.py script there is a setting for the EXPAT_DIR. I have tried > > setting that to the directory where the Expat source files are > located > > and to the location of the library the Expat install creates. > > > > What am I missing here? > > Precise bug reporting. When it said 'an error occurred' - what > precisely did it say? > > Could it be the case that you have compiled Expat as a shared library, > > and that your operating system won't find that shared library because > the shared library is in /usr/local/lib? In that case, you need to set > > LD_LIBRARY_PATH, or apply one of the other 4 strategies to make > Solaris find shared libraries. > > Regards, > Martin I'm sorry but I am new to this sort of thing....here is the text of the "error"... building 'pyexpat' extension /orion/pkg/Python-2.2.1/Modules/pyexpat.c: In function `get_version_string': /orion/pkg/Python-2.2.1/Modules/pyexpat.c:1518: warning: subscript has type `char' gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DHAVE_EXPAT_H=1 -I. -I/orion/pkg/Python-2.2.1/./Include -I/usr/local/include -IInclude/ -c /orion/pkg/Pytho n-2.2.1/Modules/pyexpat.c -o build/temp.solaris-2.7-sun4u-2.2/pyexpat.o gcc -shared build/temp.solaris-2.7-sun4u-2.2/pyexpat.o -L/usr/local/lib -lexpat -o build/lib.solaris-2.7-sun4u-2.2/pyexpat.so WARNING: removing "pyexpat" since importing it failed Where would I set the LD_LIBRARY_PATH? In my environment, the Setup script or where? And what are the 'other 4 strategies"? If you could point me in the right direction it would be most appreciated. TIA Doug -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From roffe at aqualene.uio.no Sat Jul 20 04:53:11 2002 From: roffe at aqualene.uio.no (Rolf Marvin Bøe Lindgren) Date: Sat, 20 Jul 2002 10:53:11 +0200 Subject: [Q] wxPython - layout & placement References: Message-ID: [Steve Menard] | One easy solution is to us a wxPanel to do you layout, then put that | panel in the wxDialog. It should not be too hard to make sure the | wxPanel fill out the entire dialog ... oh, I tried that: dlg = wxDialog(parent,-1,FileName,size=(400,400)) dlgPanel = wxPanel(parent=dlg,-1) wxButton (parent=dlgPanel, id = -1, label = 'This is a button', pos=(10,10)) dlg.ShowModal() this gives an entirely blank dialog. is there anything obviously wrong here? -- Rolf Lindgren http://www.roffe.com/ roffe at tag.uio.no From phr-n2002b at NOSPAMnightsong.com Mon Jul 15 22:18:26 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 15 Jul 2002 19:18:26 -0700 Subject: implementing large trees References: Message-ID: <7xr8i4h0ul.fsf@ruckus.brouhaha.com> How much info do you need to access at each node? If not too much info per node, your best bet is probably figure out a compact in-memory representation for the tree, preferably organized for reasonable paging locality during traversal. Then use the array and/or mmap modules to crunch on the in-memory structure, decoding individual nodes and edges as necessary. With luck, this will fit inside a few hundred megabytes of memory, which is not that large an amount for a workstation these days. From aleax at aleax.it Thu Jul 11 16:28:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 20:28:44 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> Message-ID: <0UlX8.69924$vm5.2553930@news2.tin.it> Martijn Faassen wrote: > Alex Martelli wrote: > [snip long discourse on holy war topic] >> I suspect we'll have (at best) to agree to disagree on the >> specifics of this. > > Yes, this is probably Python's version of the "where do I put the { and > } holy war", as you haven't managed to convince me at all; I prefer > linebreaks after ':' and indentation for blocks, no matter how small they > may be. My eyes do trip over the other variety and leave me with a feeling > of frustration. > > The other Python holy war topic is tabs versus spaces. > > More than one way to do it can lead to holy wars, apparently. :) Fortunately, on the tab vs spaces issue we do have the BDFL's own word in PEP 8 -- the holy war is over, and spaces have won (quite interesting, particularly considering that it shows Guido *can* change his mind on such subjects). Irreducible tab lovers can now go form their heretical underground and plot the Tab Revolution. No such official pronouncement for now on whether linebreak must always come right after a colon (though I suspect I know where the BDFL's sympathies lie on this, he hasn't gotten around to writing them down, AFAIK, and surely not in PEP 8 so far -- good, gives us heretics-to-be more time to prepare _our_ underground network...). Interestingly, both cases can at least in part be framed as "there's more than one way _and you should choose among them advisedly_" vs "there's more than one way _but you should only ever use one of them_". I'm on the "choose advisedly" meta-side when the way the program looks is concerned -- and so is Guido, on some aspects (PEP 8 says to use or not use spaces around some operators "advisedly") but not on others (PEP 8 forbids spaces used for aligning assignments, e.g.). I'm _definitely_ on the "use only one way" where the same looks can be arrived at in separate ways -- where the "one way" is the one that survives the many weird ways different programs (printer drivers, email and news, web browsers ... it's not JUST about editors:-) can choose to mangle tabs. As I said, Guido agrees in PEP 8. Interestingly enough, I find I can live with everything that is mandated in PEP 8 -- some recommendations are not my favorite ones, but there's nothing really major in it that irks me. In several ways I've consciously adapted my Python style to consistently follow PEP 8 when it was otherwise wavering between different usages without any strong preference. It's _very_ different for PEP 7, on C code style, where there _are_ a couple of points that would make me reject a lucrative job offer if part of the conditions was that I had to follow that style for a long time -- and I'd bet that most experienced C'ers find some aspect there on which they feel just as strongly, though quite likely on different subjects and opposite directions from mine...:-). Alex From Bill.Scherer at VerizonWireless.com Thu Jul 11 09:44:29 2002 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Thu, 11 Jul 2002 09:44:29 -0400 (EDT) Subject: struct unpack help? Message-ID: Hello - I'm trying to unpack a struct and I need some help. Here's a sample string of the struct: sampleStructString = "_782c1a08_p_void" I know that the struct defines only two unsigned shorts. That would imply (to me, anyway) a format of 'HH'. But calcsize of that is 4, while my string is 16 bytes. So struct.unpack('HH', sampleStructString) results in: struct.error: unpack str size does not match format I believe that the first of the two shorts in the sample struct string has a decimal value of 1. TIA, Bill -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From merkosh at hadiko.de Tue Jul 16 15:46:40 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Tue, 16 Jul 2002 12:46:40 -0700 Subject: problem with references Message-ID: Hi, I've got some object "Sequence" which takes one element and repeatedly appends copyies of this element into a queue. Now, each element "has a condition" (f.e. self.value < 10). Idea is to read in a file (something like someSequence.parse() ). Sequence will propagate this call to all sub-elements. Sequence will continue to create sub-elements and instantly parse this sub-element (with something like element.parse()) until the first sub- element raises an ParseError. Sequence will then test wether the number of elements in the queue is within a predefined range, otherwise it will raise a ParseError, too. The above was necessary for you to understand what I'm doing. After a debugging session with pdb I found out that the following line creates the problem: !>> cpy = copy.deepcopy(self.element) try: cpy.parse(f) except ParseError: #reached maximum hits .... else: if (): self.value.append(cpy) ... This is a code fragment which creates a deep copy of a template object (stored in self.element) and then tries to parse this element. on success the copy is added to the queue (self.value). However, this fails when Sequence goes for a second loop. Then cpy is overwritten with a second copy of the template, which also overwrites the value in the queue (self.value). Why is that so and is there any way of stopping this? :) Thanks for any help! Uwe From aleax at aleax.it Sun Jul 7 07:54:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 11:54:09 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2766B3.1010501@ob_scure.dk> Message-ID: Thomas Jensen wrote: ... > Oh, I thought Zope was "just" a product. It's a product. Not sure what the "just" means here. > Google and Fidelity, nice! (Do you have any links regarding this?) Look at Google's own site, where they list job prospects, to see Python as a prereq for some job positions. About Fidelity, I think you may want to contact ReportLabs -- it's their customer, after all, I only know about it because it was mentioned at Europython recently. >> Point 3 is troublesome if taken literally -- I know of NO language >> claiming 99.999% freedom from defects for its implementations. > > I'm sorry I didn't make myself clear (in Denmark usually 5 nines means > uptime or accesability for web services). Actually I belive we "only" > guarantee 99,99% to our customers :-) That's quite another issue, and mostly related to setting up redundance suitably (no single point of failure). And one in ten thousands IS much more reasonable / achievable than one in a hundred thousands. > I belive the concern was more about Python taking down our servers and > thereby ruining our uptime (we have a load balancing unit, so both > servers had to go down). No reason to think that's any more likely than with any other programming language. We're talking about a language that's been around for over ten years, after all, not a "new kid on the block". > Having used Python quite a bit, I known that wouldn't happen but 2 > people saying it is better than one :-) > > I've worked a lot with MS tools professionally and must say that my view > of MS have gone from bad to worse. Visual Basic is by far the worst, > most clumsy and buggy computer language I've ever used. I've come to > really hate that language. The only "good" thing about it, is that it's > so closely bound to COM, that COM components are really easy to make. > Don't even get me started about the stability of using IIS for SOAP > servers :-( I won't. But -- any opinion on the VB7, aka VBNET, release? On paper it looks better than VB6 (it should -- they made two dozen incompatible changes, each taking it a bit closer to Python:-) but I have no idea about the reliability of the implementation, not having yet had to use it. Alex From edream at tds.net Sun Jul 14 09:00:39 2002 From: edream at tds.net (Edward K. Ream) Date: Sun, 14 Jul 2002 13:00:39 GMT Subject: Making code 2.1 compatible References: Message-ID: <3D3175EF.1565E789@tds.net> > The only way to support interoperability is to actually test it. You need a > copy of python 2.1 SOMEWHERE. Another machine, your friend, a client, somebody. > > I must be spoiled by Debian making this easy (-: I have 1.5.2, 2.1, and 2.2 > installed. I agree. I was asking for something that isn't really very useful. Thanks for this comment. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From daniel.dittmar at sap.com Mon Jul 1 12:37:51 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 1 Jul 2002 18:37:51 +0200 Subject: Python language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> Message-ID: >> It seems to me that C.l.py is too overloaded today. >> Wouldn't it be nice if someone(not me - I think I don't have >> resources for it) bothered to setup a wiki for discussion about >> python language? Two topics which would benefit from having a Wiki (because the information is constantly changing): - GUI programming and toolkits - Web programming I'm thinking along the lines of - comparisons - cookbook/snippets - initial meeting ground for new projects There are some brave souls trying to summarize this on web pages, but a Wiki makes it possible to distribute the work. I don't know whether it would be better to have one large Python Wiki or to have topics such as these split into seperate Wikis. I'm sure there are other topics as well - how can I implement this PEP in current Python - functional/logical/whatever programming in Python - autocoding (just joking - too late, I made the kill file) Daniel From news at bobs.org Thu Jul 4 16:18:41 2002 From: news at bobs.org (Bob Arnson) Date: Thu, 04 Jul 2002 20:18:41 GMT Subject: PythonWin + other GUIs = CRASH! References: <3D232FEE.3010606@gmx.de> Message-ID: "Alistair Campbell" wrote in message news:xeWU8.606$P%4.24491 at ozemail.com.au... > Has anyone tried Komodo, the ActiveState IDE, with this? I haven't but I I have, and though it doesn't crash, it doesn't work -- it just hangs. (I was using the latest Komodo, v.1.2.8RC2, with Python 2.2.1 and wxPython 2.3.2.1.) The HAP Debugger works fine, however; http://hapdebugger.sourceforge.net/. -- sig://boB http://IntellectualFrottage.com From mcfletch at rogers.com Sun Jul 7 16:35:08 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 07 Jul 2002 16:35:08 -0400 Subject: Fatal Python error: PyThreadState_Get: no current thread with extension module Message-ID: <3D28A5FC.7080302@rogers.com> I'm trying to compile a new extension module (based on mx.TextTools), and I'm discovering that the programme gets a Fatal Python error after completing a test suite (likely during cleanup of the various modules). I'm trying to figure out what the error really means, and in which crack I should put my finger to stop the dike from bursting. Is there a guide/guidelines/helpful-elf-who-sneaks-into-the-shop-at-night for debugging this kind of error anywhere? S:\sp\simpleparse\tests>mx_flag.py ...... ---------------------------------------------------------------------- Ran 6 tests in 0.000s OK Fatal Python error: PyThreadState_Get: no current thread abnormal program termination Help appreciated, Mike _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From roy at panix.com Sun Jul 7 21:53:43 2002 From: roy at panix.com (Roy Smith) Date: Sun, 07 Jul 2002 21:53:43 -0400 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> Message-ID: OK, now I'm stumped. I've got the following in rulexParser_unit.py: ==================================== import sys import unittest from types import * sys.path.insert (1, '..') import rulexParser class parserTestCase (unittest.TestCase): def setUp (self): self.parser = rulexParser.rulexParser() class dictionaryEntries (parserTestCase): def runTest (self): tables = self.parser.parse ('data/rulex.envmon') self.assertEqual (type (tables), DictType) self.assertEqual (1, 0) for table in tables: print type(table) self.assertEqual (type (table), DictType) if __name__ == "__main__": dictionaryEntries().run() ==================================== parser.parse() is supposed to (and does) return a dictionary of dictionaries. The line "for table in tables:" should read "for table in tables.keys():". As written, it should raise a TypeError. In the process of trying to figure out why it wasn't, I added the "print type(table)" line, and it doesn't print anything. Then I added the "assertEqual (1, 0)", and it still does nothing. Obviously, I'm doing something wrong. I suspect something has wrapped my methon in a try block that catches all these exceptions, but then doesn't do anything with them. From pinard at iro.umontreal.ca Mon Jul 8 08:26:56 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 08:26:56 -0400 Subject: join [was: Re: converting an array of chars to a string] In-Reply-To: References: <3d12dda2_6@news.newsgroups.com> <3D12E228.6030501@wedgetail.com> <3D1307AF.3070308@wedgetail.com> Message-ID: [Duncan Booth] > Writing ''.join(list) still sucks though. JOINER.join(LIST) has some technical advantages, which are much bolded by its proponents. Despite theses advantages, it just remains plain ugly. Proponents say that we will get used to it, and learn to love it, after a few days or a few years, depending on how rooted are one's aesthetics. In a way, this is quite similar to smoking habits: you get sick the first times, and you eventually learn to much like it, if you are persistent enough. I now use this construct all the time, and even guess I'm going to like it one day. Yet I hope I will always remember that I'm lying to myself :-). -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From spam at ob_scure.dk Sat Jul 6 17:52:51 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sat, 06 Jul 2002 23:52:51 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: <3D2766B3.1010501@ob_scure.dk> Alex Martelli wrote: > Thomas Jensen wrote: [snip] > Come visit www.python-in-business.org -- we founded the Python > Business Forum, a non-profit alliance of firms which do use Python > "for key functions", and one of the PBF's primary purposes is to > help reassure CEO's (and CTO's &c, for larger companies:-) about > just such issues as these. Appriciate the link. I'll keep it for later use, should we go for Python. > Point 1 is basically never a problem because Python is to easy > to pick up (and somebody else's Python code is easier to maintain > than for any other language), but the PBF aims to help, in the > long run, by establishing a network and referral point for > Python trainers and consultants. Sounds interresting. > Point 2 is easy -- Zope Corporation relies on Python so much it > pays to employ the Python core team, Google uses Python enough to > demand Python skill in some of its job offers, Fidelity (a huge > financial trust in Britain) is dependent on Python (tbe basis of > all of ReportLab's excellent products) for all of its reports-as- > PDF web sales strategy -- that's three. We can no doubt find > more, but three is what your boss asked for. Oh, I thought Zope was "just" a product. Google and Fidelity, nice! (Do you have any links regarding this?) > Point 3 is troublesome if taken literally -- I know of NO language > claiming 99.999% freedom from defects for its implementations. I'm sorry I didn't make myself clear (in Denmark usually 5 nines means uptime or accesability for web services). Actually I belive we "only" guarantee 99,99% to our customers :-) > The standard Python distribution is certainly far less buggy than, > e.g., most Microsoft language products I've ever used -- on which > many corporations, wisely or otherwise, rely for their business -- > but that's still a FAR sight from 1-part-in-100,000-or-lower > defect rates. One of PBF's plans, named "Python in a Tie", is > a very stable Python distribution, due to be blessed by Guido but > tested very intensely by the PBF. But the targets, though not > quantified so far, are NOT as ambitious as 99.999%. If you're > planning deployment in life-critical applications (the only > reason I can see for such strict, enormously expensive demands) > I think, regretfully, that you'll have to look elsewhere (I'll > be curious to hear about what software tools you find that claim > those reliability levels, at least if they back it up with real > hard-cash reliability insurance -- words are cheap). I wholeheartedly agree. I belive the concern was more about Python taking down our servers and thereby ruining our uptime (we have a load balancing unit, so both servers had to go down). Having used Python quite a bit, I known that wouldn't happen but 2 people saying it is better than one :-) I've worked a lot with MS tools professionally and must say that my view of MS have gone from bad to worse. Visual Basic is by far the worst, most clumsy and buggy computer language I've ever used. I've come to really hate that language. The only "good" thing about it, is that it's so closely bound to COM, that COM components are really easy to make. Don't even get me started about the stability of using IIS for SOAP servers :-( -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From mwh at python.net Tue Jul 9 08:59:53 2002 From: mwh at python.net (Michael Hudson) Date: 09 Jul 2002 13:59:53 +0100 Subject: [snake-farm] Broken build system as of 2002-06-04 In-Reply-To: Anders Qvist's message of "Tue, 9 Jul 2002 10:17:16 +0200" References: <20020709081716.GT20301@lysator.liu.se> Message-ID: <2mznx112gm.fsf@starship.python.net> Anders Qvist writes: > The snake-farm has been choking on the python CVS source since > 2002-06-04, like thus (on _all_ platforms): I've noticed :) > The problem occurs only when building the python source in a separate > build dir. Eg: > > cd build > ../pythonb/dist/src/config You mean .../configure, right? > make all > > It seems to me that sysconfig.py is unaware that building may occur in > a separate directory. Well, it's more than that, because I build like this all the time and don't get the failures. Are the scripts the snake-farm uses viewable anywhere? Cheers, M. From slhath at charter.net Tue Jul 30 23:54:09 2002 From: slhath at charter.net (Scott Hathaway) Date: Tue, 30 Jul 2002 22:54:09 -0500 Subject: conditional importing References: <0ad19.92805$724.68398@atlpnn01.usenetserver.com> Message-ID: Thanks to both of you guys for your advice. I will release the class when it is done. Whether it will be useful to anyone but me remains to be seen. :) Scott "Steve Holden" wrote in message news:0ad19.92805$724.68398 at atlpnn01.usenetserver.com... > "Gerhard H?ring" wrote in message > news:mailman.1027907323.21253.python-list at python.org... > > * Scott Hathaway [2002-07-28 20:29 -0500]: > > > How can I do a conditional import? I am creating a database wrapper > class > > > that is similar to adodb in PHP. > > > I have the following class: > > > > > > >from mx.ODBC import Windows as db1 > > > import MySQLdb as db2 > > > > Better use something like: > > > > module_name = "MySQLdb" > > try: > > dbmodule = __import__(module_name) > > except ImportError, reason: > > # error handling here > > > > def open_connection(*args, **kwargs): > > return dbmodule.connect(*args, **kwargs) > > > > Unfortunately, the arguments for the connect method aren't standardized. > > But at least some modules allow for a single connection string where the > > arguments (host, user, passwd, ...) are separated by colons. > > > > My preferred technique (when all modules obey the DB API sufficiently for my > needs) is: > > if dbtype == 'odbc': > import mx.ODBC.Windows as db > else: > import MySQLdb as db > > conn = db.open(...) > > The real problem at present appears to be the various different modules' > insistence on using different paramstyles - in the case above, mxODBC > expects a "?" for a parameter substitution, while MySQLdb expects a "%s". > > something-i-need-to-work-on-ly y'rs - steve > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > ----------------------------------------------------------------------- > > > > > From mwh at python.net Tue Jul 23 11:41:15 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 23 Jul 2002 15:41:15 GMT Subject: passing a tuple of floats to C++ References: <3D3D761B.7925CC36@mill.co.uk> Message-ID: Joe Connellan writes: > How would I go about passing a tuple of floats of an arbitrary (but > large) size to C++ - would I use PyArg_ParseTuple()? I wouldn't. What's wrong with PyTuple_GetItem? Cheers, M. -- ARTHUR: Don't ask me how it works or I'll start to whimper. -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From joec at mill.co.uk Tue Jul 23 11:28:27 2002 From: joec at mill.co.uk (Joe Connellan) Date: Tue, 23 Jul 2002 16:28:27 +0100 Subject: passing a tuple of floats to C++ Message-ID: <3D3D761B.7925CC36@mill.co.uk> How would I go about passing a tuple of floats of an arbitrary (but large) size to C++ - would I use PyArg_ParseTuple()? From mwh at python.net Fri Jul 26 10:02:06 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 14:02:06 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: Alex Martelli writes: > Michael Hudson wrote: > ... > >> Bingo. I had much the same approach for the first 20 years > >> or so of my programming career, > > > > Then I'm ahead of you by ... erm ... 13 years. Wow, I've been > > programming (admittedly only as a hobbyist) for nearly a third of my > > life. That's scary somehow. > > Yes, the thought of a 99+ yo person who's been programming > for almost 33+ years is indeed pretty scary. > > OTOH, if you were _behind_ me by 13 years, I meant that I learnt something in 13 less years than it took you. Of course having oldies like you to point out these facts probably helped me pick them up... . > rather than ahead, then programming for 7 years out of 21 wouldn't > be (scary). Well, I'm counting from 16 as that's when I bought CodeWarrior for the Mac and learnt a "real" programming language (C++). If I counted from my first program in BASIC, that would be ... erm ... from 10 or so, so well over half my life... > (BTW, I've been programming for over _25_ years now -- more than > half of my life...). Of course, I've only been a paid programmer for ~six months, only a fourty-seventh or so of my life. Somehow that doesn't seem so significant :) Cheers, M. -- Any form of evilness that can be detected without *too* much effort is worth it... I have no idea what kind of evil we're looking for here or how to detect is, so I can't answer yes or no. -- Guido Van Rossum, python-dev From anton.wilson at camotion.com Mon Jul 29 19:20:11 2002 From: anton.wilson at camotion.com (anton wilson) Date: Mon, 29 Jul 2002 19:20:11 -0400 Subject: global interpreter lock not working as it should Message-ID: <200207292319.TAA20259@test-area.com> I'm running linux 2.4.18 and 2.4.19 with Python 2.2 and the linuxthreads library. I'm having a problem where the interpreter in ceval.c does not let threads run concurently. Any thread that holds the lock never gives up the lock until it has run to completion. In addition to my program printouts I've tested and found that as long as a thread needs to run, it will always reaquire the GIL immediately after releasing it every 10 byte codes! Of course, if a thread never blocks on the GIL, no other thread will ever run. And this is what is happening. However, this problem is solved by placing a explicit sched_yield between the calls to release the lock and to acquire the lock again in the interpreter loop. Then, switching works perfectly. What is the problem here? Any thoughts would be appreciated. Anton From jonathan at onegoodidea.com Thu Jul 4 12:28:28 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 17:28:28 +0100 Subject: replacing instance __setattr__ References: Message-ID: On 4/7/2002 12:42, in article K3QTagAQSDJ9Ew27 at jessikat.demon.co.uk, "Robin Becker" wrote: > special methods aside I find in 'Unifying types and classes in Python > 2.2' http://www.python.org/2.2/descrintro.html#mro > that the object is always searched last for methods which seems a bit > daft and obviously different for non-method attributes. > > Maybe that's not true of the 2.2.1 interpreter. I get: >>> class foo: ... def hello( self ): ... print 'foo!' ... >>> f = foo() >>> f.hello() foo! >>> >>> def bar_hello( self ): ... print 'bar!' ... >>> f.hello = new.instancemethod( bar_hello, f, foo ) >>> f.hello() bar! >>> As far as I am aware this has always been the case. I think you may have misread that document. The section you reference refers to the method resolution order, which is used in searching the base classes after consulting the instance dict. In new style classes, the 'object' type is generally the last type in the MRO, perhaps that's what you're thinking of? > I had always imagined that the object dict was used before anything else > in all cases. We seem to have a lot of special cases for the unwary to > find punji sticks in. There's only one special case that I know of and that's the special attribute methods, which are different for the reason I posted before: they *are* the mechanism that implements the lookup order. Jonathan From ben_altman at deadspam.com Tue Jul 9 09:06:00 2002 From: ben_altman at deadspam.com (Ben Altman) Date: Tue, 9 Jul 2002 09:06:00 -0400 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <080720021458067296%pecora@anvil.nrl.navy.mil> <080720021645110243%pecora@anvil.nrl.navy.mil> Message-ID: "Lou Pecora" wrote in message news:080720021645110243%pecora at anvil.nrl.navy.mil... > In article , Roy Smith > wrote: > > > Saves typing, yes, but makes your code harder to understand by > > somebody else who has to read and maintain it later. > > True, to some extent, although nobody will have to maintain my code. > It's strictly specialized to my work and will not be used for > production of anything. > > But that is a concern, you're right. Not if it is understood to be the convention especially if it clearly documented. Then when you see '_' you strat thinking 'self' all the time. Ben From bobx at linuxmail.org Fri Jul 12 18:30:23 2002 From: bobx at linuxmail.org (Bob X) Date: Fri, 12 Jul 2002 22:30:23 GMT Subject: Guido van Rossum Tutorial - .PDF or other format? References: Message-ID: <3D2F58A7.4080304@linuxmail.org> David Wright wrote: > Greetings > > Could someone please advise if this suberb document is available on the Web > in a printer friendly format, such as .pdf or even .doc. (other than the > hypetext version on line and on my PC). Yes, I'd like the *address* too ;-) > > Many thanks in advance > David Wright > ~~~~~~~~~~~~~~~~~~~~~~~~~~ > Education is not the filling of a vessel, > but the kindling of a flame." - Socrates > ~~~~~~~~~~~~~~~~~~~~~~~~~~ The PDF version *used* to have problems printing with Acrobat Reader. Don't know if that is fixed yet. From vlindberg at verio.net Wed Jul 3 16:36:43 2002 From: vlindberg at verio.net (VanL) Date: Wed, 03 Jul 2002 14:36:43 -0600 Subject: Help! Script FrontPage via COM with python? Message-ID: <3D23605B.9080108@verio.net> Hello, Does anybody have experience scripting Microsoft FrontPage via COM? Ideally, I would like to be able to automate publishing of a large number of sites using the win32all extensions. Failing that, does anybody have any experience *at all* scripting frontpage (with any language)? Thanks, VanL From max at alcyone.com Mon Jul 8 22:02:44 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Jul 2002 19:02:44 -0700 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> Message-ID: <3D2A4444.82F1D42C@alcyone.com> Lowel Stern wrote: > You will find that if you use the %s with the popen command you get an > error: > TypeError: unsupported operand type(s) for %: 'file' and 'str' That means you did it wrong, probably mixing up parentheses. Without more information we can't say what specifically. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From dfackrell at DELETETHIS.linuxmail.org Thu Jul 18 11:06:38 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Thu, 18 Jul 2002 09:06:38 -0600 Subject: property problem References: <3D36C65A.5040300@mplusr.de> Message-ID: <3d36d97f$1_2@hpb10302.boi.hp.com> You have defined __data as a private attribute: "Peter Maas" wrote in message news:3D36C65A.5040300 at mplusr.de... > Hi, > > while experimenting with class properties using Python 2.2.1 > I encountered the following weird behaviour: > > This is my testclass: > > class proptest: > > def __init__(self): > self.__data = 0 This declaration invokes python's name mangling. The creation of x later will call this constructor and the __data attribute will appear as x._proptest__data (I think). > def get_data(self): > return self.__data > > def set_data(self, value): > self.__data = value > > data = property(get_data, set_data) > > def meth(self): > return self.__data > > This is my testcode: > > >>> x = proptest() > >>> x.data=234 This line creates a new attribute named x.data, which is completely unrelated to x._proptest__data > >>> x.data > 234 > >>> x.meth() > 0 > >>> x.set_data(234) > >>> x.meth() > 234 Does that help? -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From stefan.heimann at web.de Sun Jul 28 11:49:35 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 28 Jul 2002 15:49:35 GMT Subject: TAB completion References: <3d43eeb4$0$12280$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Hi! Yigal Duppen wrote:: >> My problem is: How can I call the default completion function that >> comes with the python distribution? > > I think you should use the rcompleter module. No. The library manual says: The rlcompleter module defines a completion function for the readline module by completing valid Python identifiers and keywords. I don't want to complete valid Python identifiers and keywords. I want to complete the builting commands of my shell. Bye Stefan From whisper at oz.net Fri Jul 5 14:47:34 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 5 Jul 2002 11:47:34 -0700 Subject: adding methods on the fly In-Reply-To: Message-ID: Have you looked at Boost? www.boost.org David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Renzo Tomaselli > Sent: Friday, July 05, 2002 9:14 > To: python-list at python.org > Subject: adding methods on the fly > > > Hi all, > after a long and unsuccessful search about extending C++ classes by > Python methods, I came up to the point where a couple of basic questions > should be answered: > > 1. Can we add new (Python) methods to a C object wrapper, e.g. > after it has > been instantiated with a normal (C) method table ? > 2. if not: can we add a new method to an already imported Python > class ? If > yes, how can we do it, assuming to start from a method statement > hosted by a > string ? > > I understand that the latest version (2.2.1) allows for defining a class > which inherits from a C type, so that we can define some Python methods on > it, while retaining the capability of inherited C methods. > The point is that I want to add Python methods on demand to such class. > Thanks, > > Renzo Tomaselli > > > -- > http://mail.python.org/mailman/listinfo/python-list From max at alcyone.com Wed Jul 10 16:31:46 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Jul 2002 13:31:46 -0700 Subject: Z-machine/Infocom interpreter in Python? References: <3D2BE29E.4C49B91C@alcyone.com> Message-ID: <3D2C99B2.731F1A85@alcyone.com> [Including comp.lang.python in newsgroups one last time, since this still involves Python; followups to rec.arts.int-fiction only.] Andrew Plotkin wrote: > There was a Perl Z-code interpreter. I don't see it on the Archive, > but do a web search under "Rezrov". I believe it's written to be a > normal application, not a chat plug-in, but converting it might be > easier than converting a C application. Right, a Perl buddy of mine is looking into that one. Evidently it's a fairly general library so it would probably do the job on the Perl side. > I don't recall a Python interpreter. I'm in favor of one, though. :) > > Then there's Floyd, the bot who hangs out on IFMud and does more or > less this job. I'm not sure what he's written in. I suspect pipes and > hackery are involved. Right. That is certainly feasible, but it isn't elegant and would be a headache. I was hoping for a pure Python solution so that I can just "make it go." I might end up writing my own, though as indicated I'd only be concerned with the barest minimum of implementation. > Z5 and Z8 are what you're looking for. Z6 was the graphics-supporting > version. (Z8 is not graphical; it's a minor variant of Z5 with a > different memory map, so most interpreters that support 5 also support > 8.) I read the Z machine specification last night. It's pretty straightforward; it looks like the biggest roadblock is going to be maintaining compatibility with multiple versions of the Z machine. z5 and z8 would be obvious targets, although since I'm interested in the ability to play legacy Infocom games as well, it looks like I'm going to need z3 support, and maybe z4 or even z2. z1 is so ancient it doesn't seem necessary, and z6 is the graphics stuff I don't want. So should a first run target z2, z3, z4, z5, and z8? Does that sound right? > The status line would have to be dealt with specially. The simplest > plan is to have the system intercept a particular command ("$STATUS" > maybe) and dump the status window. Right, there would have to be some out-of-band solution to get at the status line; it wouldn't be a normal part of the back and forth with the game client. Seems relatively straightforward, anyway. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From zopestoller at thomas-guettler.de Tue Jul 9 09:25:12 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 09 Jul 2002 15:25:12 +0200 Subject: win32: Leaving Dos Box open Message-ID: <3D2AE438.9030205@thomas-guettler.de> Hi! How can the dos box be left open when I run foo.py from the windows explorer and there is a syntax error? thomas From mertz at gnosis.cx Thu Jul 4 23:20:57 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 04 Jul 2002 23:20:57 -0400 Subject: Copyright metaphors References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> <7xwusbyncl.fsf@ruckus.brouhaha.com> Message-ID: |> [copyright contract] is an extremely *bad* metaphor, |> one that does far more to conceal what's going on than reveal. Paul Rubin wrote previously: |Is it a worse metaphor than "the copyright bargain"? That phrase has |been around for decades or centuries and is generally considered apt. Hmmm... however many decades or centuries, I've never read that specific phrase before this thread. I do have a Ph.D. in social philosophy, and have read moderately widely in legal opinions. But I'm sure you're right that someone has used it (and have a particular interest in recent trends in abusive extension of IP law). I don't particularly -like- the metaphor of "copyright bargain," but it feels a lot less deceptive than is the contract metaphor. Would you like the phrase "taxation bargain?" That seems a bit similar--states impose mandatory tax obligations, at least nominally in "exchange" for the provision of various services to citizens and residents. I still kinda think of a bargain as something that people actually agree to... but the word is more vague than 'contract', so I can kinda "get" the word 'bargain'. |I have a worse problem with "IP" than with "copyright bargain". The |copyright bargain is one that society (through its elected legislature) |supposedly made with authors. The current problem is that the legislature |acted in the interests of lobbyists rather than the electorate. I quite agree with Paul Rubin here. I don't like to use "IP" without the scare quotes (although I only added them the first time, not each subsequent time, in my prior post). And of course I am sickened by the way that Disney &Co outright purchased the "Mickey Mouse Protection Act." But I don't agree that copyrights were ever ethically defensible to start with; nor that they ever "advanced the progress of arts and science" as the US Constitution allows (as a limited possibility). Then again, I'm also not such a fan of slavery, which the US Constitution also enshrined.... both for pretty much the same reasons. -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From iwk_removethis at xs4all_removethisalso.nl Mon Jul 22 10:39:09 2002 From: iwk_removethis at xs4all_removethisalso.nl (iwk) Date: Mon, 22 Jul 2002 16:39:09 +0200 Subject: ssh and Python References: Message-ID: <3D3C190D.5020009@xs4all_removethisalso.nl> edadk wrote: > I would like to write script that using ssh automatically execute > commands commands on a remote machine. How can I do that? Use the following function 'rcmd' to execute commands on a server through SSH with password authentication (better to use keys, but that's not always an option) The trick is to use os.forkpty because ssh will not read stdin for the password, but rather directly from the terminal. It works on Unix and on Windows through Cygwin (not directly on Win32 because it lacks the os.forkpty() implementation) Regards, Iwan #!/usr/bin/env python #Remote command through SSH using user/password import os, time def pause(d=0.2): time.sleep(d) def rcmd(user, rhost, pw, cmd): #Fork a child process, using a new pseudo-terminal as the child's controlling terminal. pid, fd = os.forkpty() # If Child; execute external process if pid == 0: os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + cmd) #if parent, read/write with child through file descriptor else: pause() #Get password prompt; ignore os.read(fd, 1000) pause() #write password os.write(fd, pw + "\n") pause() res = '' #read response from child process s = os.read(fd,1 ) while s: res += s s = os.read(fd, 1) return res #Example: execute ls on server 'serverdomain.com' print rcmd('username', 'serverdomain.com', 'Password', ['ls -l']) From tim.one at comcast.net Tue Jul 2 22:47:15 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 02 Jul 2002 22:47:15 -0400 Subject: Comments in pickles? In-Reply-To: Message-ID: [Roy Smith] > I've got a file parser that returns a data structure. As part of a > regression test suite, I'm going to parse several sample files and save > the resulting data structures as pickle files to compare against future > versions. I want to check those pickles into CVS. > > Our usual practice is to imbed the CVS id string ($Id: ) in every > checked-in file as a comment. I encourage you to question that practice. > Is there any way to do that with a pickle? Does a comment convention > exist which cPickle.load() understands? No. If you have to do this, give your data structures a (say) .rcsid attribute, and store the $Id in that as a string. From plungermonkey at cox.net Tue Jul 16 11:44:31 2002 From: plungermonkey at cox.net (Jef) Date: Tue, 16 Jul 2002 15:44:31 GMT Subject: Radians vs. Degrees References: <3D33016C.8030804@cox.net> Message-ID: <3D3440D3.2060400@cox.net> Jef wrote: > Hi All, > > I'm new to this NG so please bear with me :-) I'm writing an addon for > the Quake2 editor named QuArK and could use some advice from the > math/coding gurus out there. > > My problem is that I'm trying to create a torus (donut) and the C code > I'm looking at uses DTOR to convert degrees to radians and I see no > mention of it (DTOR) in Python. My question is whether I need this in > Python or does Python automatically convert to radians during > calculations? Also, do the FOR loops work the same as in C++ (e.g. > FOR(x=0, x<360, x++))? If not, any suggestions on how to do this? > > TIA > > -Jef > Thanks for the info! It'll certainly save what little I have left :-p From robin at jessikat.fsnet.co.uk Fri Jul 19 04:55:01 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 19 Jul 2002 09:55:01 +0100 Subject: ANN: Pyrex 0.3.4 References: Message-ID: In article , Brian Lenihan writes >Robin Becker wrote in message >news:y at jessikat.fsnet.co.uk>... ...... >> primes.c(139) : see declaration of 'initprimes' >> error: command '"C:\Program Files\Microsoft Visual >> Studio\VC98\BIN\cl.exe"' failed with exit status 2 > >It's not you. MSVC doesn't like the void initprimes >prototype above the > >__declspec(dllexport) >void initprimes(void) { > >You can work around it by inverting the order in >Pyrex/Compiler/Nodes.py like so: > >header = "void init%s(void)" % env.module_name >if sys.platform == "win32": > code.putln("__declspec(dllexport)") >else: > code.putln("%s; /*proto*/" % header) thanks for the info, but this code looks pretty weird to me. Why do we need the prototype immediately before the actual specification? in the non win32 output void initprimes(void); /*proto*/ void initprimes(void){ ....... } the first line seems completely redundant. any how I tried /F's suggestion and replaced all that with code.put_var_declarations(env.const_entries, static = 1) code.putln("") code.putln("DL_EXPORT(void) init%s(void){" % env.module_name) code.put_var_declarations(env.temp_entries) -- Robin Becker From mwh at python.net Thu Jul 25 11:03:24 2002 From: mwh at python.net (Michael Hudson) Date: 25 Jul 2002 16:03:24 +0100 Subject: [Pythonmac-SIG] Numeric Q: How to get DBL_MAX, etc. in Python? In-Reply-To: "Louis M. Pecora"'s message of "Wed, 24 Jul 2002 17:43:33 -0400" References: Message-ID: <2mbs8vg88z.fsf@starship.python.net> "Louis M. Pecora" writes: > In C there are platform-specfic, floating-point constants as follows defined in float.h, > > /* The largest double precision # */ > DBL_MAX (* (double *) __double_max) > > /* The accuracy of double precision */ > #define DBL_EPSILON (* (double *) __double_epsilon) > > /* The smallest double precision # */ > #define DBL_MIN (* (double *) __double_min) > > Where do these reside in Python? Nowhere. > I have looked over my Python manuals and done a Google search, but > can't find any reference to them or float/double limits outside of > some threads online that are requesting the same as me, but no > answers. Are there standard Python functions or globals that return > these values for the platform one is operating on? Nope. Obviously writing a C extension to expose these shouldn't be too hard... (although making them constants is inevitably a bit broken -- DBL_EPSILON varies as the rounding mode does, for example). > Any help appreciated. Thanks. Well, not sure this counts. Cheers, M. -- > So what does "abc" / "ab" equal? cheese -- Steve Holden defends obscure semantics on comp.lang.python From eugene1977 at hotmail.com Wed Jul 17 02:47:34 2002 From: eugene1977 at hotmail.com (a64bs4$1oo$1@newsreader.mailgate.org) Date: Wed, 17 Jul 2002 02:47:34 -0400 Subject: history xml file parse help Message-ID: hi i'm totally newbie to python/xml (just reading first book of those) i'd like to parse a history file(galeon browser) and feed into database and crawl each url and save it in database also.. so that i can do search on it.. well.. this history file looks very easy to parse.. but i couldn't find a working sample code.. can anyone help me plz? thank you From anton.wilson at camotion.com Wed Jul 31 18:22:17 2002 From: anton.wilson at camotion.com (anton wilson) Date: Wed, 31 Jul 2002 18:22:17 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207312221.SAA29204@test-area.com> > > > So, the GIL does not blcok as intended, and this probably needs to be > > looked into. > > It does not always block, and this is as intended. > One final clarification on this subject is that with the current version of python on my system, the GIL never blocks, and that is why I was complaining. The only reason other threads get scheduled is because threads run out of time. From roy at panix.com Tue Jul 2 23:23:22 2002 From: roy at panix.com (Roy Smith) Date: Tue, 02 Jul 2002 23:23:22 -0400 Subject: Comments in pickles? References: Message-ID: Tim Peters wrote: >> Our usual practice is to imbed the CVS id string ($Id: ) in every >> checked-in file as a comment. > > I encourage you to question that practice. This is getting a little off-topic, but why do you say that? It's the most convenient way I know of to identify a file when you're looking at it. From bokr at oz.net Mon Jul 1 15:54:39 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2002 19:54:39 GMT Subject: stream to string-question References: Message-ID: On Mon, 1 Jul 2002 18:08:42 +1000, Aldo Cortesi wrote: >Thus spake Klaus Reinhardt (K.Rdt at TU-Berlin.DE): > >> --------------------------------------------------------------------- >> Hi >> y=os.popen( 'netstat -a -n','r').read() y=os.popen( 'netstat -a -n','r').readlines() #(a) y=os.popen( 'netstat -a -n','r').read().splitlines() #(b) >> # Aktive Verbindungen >> # >> # Proto Lokale Adresse Remote-Adresse Status >> # TCP 0.0.0.0:1171 0.0.0.0:0 LISTENING >> # TCP 130.149.164.212:1171 130.149.4.11:110 ESTABLISHED >> print y ^^^^^^^-- leave out, since this would now be printing ['<1st line>, '<2nd line>', ''] >> for i in y: >> print "--------: ", i print "--------: ", i.rstrip() #(a) strip trailing whitespace, so print doesn't double it print "--------: ", i #(b) splitlines above does the job >> The last is outputting each character in a single line. Is >> there a function to convert this stream in the text-rows? > > >The variable "y" above is a single, long string with some >embedded newlines. When you iterate over a string you get >its component characters one by one. > >What you really want to do is to split the string up into a >list of lines. Luckily, the string type has a method that >does exactly that... Try: > > lines = y.splitlines() > for l in lines: > print "---: ", i > I forgot splitlines, so I was going to suggest (a) until I read your suggestion, which I would then suggest using as in (b). Regards, Bengt Richter From Eaborges at hotmail.com Tue Jul 30 17:12:23 2002 From: Eaborges at hotmail.com (Emanuel Borges) Date: 30 Jul 2002 14:12:23 -0700 Subject: Error including win32net in a Python COM server Message-ID: I've created Python COM servers in the past with a fair amount of success but I can't seem to figure out what I am doing wrong in this instance. The only difference that I have found is that in this particular COM server, I am importing win32net. And after doing some debugging I have found that the COM server works fine if I remove this import. This, however I can't do because I need NetUseGetInfo, NetUseAdd, NetUseDel & NetUseEnum for my Server to function correctly. I've attached the meat of my code below. If anyone can offer any insight, I would be extremely grateful. The error that I'm getting is that the Specified procedure could not be found. When I use Python debugging I get the error number 2147221231. I've looked in previous posts but haven't had much luck... ##The splitstring is just here so that I could test the COM server ##without the win32net import. Without the import, it works fine. ##The code itself also works fine before making it a COM server. import os from win32net import NetUseGetInfo, NetUseAdd, NetUseDel, NetUseEnum class ShareControll: _public_methods_=['QueryDrive','MapDrive','DeleteDrive','SplitString'] _reg_progid_ = "PythonDemos.MW_COM" _reg_clsid_ = "{1CBECF27-89E4-4E5A-928B-92E11B11B0A9}" def MapDrive(self, letter, share): try: share = u'%s'%share letter = u'%s'%letter NetUseAdd(None,1,{'remote': share, 'local': letter}) status = "sucess" except: status = "fail" return status def DeleteDrive(self, letter): try: NetUseDel(None,letter) status = "sucess" except: status = "fail" return status def QueryDrive(self, letter): try: query = NetUseGetInfo(None,letter) except: query = "Drive not in use" return query def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) if __name__ == "__main__": print "Registering COM server..." import win32com.server.register win32com.server.register.UseCommandLine(ShareControll) From markm at cup.hp.com Wed Jul 3 21:14:03 2002 From: markm at cup.hp.com (Mark Mitchell) Date: Wed, 3 Jul 2002 18:14:03 -0700 (PDT) Subject: Threads, signals, and fork Message-ID: <200207040114.SAA09082@hpadl658.cup.hp.com> Python 2.2 blocks signals in new threads: /* Mask all signals in the current thread before creating the new * thread. This causes the new thread to start with all signals * blocked. */ sigfillset(&newmask); SET_THREAD_SIGMASK(SIG_BLOCK, &newmask, &oldmask); That means that if the thread calls fork(), all signals are blocked in the child process. This is not necessarily what the programmer wanted. The blocking of signals for new threads is justified in the documentation for the signal module with the argument that since some systems do not allow you to send signals to individual threads, Python doesn't let you do it on any system. That argument is fine as far as it goes -- but since Python doesn't provide sigprocmask, there's no way to re-enable signals -- even for child processes. Thoughts? -- Mark Mitchell CodeSourcery, LLC mark at codesourcery.com From fredrik at pythonware.com Mon Jul 1 07:10:43 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 11:10:43 GMT Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: John Roth wrote: > Python does not support declarations at all. sure does. it's spelled "assert isinstance". From b.maryniuk at forbis.lt Thu Jul 4 04:09:07 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 10:09:07 +0200 Subject: Efficient python programming... In-Reply-To: <3D23D092.4E3AD523@engcorp.com> References: <3d238f6b.579164824@news.dsl.pipex.com> <3D23D092.4E3AD523@engcorp.com> Message-ID: <200207041009.07015.b.maryniuk@forbis.lt> On Thursday 04 July 2002 06:35, Peter Hansen wrote: > > I prefer this one: > > > > "You can have it right" > > "You can have it cheap" > > "You can have it now" > > > > Pick any two. > > Interestingly, XP provides a way to have all three... If You mean XP-programming, than I'm not agree: You can't have it NOW. If You mean WinXP, than I'm agree.reverse() : You can have it bad, expensive and later (like anything something else from Microsoft, what's newer works right)... -- Sincerely yours, Bogdan M. Maryniuck Who wants to remember that escape-x-alt-control-left shift-b puts you into super-edit-debug-compile mode? (Discussion in comp.os.linux.misc on the intuitiveness of commands, especially Emacs.) From mkingston at -at-shaw.ca Thu Jul 4 17:21:28 2002 From: mkingston at -at-shaw.ca (Mark Kingston) Date: Thu, 4 Jul 2002 14:21:28 -0700 Subject: Newbie: Dynamically create a Tree List with items read from multiple files Message-ID: <3d24bdf2$1_1@axion.net> Hi everyone, This may be a simple one to most of you but I'm not sure where to start... I've been looking at the wxPython demo and would like to modify it so that when it starts, it loads the tree items (wxTreeCtrl) from multiple files depending on a parameter passed to it. Also, when a user clicks on a button which supplies the application a different parameter, the control is refreshed with the new items. To generalize the question, I guess I would like to know how to populate a control with items read in from multiple files. Any help would be appreciated! -- Mark. mkingston at -at-shaw.ca Please remove '-at-' from my email address if replying directly to me. From gleki at gol.ge Tue Jul 2 04:56:01 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Tue, 02 Jul 2002 10:56:01 +0200 Subject: Where python especially good ? References: Message-ID: <3D216AA1.C76A25A9@gol.ge> Python is LOT more, than just a scripting language. Python interpreter is, maybe first of all, the virtual machine. Therefore, one may apply Python in nearly all fields, where the compiled languages dominate. Python supports not only the procedural programming, but, OO, and what is not less important, functional programming Python is the first class language for pedagogical purposes. Personally, I need Python for scientific computations. Not each language has SciPy (Scientific Python), NumPy (Numeric Python) and MMTK (Molecular Modeling ToolKit) modules. Indeed, Python's big advantage is the refined set of modules. Greetings, Giorgi Andrey Koubychev wrote: > Hello everyone, > > What do you think, at what tasks pythons shows great benefits comparing to > other script languages ? > > -- > Best regards, > Andrey Koubychev From fperez528 at yahoo.com Wed Jul 24 20:12:46 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 24 Jul 2002 18:12:46 -0600 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: holger krekel wrote: > My use case is > > from?somemodule.someclass?import?filter1 > > where 'filter1' would reference an unbound class-method. > I need this for implementing a class which offers filter > functions which can be applied either as > > obj.filter1(args) > or > filter1(obj,?args) > > Of course, you can express the latter via > > someclass.filter1(obj,?args) > > but i want to have filter1 (and 41 other filter methods) > potentially directly in the namespace.??I?know?that?i?can?write > > filter1=someclass.filter1 > filter2=someclass.filter2 > ... > > but it's redundant and you have to repeat this scheme whereever > you use 'somemodule'.??That's?ugly?where?in?fact?i?just?want?to?say > > from?somemodule.filters?import?filter1,filter2,?filter37 > > and someclass could inherit from 'filters', thus providing both > invocation methods. What about: #somemodule.py def filter1(self,args): ... def filter2(self,args): ... ... class someclass: ... someclass.filter1 = filter1 someclass.filter2 = filter2 ... # end somemodule.py I know there's still one little layer of redundant typing, but it only has to be done in the module which defines your class, not by the users. So you do it once and you are done. Is there any reason why this doesn't address your requirements (I may well be missing something)? cheers, f. ps. I guess you lose safety checks on what 'self' is when you invoke them as standalones, but you could always put an assertion in them if that is critically important. From peter at engcorp.com Thu Jul 11 23:48:48 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Jul 2002 23:48:48 -0400 Subject: Python for data driven website? References: Message-ID: <3D2E51A0.730F521A@engcorp.com> Micah Mayo wrote: > > My company is in the early stages of building a web application for > accountants. Right now we're trying to choose which technology we're going > to write it in. You don't need to say any more than that to elicit the correct answer at this point, which is "what are your requirements?". You need to get a handle on what you actually need to accomplish, not just go on a wild search for cool technologies. You've implicitly identified that you are uncomfortable with the restrictions of some proprietary products from certain largish companies, so one can infer one of your requirements is something like open or free licensing. What else? What kind of performance do you need? Reliability? Scalability? Ease of development or maintenance? Prior experience in the technology by existing developers? Come up with the answers to those and many similar questions, and then you are ready to research the available options and pick the best for your needs. I strongly recommend *not* just asking "what can this product do for me?" because you will end up with a solution to problems you don't even have, and all kinds of hidden costs as a result. (My free advice as a consultant... worth what you paid for it. :-) -Peter From imcmeans at home.com Tue Jul 2 17:58:49 2002 From: imcmeans at home.com (Ian McMeans) Date: Tue, 02 Jul 2002 21:58:49 GMT Subject: more details References: <1qeU8.54178$vo2.2989593@news2.telusplanet.net> Message-ID: I'm running apache 2.0, and python 2.2. Here's the URLError that's thrown: global URLError = , err = URLError: __doc__ = None __getitem__ = > __init__ = > __module__ = 'urllib2' __str__ = > reason = Can someone with apache try the script I wrote and tell me if it works? How can I get more details on the error? From see_reply_address at something.invalid Mon Jul 22 21:54:58 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 23 Jul 2002 13:54:58 +1200 Subject: Dict^H^H^H^HSomething in binary pickle causes exception References: Message-ID: <3D3CB772.8050703@something.invalid> Tim Peters wrote: >>>>import cPickle >>>>d = {1: 2} >>>>s = cPickle.dumps(d, 1) >>>>cPickle.loads(s) >>>> > {1: 2} > No problems for me. Show us what you do that fails. Sorry, it looks like I jumped to a completely unwarranted conclusion by assuming that dictionaries were responsible. There is *something* in my pickle that the unpickler doesn't like, however. It's a pickled Plex Lexicon, and it's rather big (too big to post here, anyway). I'll do some more investigation and try to narrow it down. Anyway, what I mainly wanted to find out is whether the binary format *should* be able to handle everything that the non-binary format can. I take it the answer to that is "yes"? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From donn at u.washington.edu Fri Jul 5 13:13:13 2002 From: donn at u.washington.edu (Donn Cave) Date: 5 Jul 2002 17:13:13 GMT Subject: IMAP Email Question References: Message-ID: Quoth "Emile van Sebille" : | Charel Yueng | > I cannot process any string data because it's a tuple. I can't seem | > to be able to parse any data. | > | > What should be my approach to this problem? | > what I need to extract is separated by the '=' sign ie. | > charles,yueng,someaddress | > | | >>> s = | 'fname=charles\r\nfname=yueng\r\naddress=someaddress\r\n\r\n\r\n' | >>> [x.split("=") for x in s.split()] | [['fname', 'charles'], ['fname', 'yueng'], ['address', 'someaddress']] I suspect you're taking his example too literally. If the message always looked just like that, then he could save himself the trouble and just assume the result. Actual email messages tend to have a body after the header, so if you want to focus your analysis on the header, then you need to start by separating it from the body - header, body = text.split('\r\n\r\n', 1) Values in an ordinary header may contain white space, so it would make some sense to start by splitting them on line boundaries. His example, with the fname= format, doesn't strike me as an RFC822 email message, but if that's just an error in the problem statement, the rfc822 module might help do all this. Donn Cave, donn at u.washington.edu From tim.one at comcast.net Sun Jul 14 15:16:11 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 14 Jul 2002 15:16:11 -0400 Subject: Python and Parrot In-Reply-To: <3D316CCA.90605@myrealbox.com> Message-ID: [Johann H?chtl] > Can someone quote a bit on Python --> Parrot > (the upcoming VM Perl 6 is about to use. Designed for weakly typed > programing languages. See http://www.parrotcode.org ) > > > Recent progress has been very fast and according to > > http://use.perl.org/articles/02/07/03/2241212.shtml > > the progress of parrots implementation is even likely to speed up. Umm, that says the Perl Foundation has run out of money to pay the principal developers, and at least in Dan's case makes clear that he can't afford to work for free ("unless ... comes through in the next few weeks, Dan will get a full-time job and likely pass on the Parrot Design Hat"). This is likely to speed progress in what sense? > Recent speed measurements of the VM yielded very good results and the > ruby folks already seem to have the Parrot VM as a target in mind. > > http://www.rubygarden.org/article.php?sid=234 Looks like that both started and petered out in May. A better sense may be gotten from Ruby's Parrot front-end project Wiki: http://www.rubygarden.org/ruby?CardinalProject It appears inactive; the last edit on the home page was to remove the link to the codebase: http://savannah.gnu.org/projects/cardinal/ which also appears to be inactive. The development mailing list also looks dormant now, after a small flurry of activity in May: http://mail.freesoftware.fsf.org/pipermail/cardinal-dev/ > Has the situation for Python changed ... Not that I know of. Andrew Kuchling has kept half an eye on Parrot in the Python world, and AFAIK nobody else has volunteered time to do more than that. Parrot is a wonderfully ambitious project, but other commitments are such that we've only been able to wish it well from a distance. From Norman_Shelley-RRDN60 at email.sps.mot.com Fri Jul 26 16:34:45 2002 From: Norman_Shelley-RRDN60 at email.sps.mot.com (Norman Shelley) Date: Fri, 26 Jul 2002 13:34:45 -0700 Subject: ?Module re documentation bug, error, or misunderstanding? Message-ID: <3D41B265.AD56FF90@email.sps.mot.com> In http://www.python.org/doc/current/lib/re-syntax.html and even in my old paper copy (version 1.5.2?) it has this: \number Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not'the end' (note the space after the group). This special sequence can only beused to match one of the first 99 groups. If the first digit of number is 0,or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. (There is a group 0, which isthe entire matched pattern, but it can't be referenced with \0; instead, use \g<0>.) Inside the "[" and "]" of a character class, all numeric escapes are treated as characters. So, what am I missing below as both searches "should" succeed? % python2.1 Python 2.1 (#2, Apr 24 2001, 11:33:06) [GCC 2.95.3 20010315 (release)] on hp-uxB Type "copyright", "credits" or "license" for more information. >>> import re >>> re.search("(.+) \1", '55 55') >>> >>> re.search("(.+) (.+)", '55 55') From fredrik at pythonware.com Tue Jul 16 18:52:30 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Jul 2002 22:52:30 GMT Subject: UnicodeError: ASCII encoding error: oridinal not in range(128) References: Message-ID: Doru-Catalin Togea wrote: > The same code fails when "tmplText" comes from an XML files which contains > norwegian characters (latin-1 extension), like ø, in the data, not > in the tags, with the following error message: > > Traceback (most recent call last): > File "./python/genh1.py", line 335, in ? > f.write(tmplText) > UnicodeError: ASCII encoding error: oridinal not in range(128) you're trying to write unicode strings to an 8-bit device, without telling Python what encoding to use. instead of guessing what to do with non-ASCII characters, Python throws an exception. > What kind of strings do write() and print() handle? Hopefully I can > convert my strings to that type. try: f.write(tmplText.encode(encoding)) where encoding is the encoding used by your terminal (most likely "iso-8859-1", aka latin 1). for some additional notes, see: http://effbot.org/zone/unicode-objects.htm http://www.python.org/doc/current/tut/node5.html (section 3.1.3) http://www.reportlab.com/i18n/python_unicode_tutorial.html and http://www.python.org/peps/pep-0100.html From aldo at nullcube.com Tue Jul 30 19:05:48 2002 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 31 Jul 2002 09:05:48 +1000 Subject: Check undefined variable In-Reply-To: References: <3D46AD2E.709@img-online.de> Message-ID: <20020730230548.GB14027@nullcube.com> Thus spake John Hunter (jdhunter at ace.bsd.uchicago.edu): > >>>>> "Michael" == Michael Grabietz writes: > > Michael> Hi, how is it possible to check whether a variable 'a' is > Michael> undefined or not. > > The namespace is stored in a dictionary that maps variable names to > values. You can access the namespace with the functions globals() and > locals(). Since these return a dictionary, you can use the method > has_key() to see if the name exists > > >>> globals().has_key('a') > 0 > >>> locals().has_key('a') > 0 > >>> a = 1 > >>> globals().has_key('a') > 1 > >>> locals().has_key('a') > 1 Unfortunately this idiom doesn't quite work as expected. Consider the following: def foo(): mung = 1 def bar(): print globals(), locals() print mung bar() foo() With nested scopes, the variable mung is certainly available within the function bar, yet it is not to be found in either the globals or locals dictionaries. The only complete way to check wether a variable is defined in a certain scope is to reference it, and catch the exception. Aldo -- Aldo Cortesi aldo at nullcube.com From b.maryniuk at forbis.lt Tue Jul 9 04:41:07 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 10:41:07 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <96c7f32.0207081518.52ea644a@posting.google.com> References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <200207091041.07136.b.maryniuk@forbis.lt> You know, that's funny. :)))))) On Tuesday 09 July 2002 01:18, curt finch wrote: > Issues and concerns > ? No integrated GUI (Graphic user interface) support. wxWindows, anygui, Tk, GTK+, QT, fwm and Windoze resources. Did somebody can make Java soft with... QT or wxWindows widgets? No?!.. > ? No compiler to the native code. Aha, sure. Java -- "write once and debug everywhere". Ask them what is JVM and what that 40 megs bloatware doing on your machine and why same Java crapware doe not working on shortly-different JVM versions. > ? No automatic garbage collection. What?! > ? Does not have vast number of libraries as that of Java, > Perl, C++; etc. Actually, do not trust for all what is on CPAN, if you do something expencive, commertial and with long support offering. IMHO... > ? Since Python is an interpreted language, it requires > frequent run-time checks and thus does not provide the speed, > performance and efficiency of compiled languages like Java, Perl and > C++, which is a major issue. This is really VERY funny. Who said that *Perl* or Java is compiled language? They both are _interpreters_ with different that Java do bytecode first. > ? Python does not provide multiple ways to perform tasks as do > most other languages. This is just commertial crap of stupid managers. > ? Limited documentation- only two English language books exist > which provide tutorials or a library reference for Python. Take them look over amazon.com -- let they stop crapping you. > ? The language is restricted to fewer code modules. Ask them to show the Java code, where is the multiple class inheritance. ;-) > ? Lacks native threading capabilities. Really? Just do: import thread import threading ...or show them few examples of threading from wxWindows demos. > ? Lacks basic tools such as integrated source level debuggers. Oh yes. I "like" when JSP shows me at leat five pages of traceback where you can found nothing suitable for bugfixing. One of the all featureas why I like Python -- is _exact_ and _smart_ explanation what and where is wrong (unlike Perl or Java). > ? No packaging methods for software distribution. Look at any release since 2.0 (afaik). > ? Lacks tools to solve typographical and type mismatch classes > of errors. What the crap is here? Is it like "wwooohhoooo!!! I have COMPILED it!!! SEL-L-L!!!" > ? Python cannot write docstrings in C++. What is this (anybody understood this?). > ? Python is difficult to read. Aha, sure: -----------------8<----------------- #!/usr/bin/perl -w use strict; $_=q[";7w2q";m/656/bq6/i;$g= q(3616w8206qc7);$/="265502"; 0;{$w=~y/726568q7/=46/;}for( 6..ew(6));q1;=|20.747.3754|; @wa];s[\[^0-9a-f\]]{}g;@ARGV =reverse(/../g);$a=\@ARGV;0; grep{push(@_,sprintf('%.2x', hex))}@$a;$"=q s\xs ;$$=qq"$ \"@_";$$=~s/\s//g;print eval qq("$$"); -----------------8<----------------- > Application Areas > ? Prototyping and development > ? Platform independent graphic user interface applications > ? Internet scripting/applications > ? Automated test harnesses > ? System administration applications > ? Shell scripting/OS Scripting > ? Text processing > ? Database Interfaces > ? Application Extensions > ? Distributed Programming All of this are just buzzwords, used by stupid lamers. What I suggest, is only FIRE OUT your competitors. > Python users > ? Yahoo > ? Infoseek also NASA, Google, IBM and a lot of others, described on http://www.python.org -- Sincerely yours, Bogdan M. Maryniuck lp1 on fire (One of the more obfuscated kernel messages) From duncan-news at grisby.org Mon Jul 1 12:08:04 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 01 Jul 2002 16:08:04 GMT Subject: Europython pictures References: Message-ID: In article , Scherer, Bill wrote: >> http://www.grisby.org/Photos/085/ >Nice photos. Can you add some captions so we know who we are >looking at? Good idea. I've added captions to the ones where I can remember the names. Feel free to email me with additions or corrections... Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From tbryan at python.net Sat Jul 27 11:05:26 2002 From: tbryan at python.net (Tom Bryan) Date: Sat, 27 Jul 2002 15:05:26 GMT Subject: Python and XML help References: Message-ID: Mathieu wrote: > I'm new to Python and having some problems parsing the following XML : Suggestion: You'll get more responses if the code you post will run or will only hit errors that you're asking about in your post. If you're hitting an Exception, then you should include the Python stacktrace in your post. Often, we'll then be able to answer your question without even running your code. > > > > This document isn't even well-formed XML. It should be or > > > > > > > > You also need a closing properties tag > if __name__ == "__main__": > p=myparser() I'm assuming you left out something like data = open( "properties.xml" ).read() > p.feed(data) > p.close() > I would like the script to write only the "name" variables that are > within the "first" brackets and ignore the others. Please note that my > code must stay compatible with Python 1.5 and that this example might > not work or contain errors, because it is a simplified version of the > code I have written. I'm more familiar with SAX parsers in Java, but Python's XMLParser looks similar. Generally, I would say that you should just keep a stack of element names that your parser has seen. Then you can peek at the stack to see where you are. I see that XMLParser seems to maintain a stack, but I'm not sure whether you're really supposed to use it. That is, perhaps it isn't guaranteed to exist in future versions. Look at xmllib.py in your Python distribution and see what the comments to XMLParser say. Anyway, using the stack inherited from XMLParser, here's how I would do what you're saying def start_item(self,attrs): # Look for "item" elements only within "first" elements # and print the value of the "name" attribute if self.stack[-1][0] == 'item' and self.stack[-2][0] == 'first': print attrs['name'] ---Tom From peter at engcorp.com Thu Jul 18 18:35:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Jul 2002 18:35:08 -0400 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <3D37429C.53BC0FDB@engcorp.com> OtisUsenet wrote: > > Python newbie question. How does one do something like this in > Python: > > # assign the value of j to i and then increment j by 1 > i = j++ > > I checked the FAQ at http://www.python.org/doc/FAQ.html, but this > simple question wasn't covered :) I can't find it in 2 Python books > either. Is there anything you don't like about doing it exactly as your comment reads? >>> i = j >>> j = j + 1 On newer Pythons, you can replace the second line with j += 1 if you wish. -Peter From alexandrecourbot at linuxgames.com Sun Jul 21 05:42:05 2002 From: alexandrecourbot at linuxgames.com (Alexandre Courbot) Date: Sun, 21 Jul 2002 11:42:05 +0200 (CEST) Subject: Python very slow on the Sharp Zaurus - any idea why? Message-ID: <20020721115251.12dd6d7d.alexandrecourbot@linuxgames.com> Hello everybody, I have just ported the game I'm working on to the Sharp Zaurus (206 Mhz StrongArm, Linux based handheld). This game links to the Python library to embed the Python interpreter, which is used as the game internal scripting language. However, performances are far behind what I'd have expected. On a classic PC, there is no noticeable overhead because of the Python scripts and the gfx operations takes most of the CPU. On the Zaurus however, it's all the contrary: the game is so slow that it is totally unplayable. And when I disable all Python scripting, it's very smooth. I don't understand why it is becoming so slow on the Arm. Note that the Arm doesn't have any floating point unit, and that the floating point operations are all emulated. But I never use any floating point arithmetic in my game or in my Python scripts. Note also that I had to cross-compile the Python library myself from Python 2.2 sources, as there is no lightweight Python distribution for the Arm. But I don't get what's wrong. Does Python use floating point arithmetic internally? Is there something else I missed? My scripts are short schedules that update a character state or take a decision like where to move, for instance. They are quite short, and are run by the game engine at the rate of about 70 times per second. If you want so, I can send one here for analysis. Any help, comment or pointer would be greatly appreciated - moreover Python is quite popular on the Zaurus, as it allows to build GUI applications very easily, so it's surely worth to try to speed it up! Thanks! Alex. -- http://www.gnurou.org From aleax at aleax.it Wed Jul 17 04:30:32 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 17 Jul 2002 08:30:32 GMT Subject: inheriting from C types References: <878dc260.0207161005.6fec78ec@posting.google.com> Message-ID: Renzo Tomaselli wrote: > Hi all, > I'm looking at tips & tricks about inheriting from a C type. It works > (almost), but from any derived class I'm not able to see any base > class method. > Say I implemented a C-type "ype" having > Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE flags as well as tp_dealloc, > tp_getattr slots. > Allocators, constructors etc. are usual defaults. But how is the tp_methods slot set? > Now, in Python: > > import ype > class k(ype.ype): > pass > k1 = k() > > I cannot see/invoke any method on base class ype from k1, while I can > see all of them after direct creation of a base instance, say k2 = > ype.ype(). That's strange. Try something like this (inhe.c): #include "Python.h" typedef struct { PyObject_HEAD } inhe; static void inhe_dealloc(PyObject *op) { op->ob_type->tp_free(op); } static PyObject * inhe_greet(PyObject *self) { Py_INCREF(Py_None); return Py_None; } static PyMethodDef inhe_methods[] = { {"greet", (PyCFunction)inhe_greet, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; static PyTypeObject inhe_t = { PyObject_HEAD_INIT(0) 0, "inhe", sizeof(inhe), 0, inhe_dealloc, 0, 0, 0, 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, "inheritable type", 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ inhe_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ _PyObject_Del, /* tp_free */ }; static PyMethodDef no_methods[] = { {0} }; void initinhe(void) { PyObject* self; inhe_t.ob_type = &PyType_Type; self = Py_InitModule("inhe", no_methods); PyObject_SetAttrString(self, "inhe", (PyObject*)&inhe_t); } and of course the usual setup.py: from distutils.core import setup, Extension setup(name = "inhe", version = "1.1", description = "a tiny example of inheritable type", maintainer = "Alex Martelli", maintainer_email = "aleaxit at yahoo.com", ext_modules = [ Extension('inhe', sources=['inhe.c']) ] ) and a try.py something like: import inhe class gop(inhe.inhe): pass g = gop() g.pop=23 print g.pop print g.greet() del g i = inhe.inhe() print i.greet() print 'OK' class fop(gop): pass print dir(inhe.inhe) print dir(gop) This is working fine for me with Python 2.2.1. Maybe it can help you pinpoint the differences between my working code and your failing code? Alex From eugene1977 at hotmail.com Fri Jul 19 19:46:14 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Fri, 19 Jul 2002 18:46:14 -0500 Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: i used this code.. self.url=attributes["url"].encode('utf-8') what should i do more? this is what actual xml file looks like this is python error msg.. -------------- self.url: http://music.2000mp3.com/artist_viewk.php3?mode=abcd&name=A&lg= > self.title: 2000 MP3 : MP3 ???????????????????????? > Traceback (most recent call last): From renzo.tomaselli at tecnotp.it Fri Jul 5 12:14:07 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: Fri, 5 Jul 2002 18:14:07 +0200 Subject: adding methods on the fly Message-ID: Hi all, after a long and unsuccessful search about extending C++ classes by Python methods, I came up to the point where a couple of basic questions should be answered: 1. Can we add new (Python) methods to a C object wrapper, e.g. after it has been instantiated with a normal (C) method table ? 2. if not: can we add a new method to an already imported Python class ? If yes, how can we do it, assuming to start from a method statement hosted by a string ? I understand that the latest version (2.2.1) allows for defining a class which inherits from a C type, so that we can define some Python methods on it, while retaining the capability of inherited C methods. The point is that I want to add Python methods on demand to such class. Thanks, Renzo Tomaselli From dsavitsk at e-coli.net Sun Jul 7 15:10:44 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 07 Jul 2002 19:10:44 GMT Subject: are win32com definitions from adovbs.inc accessible to Python or do I have to transcode them? References: <3d272a2b$0$4298$afc38c87@news.easynet.co.uk> Message-ID: I think this is what you are asking ... have you run MakePy and looked in the generated code (in ..\gen-py)? they should be there, and they should be accessable. the only caveat is that MakePy will need to be run wherever you install. i prefer, however, even after running MakePy, to just add a comment as to what they are in case makepy support disappears somewhere (usually from upgrading python and forgetting to re-makepy). >>> CMD.CommandType = 0x1 # adCmdText >>> RS.CursorType = 3 # adOpenStatic but you can get to them via ... >>> win32com.client.constants.adCmdText 1 >>> win32com.client.constants.adOpenStatic 3 which sems like a lot of typing to me. (also, note that the "c" in constants is lowercase.) -d "chris lyon" wrote in message news:3d272a2b$0$4298$afc38c87 at news.easynet.co.uk... > I'm using Python 2.1.2.12 with ADO and am wondering if anyone has a way of > encoding the defined constants in adovbs.inc or do I have to look them up > myself (error prone) or do I encode the package myself (noble but the > deadline approaches) ? > > Sorry if this seems a bit cheeky, if theirs a more appropriate mailing list > for these question please point me at it. > > Chris Lyon > > From roy at panix.com Sun Jul 7 11:32:39 2002 From: roy at panix.com (Roy Smith) Date: Sun, 07 Jul 2002 11:32:39 -0400 Subject: newbie-question: more then one constructor in a python-class? References: <3D285A64.6000904@snafu.de> Message-ID: "T. Kaufmann" wrote: > is there a way to have more (then one) constructors in a python-class (like > in Java)? Not really (and that's a good thing, IMHO). You can achieve much the same effect, however, by doing something like: class foo: def __init__ (self, string1=None, string2=None): which allows you to create a foo instance with any of the following calls: a = foo() b = foo('spam') c = foo('spam', 'eggs') If you leave out a positional parameter, it defaults to None (at least it does in the example above). You can build even more complicated constructors using the *args and **kwargs constructs. See http://www.python.org/doc/current/ref/function.html for details. That being said, I find that I only rarely use optional parameters, and I've never (in 5 years) found a need for using either the *args or **kwargs constructs. That's not to say that they're not useful, or that you shouldn't use them, but the dynamic typing and inherent polymorphism of Python seems to make the "let's invent a zillion constructors for every possible combination of arguments" style so common in C++ (and, I guess from your posting, Java) less necessary. From rjh at cyberscience.com Wed Jul 3 06:11:02 2002 From: rjh at cyberscience.com (Richie) Date: Wed, 03 Jul 2002 11:11:02 +0100 Subject: Web templating/db tool with best designer/coder separation? References: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> Message-ID: Stefan, > Can't we leave the HTML alone, just mark the affected tags by giving > them IDs I've been thinking along similar lines recently. The only slight difference is that for form controls I'm allowing the 'name' attribute as an alternative to 'id'. These are the notes I have on the way I'd like the system to work (note that normally the HTML would be read from an external file rather than included in the source): >>> import Template >>> html = """ ... ...

Please fill in your username and the message to send.

... ...
... ... ... """ ... >>> page = Template.Page( html ) >>> page.send >>> page.send.username >>> page.send.username.size 20 >>> page.send.username.size = 30 >>> page.send.username.value = "richie" >>> page.send.username.render() '' >>> page.render() [...what you'd expect...] > - One presentation command file could address and assemle > elements from different HTML template files Yes - eg. a navigation bar down the left-hand side of each page. You have a master page that contains it, marked as a named div, and put a marker div of the same name in each page. The marker just contains "Navigation here!" or something. You then take the menu out of the master page and copy it into the other pages programmatically: >>> masterPage = Template.Page( masterHTML ) >>> aboutUsPage = Template.Page( aboutUsHTML ) >>> aboutUsPage.navigation = masterPage.navigation You can then manipulate it - say you have a 'class' attribute for the menu links and you use a different class for the current page's entry: >>> aboutUsPage.navigation.aboutUs.class = "nav-highlight" (this relies on the links in the menu having 'id' tags). > - Scoping/local replacement within iteration might become complicated This is how I envisage iteration working: a designer includes a table of data in the page using dummy values, and a programmer populates it with new rows based on the designer's original. The objects have a 'clone' method which creates a duplicate object, optionally with some attributes changed: >>> tableHtml = """ ...
... ...
Richie30
""" ... >>> table = Template.Table( tableHtml ) >>> templateRow = table.record >>> templateNameCell = table.record.name >>> templateAgeCell = table.record.age >>> table.remove( record ) >>> i = 1 >>> for data in [ { 'name': 'Andy', 'age': 29 }, ... { 'name': 'Bill', 'age': 12 } ]: ... row = TemplateRow.clone( id='record%d'%i ) ... row.name.setContent( data['name'] ) ... row.age.setContent( data['age'] ) ... table.add( row ) ... i = i + 1 ... >>> table.render()
Andy29
Bill12
When a CGI form is submitted, you recreate the object tree with the submitted values like this: >>> page = Template.Page( html ) >>> page.updateValues( cgi.FieldStorage() ) >>> page.send.username.value "someusername" You can also update the values using a dictionary, for prepopulating the page out of a database for example. The biggest problem I can see is that I'm using object attributes to represent both HTML tag attributes and child objects. So 'form.name' could refer to an attribute of the
tag or to an input control on the form. The obvious solution is to put the children or the attributes (or both) into container objects: >>> page.send.children.username >>> page.send.attributes.action 'test.py' but this makes things look cluttered, especially if you're referring to objects more than one or two levels deep. Note that all these classes, Template.Table, Template.Form, etc. etc., would probably be created on the fly - there wouldn't really be a chunk of code in the Template module for every HTML tag. -- | Richie Hindle, rjh at cyberscience.com | All opinions are mine and not necessarily those of my employer. | Why did the Zen Buddhist refuse anaesthetic at the dentist? | Because he wanted to transcend dental medication. From nospam at dsl.pipex.com Mon Jul 8 19:00:30 2002 From: nospam at dsl.pipex.com (Simon Foster) Date: Mon, 08 Jul 2002 23:00:30 GMT Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> <3d28bdb0.71631360@news.dsl.pipex.com> <3d28c29a.72888518@news.dsl.pipex.com> Message-ID: <3d2a18ea.93891558@news.dsl.pipex.com> On 7 Jul 2002 23:14:30 GMT, William Park wrote: >Simon Foster wrote: >> On 7 Jul 2002 22:30:55 GMT, William Park >> wrote: >> >>>'1\n2\n3\n'.split() works as follows: >>> 1\n2\n3\n -> 1\n2\n3 -> 1 \n 2 \n 3 -> 1 2 3 >>> >>>'1\n2\n3\n'.split('\n') works as follows: >>> 1\n2\n3\n -> 1 \n 2 \n 3 \n -> 1 2 3 '' >>>where the last '\n' separates '3' and '' (null). >> >> Still seems odd! > >Not if you try to go backwards: > > 1 2 3 -> 1 \n 2 \n 3 -> 1\n2\n3 > > 1 2 3 '' -> 1 \n 2 \n 3 \n '' -> 1\n2\n3\n > >-- >William Park, Open Geometry Consulting, >8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin Don't understand what you mean here. You started from the same thing and ended up in two different places. Am I missing something? Surely whether I split on newline or arbitrary whitespace should not matter if the arbitrary whitespace consists _only_ of newlines? From rs at onsitetech.com Tue Jul 9 17:58:20 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 21:58:20 GMT Subject: Why self? References: <3D2B19CE.5040409@onsitetech.com> <3D2B540B.4030205@onsitetech.com> Message-ID: <3D2B5C2E.6050001@onsitetech.com> Alex Martelli wrote: >>Well, I'd say that an object understanding the message I send to it, or >>being the type of object I think it is - success or failure - surely is >>a big difference! Sort of the name of the whole game... > > An object can "understand" (well...) the message (out of metaphor: be > able to supply the attribute or method you're asking of it) WITHOUT > "being the type you think it is". This is called POLYMORPHISM, and > IS the whole game. > Damn! The all-caps are out. And to beat that, I've been blindsided by a red herring! 1. So you're uhh... agreeing but not? 2. I'm down w/ polymorphism, man! I'm all over over it. There's a big difference between type and class, for starters, and 'type' as in 'implements an interface' is what I'm talking about. No, you don't know me, but I know OO. :-) From martin at v.loewis.de Fri Jul 19 20:24:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Jul 2002 02:24:05 +0200 Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: eugene kim writes: > i used this code.. > self.url=attributes["url"].encode('utf-8') > what should i do more? You need to encode all Unicode objects that you have, not just the url attributes. Regards, Martin From forestiero at qwest.net Tue Jul 23 18:29:41 2002 From: forestiero at qwest.net (DogWalker) Date: Tue, 23 Jul 2002 15:29:41 -0700 Subject: What unicode character has a certain value? Message-ID: How would I convert the value of a unicode character to a unicode string; a unicode string to an ascii string (if possible); a unicode character to a decimal number. If I have the decimal value for a unicode character, how do I convert it to a unicode character? A unicode apostrophe has a decimal value of 8217. How do I get a string with an apostrophe starting with 8217? x = 8217 s = ??x From johnroth at ameritech.net Wed Jul 31 16:31:48 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 31 Jul 2002 16:31:48 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> <3d46c6a2$1_1@hpb10302.boi.hp.com> Message-ID: "Huaiyu Zhu" wrote in message news:slrnakgake.6hf.huaiyu at gauss.almadan.ibm.com... > John Roth wrote: > > > >> For vertical scoping, it is not necessary to separate items with > >commas. > > > >Is this valid Python in general, or is this another change to the > >syntax? > > It's just what I think is necessary. I'm not sure if it fits the > current python parser, although it appears to be so for existing > structures like def, class, if, while. It certainly looks nice, but I think it's a change to the syntax for list and dictionary constructors, which is a different issue. John Roth > > Huaiyu From oooooo at beeb.net Sun Jul 28 15:04:52 2002 From: oooooo at beeb.net (rmschne) Date: Sun, 28 Jul 2002 19:04:52 +0000 (UTC) Subject: Help! Python to compare dates in diff. timezones References: <8f8ffe67.0207280817.6fc327b8@posting.google.com> Message-ID: <3D4430F4.5040005@beeb.net> Sunit, I would recommend you do the following. 1. confirm the system date each site is running on the relevant machine. 2. confirm the times in the database match what you expect from 1 (I say steps 1 and 2 above as I was once caught out by what I thought were two different time-zoned machines, but in fact both were set for GMT). 3. along those lines, consider setting both machines to GMT or some common time. 4. Ensure you keep both machines in synch with each other re time, or at least to a common standard. You recognize that both machines could be set for a different time zone, but you also ought to control the drift that inevitably will occur. 5. In your Python script, simply have a variable which records the time zone of each site, and then write a function that does the arithmetic (adding or subtracting hours) to suit your needs. Doing steps 1-4 enables a program in step 5 to work. rms Sunit Joshi wrote: > Hello All > > I have problem which is like this: > I have two sites A & B which are in diff. countries in diff. > timezones. > Now both sites have same drawings (Microstation files with same names) > whose revision dates (as integer since epoch) are stored in a table in > database at both sites. The database structure is same on both sites > with identical table names. > > Now since the sites are different timezones, I was wondering what > would be the best way to compare drawings, using Python, that have > changed between two sites; for e.g. if site A wants to gets a list of > all models that have changed at site A. > > I'm open to any suggestion like using a query over HTTP, using XML, > etc. > > thanks > Sunit > sunitjoshi at netzero.net From gtaylor at lowebroadway.com Wed Jul 10 05:59:52 2002 From: gtaylor at lowebroadway.com (Garry Taylor) Date: 10 Jul 2002 02:59:52 -0700 Subject: Multi-threading on Multi-CPU machines References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > Garry Taylor wrote: > > > >I am attempting to make a multi-threading function in one of my > >programs in an effort to gain a speed increase, but I'm getting quite > >the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten > >me as to why, my code is below: > > Pure Python code will always slow down when threaded; in order to gain a > speedup, you must call an extension that releases the GIL. All I/O > functions in Python release the GIL, for example. For more info, see > the slides on my home page. Thanks to those who replied, I think releasing the GIL would appear to be my best bet, as I don't want to add yet another dependency to the program, i.e. MPI and PyPar, also by 'Shared Memory' I take it you mean NUMAFlex machines and similar rather than a little 2x1GHz P4 Dell Server? The kind of machines my program will run on will max out at 4 way, I would expect, and it's not math-intensive or anything, I just want to speed up fairly average tasks, which only take around 10 seconds on a single processor. Thanks again Garry From tool_man at spamcop.net Wed Jul 24 11:34:19 2002 From: tool_man at spamcop.net (Tim Lavoie) Date: Wed, 24 Jul 2002 15:34:19 GMT Subject: Numeric data question References: Message-ID: <%Nz%8.15893$A72.86385@news1.mts.net> In article , terry wrote: > > I'm a Python newby, but I have read several books, documentation, > and email list archives, and I have not found a direct reference > to how money calculations can be handled in Python. > Specifically, I'ld like to use a Postgres (or any database) > numeric data column that represents money with 'normal' Python > math operators. I am *very* aware of the floating point > problems, and know that I must avoid even using floating point > for accounting applications. > > Would someone kindly either give me a short explaination or point > me toward an information source. > > Thanks in advance, > > terry Well, PostgreSQL does have a money type, but IIRC it's just a float with a fixed number of decimal places. You could just use pennies as the unit and integer math though. -- "The sign said, 'Jesus is the answer.' Which is kinda weird, since my question was 'What the hell's this stuff on my sandwich?'" -- Phil Bacon From mcherm at destiny.com Wed Jul 24 14:16:54 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 24 Jul 2002 14:16:54 -0400 Subject: syntax questions Message-ID: <3D3EEF16.5040404@destiny.com> > I know about the dir() function, but I'm surprised that my list object > hides a function object (even if they have the same name). > Is that how python treats names all the time? Does it mean you can't > have a class, def and variable of the same name? Yes, that's how it works all the time. Actually, the ADVANTAGE of this is that you aren't required to memorize the entire list of all built-in functions and things. For instance, if you NEVER, EVER use the "input" function (as well you shouldn't), then it's not going to hurt you if you use a line like: for input in sys.stdin: process(input) Of course, it's still not a good idea, but you aren't forced to memorize the list of built-in stuff, nor does old code break when a new built-in function is added (which happens rarely, but does happen). As for having a class, a "def" (ie, function), and a variable all with the same name, no... not in the same namespace. And this is good. Because in Python (unlike some languages), a function, a class, and a "variable", are all objects, and can be used interchangably. Consider the map() function. It is normally passed a function as its first argument and applies it to the items in a list: >>> def add5(x): return x + 5 >>> map( add5, range(4) ) [5, 6, 7, 8] But classes are instantiated by calling them, as if they were functions. So we can pass a class in, where it expects a function, and it all works just fine: >>> from UserString import UserString >>> map( UserString, range(4) ) ['0', '1', '2', '3'] We could even use a variable to store the item to pass... resulting in code like this: >>> f1 = add5 >>> f2 = UserString >>> [ map(f, range(4)) for f in f1, f2] [[5, 6, 7, 8], ['0', '1', '2', '3']] So the fact that all things are just "objects" and don't have separate namespaces is highly useful, since it comes closer to making "everything" first class objects, giving the language more power. -- Michael Chermside From list-python at ccraig.org Mon Jul 1 16:15:02 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 01 Jul 2002 16:15:02 -0400 Subject: private In-Reply-To: References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "James Kew" writes: > "Peter Hansen" wrote in message > news:3D1DE132.4A890D9D at engcorp.com... > > Rhymes wrote: > > > > > > Is there any possibility to build up a _real_ private attribute? > > > Such as C++ private data members... > > > > You realize that it's quite possible to get at private data members > > in C++, don't you? > > I can't help feeling this is overly dismissive! > > Yes, of course one can circumvent private in C++. But for me the main value > of the public and private specifiers is that they _document_ to the client > of the class what it should access and what it should not. I would think docstrings, comments, and naming conventions sufficient to provide a method for documenting what a class ought to be accessing. -- Christopher A. Craig "The shortest distance between two points is usually torn up." Frank Walsh From aleax at aleax.it Fri Jul 5 17:23:26 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 21:23:26 GMT Subject: XML content in a POST request (httplib)? References: <9e495aef.0207051255.3d10a628@posting.google.com> Message-ID: Gordian Gossen wrote: > Hello, > > I would like to transmit the content of a XML-file in the body of a > POST request. > > ------------------------------------------------------------- > What i did not understand: > -------------------------- > > How to put the a string, which contains the XML content, into the body > without making a key value pair? > > Does I need a key value /pair to transmit data in the POST request > body? urllib currently lets you to post only content type x-www-form-urlencoded. /F once posted a simple patch to overcome that, http://mail.python.org/pipermail/patches/2000-April/000493.html -- you may try to work things out from there (I don't think it was ever integrated in the standard library). Or, use different means than urllib -- httplib lets you do that easily (method 'request' of HTTPConnection instances). Alex From SRowland at BIOCRYST.com Fri Jul 26 11:33:28 2002 From: SRowland at BIOCRYST.com (Rowland, Scott) Date: Fri, 26 Jul 2002 09:33:28 -0600 Subject: Python in Biotech Message-ID: A reference to Python appears in a recent article on Open Source in the biotech industry. http://www.bio-itworld.com/archive/071102/source.html R. Scott Rowland, Ph.D. Director of Molecular Modeling BioCryst Pharmaceuticals, Inc. 2190 Parkway Lake Drive Hoover, AL 35244 http://www.biocryst.com From gerhard.haering at gmx.de Sun Jul 28 21:47:30 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 29 Jul 2002 03:47:30 +0200 Subject: conditional importing In-Reply-To: References: Message-ID: <20020729014729.GA2740@lilith.my-fqdn.de> * Scott Hathaway [2002-07-28 20:29 -0500]: > How can I do a conditional import? I am creating a database wrapper class > that is similar to adodb in PHP. > I have the following class: > > >from mx.ODBC import Windows as db1 > import MySQLdb as db2 Better use something like: module_name = "MySQLdb" try: dbmodule = __import__(module_name) except ImportError, reason: # error handling here def open_connection(*args, **kwargs): return dbmodule.connect(*args, **kwargs) Unfortunately, the arguments for the connect method aren't standardized. But at least some modules allow for a single connection string where the arguments (host, user, passwd, ...) are separated by colons. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mhuening at zedat.fu-berlin.de Tue Jul 30 04:35:49 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 30 Jul 2002 08:35:49 GMT Subject: Pmw.MenuBar hotkeys References: Message-ID: Martin Franklin wrote in news:mailman.1027968050.16442.python-list at python.org: > On Monday 29 Jul 2002 6:23 pm, Matthias Huening wrote: >> Hi, >> >> I seem unable to get the hotkeys to work with Pmw.MenuBar. >> They should be activated with +hotkey, but nothing happens... >> When a menu is opened, the hotkeys of the different menu items do >> work. The problem is only with the hotkeys on the menu bar. Any >> ideas? >> >> Matthias > > Matthias, > > Have you got a small example? I think I've had these working..... > Okay, here is a minimal example. (By the way: WinXP, Python 2.1, Pmw 0.8.5) Matthias ######## import Pmw root = Pmw.initialise() def my_func(): print 'Something happend' menubar = Pmw.MenuBar(root, hull_borderwidth = 0, hotkeys=1) menubar.pack() menubar.addmenu('File', 'Simple Commands') menubar.addmenuitem('File', 'command', label='One', command=my_func) menubar.addmenuitem('File', 'command', label ='Two', command=my_func) root.mainloop() ######## From sholden at holdenweb.com Fri Jul 26 10:19:40 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 26 Jul 2002 10:19:40 -0400 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> Message-ID: "Dale Strickland-Clark" wrote in message news:05a2ku0canlcg4a3t3cuck7q9cqlrntu46 at 4ax.com... > I've not done any research into this yet so I could have this > completely about my ears. > > We need to do some basic authentication to control access to some > resources through HTTP. > > As I understand it, challenge/response works thus: > > 1. client prompts server to connect. > 2. server invents a random string. > 3. server sends random string to client. > 4. client produces SHA/MD5 digest of random string > 5. client updates digest with password producing client digest > 6. client sends client digest to server with userid > 7. server looks up client password > 8. server produces SHA/MD5 digest of random string > 9. server updates digest with client password producing authentic > digest > 9. server compares client digest with authentic digest > 10. if matched client is authenticated. > > Can anyone see any holes in this and does anyone have any experience > of such a scheme? Is there anything we should look out for? > > I'm planning to use the MD5 module for the digests. > Dale: You should be careful about terminology here, since the wording you currently use conflicts with standard terms in the HTTP lexicon. There are currently three well-known authentication schemes: Basic: "user:pass" is sent as the Base64-encoded content of the "Authorization" (?) header. Challenge/response (Internet Explorer only, AFAIK): the server issues a challenge, the client uses the username/password to mangle the challenge, the server confirms it would mangle in the same way and thereby authenticates the user. Digest (AFAIK only available on Apache, no browser implementations): something much more open and secure than challenge/response. Tim Hammerquist's posting puts you straight on the details. If you get digest authentication working it would be neat to retrofit it to the library. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From rs at onsitetech.com Tue Jul 9 17:09:34 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 21:09:34 GMT Subject: Why self? References: Message-ID: <3D2B50BA.3090102@onsitetech.com> Rich Harkins wrote: > ...This would happen in Java/C++ too... (Speaking for Java) Umm, not unintentionally; > ...Calling Y().pa() would return "hello, world", just like Python. So this seems > to me a problem of general polymorphism rather than Python... I disagree! > ...Java/C++ have the same problem with instance variables too that aren't > declared private (private is spelled __ in Python)... How I see it is that this _isn't_ a "problem" in Java, because the standard idiom is for instance variables to be private. (Or even the default protection, which is less than public, and generally accessible only by those who have access to the source code - ie. you've already forgone black box programming.) But sticking with methods: Having a public method in Java (esp. one that's not "final") shouts, "Please use me from your client classes! And feel free to override me!" And this public method is clearly documented by the standard Java tools. But most methods aren't public; Mine are always private - and there is never the problem described above. Robb From mdehoon at ims.u-tokyo.ac.jp Sat Jul 27 13:33:38 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Sun, 28 Jul 2002 02:33:38 +0900 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> <3D4263E7.3000107@ims.u-tokyo.ac.jp> Message-ID: <3D42D972.2060607@ims.u-tokyo.ac.jp> Sorry ... it seems that distutils ignores the CC environment variable (see below). This was done on cygwin. On Unix, the CC variable was also ignored using setenv CC gcc, and also with set CC=gcc. Here distutils defaulted to the standard cc compiler. I am guessing that it took the compiler name from the Makefile in /lib/python2.2/config. Any ideas? Thanks a lot for your help. --Michiel. $ export CC=bcc32 mdehoon at GINSENG ~/Software/Cluster $ echo $CC bcc32 mdehoon at GINSENG ~/Software/Cluster $ bcc32 Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland mdehoon at GINSENG ~/Software/Cluster $ python setup.py build running build running build_py creating build creating build/lib.cygwin-1.3.12-i686-2.2 creating build/lib.cygwin-1.3.12-i686-2.2/Pycluster copying Pycluster/__init__.py -> build/lib.cygwin-1.3.12-i686-2.2/Pycluster running build_ext building 'Pycluster.cluster' extension creating build/temp.cygwin-1.3.12-i686-2.2 gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DUSE_DL_IMPORT -Iranlib/src -I/usr/include/python2.2 -c cluster.c -o build/temp.cygwin-1.3.12-i686-2.2/cluster.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DUSE_DL_IMPORT -Iranlib/src -I/usr/include/python2.2 -c clustermodule.c -o build/temp.cygwin-1.3.12-i686-2.2/clustermodule.o ... and so on Martin v. Loewis wrote: > Michiel Jan Laurens de Hoon writes: > > >>Thanks for your reply. I am having some difficulties setting the CC >>environment variable, probably due to some peculiarities of our Unix >>system. But if I solve that and set CC=gcc, would distutils know about >>it? >> > > Yes, they use the compiler identified by this variable. > > >>I would think that distutils would choose the compiler options for >>the regular cc compiler, but substitute gcc for CC when the actual >>compilation starts, thus ending up with the wrong compiler >>options. Or am I missing something here? Does distutils check for >>the CC environment variable? >> > > Yes, it does. As for the options: For most purposes, the options of cc > and gcc are identical. In the few places where they differ, distutils > know about the differences. > > Regards, > Martin > > From marklists at mceahern.com Thu Jul 25 14:28:29 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 25 Jul 2002 13:28:29 -0500 Subject: if(debug), optimized away? In-Reply-To: Message-ID: # foo.py if __debug__: print "foo" print "bar" $ python -O foo.py bar // m From hellprout at yahoo.com Tue Jul 23 03:42:17 2002 From: hellprout at yahoo.com (hellprout) Date: 23 Jul 2002 00:42:17 -0700 Subject: pythonwin and Siebel Message-ID: <5b8834c2.0207222342.65953151@posting.google.com> Hi i'm french i'm working on siebel , i just want to use siebel to do update . But i want to use win32client module i have this code import win32com.client import os.path , os objSiebel = win32com.client.Dispatch("SiebelDataServer.ApplicationObject") print objSiebel err = 0 conf = "d:\\seaV1_1\\client\\bin\\Siebel_CSE-SFA_IA_V1_1_Local.cfg" if os.path.exists(conf): err = objSiebel.LoadObject(conf) there is an error with loadobject what can i do to pass this and use the siebel connection ? thanks a lot nicolas From paiarunk at yahoo.com Thu Jul 18 11:00:48 2002 From: paiarunk at yahoo.com (Arun KUmar) Date: 18 Jul 2002 08:00:48 -0700 Subject: Linkedlist structure giving segmentation fault Message-ID: <5e430dc.0207180700.6f5275bf@posting.google.com> hai, I a just writing a application in python, where i need to use some third party shared library, which consists of structures and linkedlists in c, now i need to call the function calls of the shared library, using the linkedlist structure, but when ever i call this and compile it with swig and run the python script, i get an segmentation fault error. what could be problem? how to use linkedlist pointers and malloc etc in swig, do i need to do some changes in my code for swig? please help me. arun From Gabe.Newcomb at noetix.com Fri Jul 19 14:03:45 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Fri, 19 Jul 2002 11:03:45 -0700 Subject: newby's tut for tkinter? Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F60DB@NOXMAIL.noetixad.com> Check out: http://www.python.org/topics/tkinter/doc.html specifically, Fredrik Lundh has an intro near the top of the page. Gabe -----Original Message----- From: netvegetable [mailto:deathtospam43423 at altavista.com] Sent: Friday, July 19, 2002 10:39 AM To: python-list at python.org Subject: newby's tut for tkinter? Is there a nice simple tut for newby programmers to learn Tkinter? If not, is there any chance of somebody clever writing one? -- netvegetable at excite.com -- http://mail.python.org/mailman/listinfo/python-list From lars at gustaebel.de Wed Jul 31 10:11:02 2002 From: lars at gustaebel.de (Lars Gustäbel) Date: Wed, 31 Jul 2002 16:11:02 +0200 Subject: tarfile.py question References: <3d41619d$1_2@nopics.sjc> Message-ID: Adonis wrote: > x = tarfile.TarFile(sys.argv[1], 'r') This will work: x = tarfile.gzopen(sys.argv[1], 'r') The TarFile class works only for uncompressed tar archive files. Whenever you want to open or create a gzipped tar, you have to use tarfile.gzopen(). I should have mentioned this a little more clearly in the docs. > i attempted to read a tar.gz file (gadfly) and when i load it no error is > posted nor any information at that, but the m variable is an empty list, > and if i attempted to do x.list() to get a list of files it returns None, > although it seems that it loaded the tar file properly no IOError was > generated, is there something i am missing? i have tested this by generating > a tar.gz file using the same module and it unpacked properly. With the next release, there will be a debug message for this case. BTW, x.list() prints out the contents of an archive as a directory listing, so it'll always return None. Hope this was helpful. -- Lars Gust?bel lars at gustaebel.de From mwh at python.net Tue Jul 23 11:20:24 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 23 Jul 2002 15:20:24 GMT Subject: curses and terminal resize References: <3D3D61D1.8010600@pp.htv.fi> Message-ID: janne halttunen writes: > Hello all, > > I am writing a curses widget library. The trouble I am having is to > obtain new values for lines and columns in terminal after resize > event. I have a short program below that should demostrate the problem: [...] > Any help is appreciated, Does this: http://groups.google.com/groups?selm=uk7xtwasm.fsf%40python.net help? Cheers, M. -- ZAPHOD: You know what I'm thinking? FORD: No. ZAPHOD: Neither do I. Frightening isn't it? -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From alexandrecourbot at linuxgames.com Mon Jul 22 17:30:24 2002 From: alexandrecourbot at linuxgames.com (Alexandre Courbot) Date: Mon, 22 Jul 2002 23:30:24 +0200 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: <7xfzybii29.fsf@ruckus.brouhaha.com> References: <7xfzybii29.fsf@ruckus.brouhaha.com> Message-ID: <20020722233024.5bec8f5f.alexandrecourbot@linuxgames.com> > Tim Peters writes: > > Python used to use float arithmetic to detect int mult overflow, but > > that didn't work correctly on some 64-bit boxes. > > > > It got replaced by over 100(!) lines of all-integer int mult > > overflow-checking code, and I believe that's still in 2.1.3. > > > > But that had an obscure endcase bug too, and it get replaced in 2.2 > > by a new float method that doesn't make unwarranted assumptions > > about the relative sizes of C longs and C doubles, and usually gets > > out quickly -- provided float arithmetic isn't pig slow. > > Ouch!! That doesn't sound so good for the Zaurus. Yeah, I wonder if it's worth to profile the stuff! :) Guys, I'll first test it with Python 2.1.3. Adonthell (the game I'm porting) works with any Python >= 1.5.2, so if the problem can be solved in the short-term by regressing to 2.1, that'll be fine for now. If the differences are significant, then maybe we could consider to add another interger-only checking method that would suit in the case of Arm processors. I'll try to give you news about it tomorrow. Thanks again for the relevant answers! Alex. -- http://www.gnurou.org From shagshag13 at yahoo.fr Tue Jul 30 05:49:36 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 30 Jul 2002 11:49:36 +0200 Subject: signature for a file ? Message-ID: Hello, i would like to have your opinion on this... i had at home many hdds, that could contain many time same files, in many places/directories (-> i'm really disorganized). i would like to do some sort on theses files. to do this i'm planning to write a python script that would compute a kind of CRC32, MD5 or SHA (i'm really not competent in that - so here i need advices and pointer to some implementations - and to know which is the best to had a unique unambiguous signature for a file) and then use it to find "doubles" : same size + same signature = probably same file. (i'm in no way concerned by the time that will need - less than a week ;o) -, this should always be much less than if i had to it myself) (another question is in a system how to know how many disks/mounting points are available ) do you think this could work ? have you any other/best suggestion ? thanks in advance, s13. From adam12 at scn.org Tue Jul 2 21:11:09 2002 From: adam12 at scn.org (adam griffin) Date: Tue, 02 Jul 2002 18:11:09 -0700 Subject: what can i expect... References: Message-ID: <20020702.181107.1129566413.856@scn.org> In article , "Shagshag13" wrote: > what can i expect if i change my python application to java ? it will be harder to read From beej at piratehaven.org Wed Jul 3 18:51:31 2002 From: beej at piratehaven.org (Beej Jørgensen) Date: 3 Jul 2002 22:51:31 GMT Subject: REPEAT... UNTIL ? References: Message-ID: In article , Gustavo Cordova wrote: >would be exactly the same as: > >""" >while 1: > ... > ... > ... > if bexpr: break >""" > >no? Sigh. It's the age-old issue. More looping primitives, or fewer? I always wanted more, but people would argue against me that the same thing can be done with a normal while loop. Well, of course it can. In fact, all the loops can be reduced to one statement, a la: loop: if cond: break But not even the purists will go that far. But as the language ages, it becomes more and more set in stone. Backward compatibility will certainly be trashed if a do-while loop is introduced, so it's not an issue to take lightly. (The other side of the coin is that my only argument for more looping primitives is that while-1 loops are ugly-looking, and don't make for the most readable code. Some people disagree or feel it's less important. And personally I always feel like I'm undergoing some kind of algorithmic failure when I code one; like I must not be doing the Right Thing. But in Python, it is.) It's not really even worth arguing about at this point unless you can come up with the killer app for do-while loops. The battle lines are clear, and either someday it'll be added, or it won't. -Beej From pinard at iro.umontreal.ca Thu Jul 18 10:48:49 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 18 Jul 2002 10:48:49 -0400 Subject: property problem In-Reply-To: <3D36C65A.5040300@mplusr.de> References: <3D36C65A.5040300@mplusr.de> Message-ID: [Peter Maas] > while experimenting with class properties using Python 2.2.1 > I encountered the following weird behaviour: [...] This is documented. To use properties, you need new-style classes. I guess you may change "class proptest:" by "class proptest(object):". -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From m.faassen at vet.uu.nl Mon Jul 22 09:46:44 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 22 Jul 2002 13:46:44 GMT Subject: Alex Martelli is off the net for a few days :-( References: <3d3c0738.271278796@news.skynet.be> Message-ID: pixie888 at hotmail.com wrote: > Very of the shelf question: > Martijn, > have you been at the ETH in Zuerich somewhere around 1994/1995? I haven't been there in 1994/1995 *yet*, pending any visits to the past using a time machine. Why in the world this question? (by the way, your email address doesn't seem to be working) Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From joconnor at cybermesa.com Tue Jul 23 19:49:41 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 24 Jul 2002 06:49:41 +0700 Subject: Distributed Python Message-ID: <20020724.064941.722308542.1589@cybermesa.com> A while back, as part of a code sample I submitted for a job, I developed a basic framework for distributed Python. This is a tool that allows one Python application to communicate with another, whether on the same machine or on remote machine(s) Being that it was just a sample, I never fully fleshed it out. I've been contemplating developing it further but first I was wondering if such a tool would be of interest to anyone else -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From opengeometry at NOSPAM.yahoo.ca Wed Jul 10 01:43:17 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 10 Jul 2002 05:43:17 GMT Subject: How to grab a part of web page? References: Message-ID: Gerhard H?ring wrote: >> I think it's possible. When I use 'wget -c' to download HTML, sometimes >> I see it start from an offset, rather than from the beginning. > > Doing this while having a packet sniffer running showed me what the > corresponding HTTP header is. >From the docs that I came across, HTTP/1.1: - "Range" header in request - "multipart/byteranges" type in the response Older HTTP: - "Request-Range" header - "multipart/x-byteranges" type but the exact syntax I don't remember. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From barry at zope.com Thu Jul 11 15:46:35 2002 From: barry at zope.com (Barry A. Warsaw) Date: Thu, 11 Jul 2002 15:46:35 -0400 Subject: RELEASED Mailman 2.0.12 Message-ID: <15661.57499.452598.614499@anthem.wooz.org> I've released version 2.0.12 of Mailman, the GNU Mailing List Manager. Mailman is released under the GNU General Public License (GPL). Version 2.0.12 fixes a cross-site scripting vulnerability among other changes. I recommend that folks upgrade their 2.0.x systems to this new version. See below for a NEWS file excerpt. GNU Mailman is software to help manage electronic mail discussion lists. Mailman gives each mailing list a unique web page and allows users to subscribe, unsubscribe, and change their account options over the web. Even the list manager can administer his or her list entirely via the web. Mailman has most of the features that people want in a mailing list management system, including built-in archiving, mail-to-news gateways, spam filters, bounce detection, digest delivery, and so on. Mailman is compatible with most web servers, web browsers, and mail servers. It runs on any Unix-like operating system. Mailman 2.0.11 requires Python 1.5.2 or newer. To install Mailman from source, you will need a C compiler. For more information on Mailman, including links to file downloads, please see any of the Mailman mirror web pages: http://www.gnu.org/software/mailman http://mailman.sourceforge.net http://www.list.org Patches and source tarballs are available at http://sourceforge.net/project/showfiles.php?group_id=103 There are email lists (managed by Mailman, of course!) for both Mailman users and developers. See the web sites above for details. Cheers, -Barry -------------------- snip snip -------------------- 2.0.12 (02-Jul-2002) - Implemented a guard against some reply loops and 'bot subscription attacks. Specifically, if a message to -request has a Precedence: bulk (or list, or junk) header, the command is ignored. Well-behaved 'bots should always include such a header. - Changes to the configure script so that you can pass in the mail host and web host by setting the environment variables MAILHOST and WWWHOST respectively. configure will also exit if it can't figure out these values (usually due to broken dns). - Closed another minor cross-site scripting vulnerability. From mdehoon at ims.u-tokyo.ac.jp Mon Jul 29 11:50:39 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Tue, 30 Jul 2002 00:50:39 +0900 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> <3D4263E7.3000107@ims.u-tokyo.ac.jp> <3D42D972.2060607@ims.u-tokyo.ac.jp> Message-ID: <3D45644F.1000900@ims.u-tokyo.ac.jp> > Perhaps you didn't set the variable correctly? > > Regards, > Martin > I tried 'set CC=gcc', and also 'setenv CC gcc', on the Unix system. In both cases, distutils ends up using cc anyway. This is with tcsh. On my Unix system, there is a file called CC in /usr/bin that is a link to a compiler. Could that be interfering with distutils? I would guess that CC and $CC are different to distutils, and therefore the CC link would not cause problems. If it does, I'll try to convince my system administrator to remove the link. --Michiel. Martin v. L?wis wrote: > Michiel Jan Laurens de Hoon writes: > > >>Sorry ... it seems that distutils ignores the CC environment variable >>(see below). This was done on cygwin. On Unix, the CC variable was >>also ignored using setenv CC gcc, and also with set CC=gcc. Here >>distutils defaulted to the standard cc compiler. I am guessing that it >>took the compiler name from the Makefile in /lib/python2.2/config. >>Any ideas? >> > > You can't take your Windows run as a proof that the variable is > ignored. On Unix, it is honored. > > Regards, > Martin > > From claird at starbase.neosoft.com Mon Jul 1 11:56:32 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 1 Jul 2002 10:56:32 -0500 Subject: Pyrhon language dedicated Wiki References: Message-ID: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> In article , Kerim Borchaev wrote: >Hello there. > > It seems to me that C.l.py is too overloaded today. > Wouldn't it be nice if someone(not me - I think I don't have > resources for it) bothered to setup a wiki for discussion about python language? . . . I've been considering it. If I hear enthusiasm, I'm more likely to do so; if anyone else wants the privi- lege, I'm less likely. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From eggy at island.net Sat Jul 13 18:36:11 2002 From: eggy at island.net (Alex Eggenberger) Date: 13 Jul 2002 15:36:11 -0700 Subject: select.select for non-sockets in win2k Message-ID: <930dfcf0.0207131436.153edc47@posting.google.com> Is there still no select.select function that works with non-sockets like the object returned by os.popen()? If not, is there a way of displaying the stdout/stderr data as it becomes available from os.popen3() calls? To clarify, I want to do something like stdin, stdouterr = os.popen4("SomeCommand") KeepPolling = 1 while KeepPolling: ThisPoll = select.select([stdouterr],[],[],1) str = stdouterr.readline() if re.search(EOF,str): KeepPolling = 0 else: print str The intent is to print new data as it appears in the stdouterr pipe. Last time I attempted to do this sort of thing I was stumped because select.select() would simply could not accept the stdouterr pipe. Is this still the case? Is there another way of approaching this problem? From pinard at iro.umontreal.ca Wed Jul 10 06:57:12 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 10 Jul 2002 06:57:12 -0400 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: References: <96c7f32.0207091153.7b2484be@posting.google.com> Message-ID: [Alex Martelli] > > PS. The notion that competitor would try to attack product by > > attacking invisible-to-user implementation language strikes me as > > bizarre. Reeks of desperation. > It does in fact happen quite often -- a technology used in the > making of a product is targeted for 'for' or 'against' marketing, > rather than user-visible aspects of the product. I've also seen it in the field of musical instrument builders, and it surprised me at the time, especially from otherwise respectable firms. Competition may become an horrible thing. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From fredrik at pythonware.com Wed Jul 24 12:56:07 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 24 Jul 2002 16:56:07 GMT Subject: syntax questions References: Message-ID: Philippe Gendreau wrote: > I'm fairly new to python and there a thing I don't understand in the > syntax. What is it with the "_". I have seen it used in many places for > what seems to be different puposes like: > > from x import _ here, you're importing something named "_" (most likely a function) from the x module. judging from your example, the "_" function is probably used to translate strings from english to the local language. for some reason, people doing internationalization (i18n) and localization (l10n) stuff seem to prefer to use functions called "_", probably only to confuse people like you and me. > Also, I'd like to understand this syntax: "((_(name),))" the _(name) part is simply a call to the translation function. it could have been written like, say local_name = _(name) or even local_name = translate(name) the (x,) part creates a tuple containing a single item (see the tutorial and the language reference for more info on tuples). a_tuple = (local_name,) the outermost () belongs to the append method call: theme.append(a_tuple) (according to the python style guide, and common sense, it's bad style to put a space between the function/method name and the parentheses...) From mwh at python.net Thu Jul 18 05:51:05 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Jul 2002 09:51:05 GMT Subject: Python 2.2.1 Build Trouble References: Message-ID: "Peter Chiu" writes: > Hi, > > I tried to build python-2.2.1 on an AlphaServer running Tru64 Unix 5.1a. Hmm, I thought that worked. > The .configure process went through okay, but make failed with error: > > gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_ > H -c ./Modules/posixmodule.c -o Modules/posixmodule.o > > Modules/posixmodule.c: In function `posix_stat': > > Modules/posixmodule.c:1310: `stat' undeclared (first use in this function) > > Modules/posixmodule.c:1310: (Each undeclared identifier is reported only > once > > Modules/posixmodule.c:1310: for each function it appears in.) > > Modules/posixmodule.c: In function `posix_plock': > > Modules/posixmodule.c:2227: warning: implicit declaration of function > `plock' > > Modules/posixmodule.c: In function `posix_lstat': > > Modules/posixmodule.c:3380: `lstat' undeclared (first use in this function) > > Modules/posixmodule.c: In function `posix_unsetenv': > > Modules/posixmodule.c:4118: warning: implicit declaration of function > `unsetenv' > > make: *** [Modules/posixmodule.o] Error 1 Well, looks like some header isn't getting #include-d, I guess because configure is somehow guessing wrong. stat not being declared is a bit surprising. Probably the easiest thing to do is hack Modules/posixmodule.c to #include the right headers by hand. The worthy thing to do is figure out why configure got this wrong -- but that may be massively tedious. Cheers, M. -- I really hope there's a catastrophic bug insome future e-mail program where if you try and send an attachment it cancels your ISP account, deletes your harddrive, and pisses in your coffee -- Adam Rixey From tmcnerney at truis.com Tue Jul 30 10:08:41 2002 From: tmcnerney at truis.com (Tim McNerney) Date: 30 Jul 2002 14:08:41 GMT Subject: Finding count of currently open file descriptors. Message-ID: <3D469D2F.6010003@truis.com> How do I go about finding out the number of file descriptors currently open in a program? I'm trying to track down a file descriptor leak which may or may not be in library calls. Will I run into problems getting an accurate count due to the possible delay between doing a close and GC? Thanks. --Tim From cliechti at gmx.net Wed Jul 24 02:33:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 08:33:05 +0200 Subject: Adding Modules to precompiled installation of Python References: Message-ID: "Jayant Kulkarni" wrote in news:ahkqsd$r2b$1 at news01.cit.cornell.edu: > "Chris Liechti" wrote in message > news:Xns9254A000DE623cliechtigmxnet at 62.2.16.82... >> "Jayant Kulkarni" wrote in >> news:ahiii8$4u2$1 at news01.cit.cornell.edu: >> >> > I am using the finite-element package Abaqus which comes with >> > precompiled Python (ver 1.5). I want to interface this with Matlab >> > using Pymat. (PyMat utility by Sterian). The problem is that as the >> > python is precompiled I do not know how to import new modules.. >> > > I changed the PYTHONPATH so that it > points > to the pymat.pyd file. I then tried > >>> import PyMat > And I get the following error: > ImportError: dynamic module does not define init function (initPyMat) > so this DLL isn't for python. maybe its for the matlab side. > If I try > >>> import pymat > I get the error: > Fatal Python error: PyThreadState_Get: no current thread this looks like a python extension. the error could mean that your precompiled python was built without threads, but i don't realy know. maybe someone else can jump in. chris -- Chris From phr-n2002b at NOSPAMnightsong.com Fri Jul 19 03:27:33 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 19 Jul 2002 00:27:33 -0700 Subject: Recursion References: Message-ID: <7xd6tk6uu2.fsf@ruckus.brouhaha.com> Abhijit Soman writes: > In the recursive function below i want to add the individual bits to a > string and return that string to the caller > Can anyone tell me how to do that > > > def showbits(x): > if x != 1: > showbits(x >> 1) > if x & 01: > print 1, > else: > print 0, I think the most direct translation is: def showbits(x): r = '' if x != 1: r = showbits(x >> 1) if x & 01: r = r + '1 ' else: r = r + '0 ' return r From mhammond at skippinet.com.au Wed Jul 10 20:23:27 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 11 Jul 2002 00:23:27 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: <3D2CD0D2.9080908@skippinet.com.au> Tim Daneliuk wrote: > Matthias Huening wrote: > >> Tim Daneliuk wrote in >> news:qmqgga.g31.ln at eskimo.tundraware.com: >> >>> Does some kind soul out there happen to have a pointer to a >>> tutorial/examples on fiddling with the Win32 registry from PythonWin? >>> >> >> >> There is a module called pyRegistry. Can't find the url right now, but >> you can get it from ActivState: >> http://aspn.activestate.com/ASPN/Modules/Python/dist_html?dist_id=11218 >> >> Matthias > > > Is there some advantage to this module over the standard _winreg module? Not really - but _winreg is newer and therefore may not be in the Python version used by the OP, or he may be choosing to target earlier Python versions for his app, etc. But you are correct - new code should use _winreg over win32api. Mark. From prema at prema.co.nz Thu Jul 18 04:06:35 2002 From: prema at prema.co.nz (Mike MacDonald) Date: Thu, 18 Jul 2002 08:06:35 GMT Subject: Pmw Inconsistencies -- Any ideas ?? Message-ID: I'm wanting to use Pmw for a small project. I notice that sometimes I can't initialise Pmw. I've posted some sample code below. Is there something I'm missing around PYTHONPATH? I reinstalled and it was OK for a while. OS is Win2K but I've noticed this on other OS's as well Very grateful for any comments Thanks in advance Mike Sample Code ================================= import Pmw ##class Gui: ## def __init__(self,parent): ## self.parent=parent ## ## NB=Pmw.NoteBook(self.parent) ## NB.pack(side='left') ## ## for count in range(5): ## NB.add('Test Label'+str(count)) root=Pmw.initialise() if __name__=='__main__': root.title('Test PMW') Gui(root) root.mainloop ## ##Error message: ## Traceback (most recent call last): ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 1, in ? ## import Pmw ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 11, in ? ## root=Pmw.initialise() From val at vtek.com Wed Jul 3 12:07:30 2002 From: val at vtek.com (val) Date: Wed, 3 Jul 2002 12:07:30 -0400 Subject: pipes.py and its limits Message-ID: Oren and All, Oren you are great. First, coz you are here to help when one needs it. Thanx. (This is the Fantastic List, nothing like that in the whole world) I spent a couple of weeks torturing the poor google trying to locate your 'flows' (i had a fuzzy idea that they exist, i tried pipeline, meta, sequence, etc but never flows..) Anyway, i'm going to follow your pointers and study all that material. thank you very much, val ----- Original Message ----- From: "Oren Tirosh" Newsgroups: comp.lang.python Sent: Wednesday, July 03, 2002 10:10 AM Subject: Re: pipes.py and its limits > On Wed, Jul 03, 2002 at 09:52:05AM -0400, val wrote: > > Hi All, > > i'm looking at pipes.py, a great pipeline implementation > > in python (BTW, who is the author?), and trying to figure > > out its limits. The description says that the commands > > to be appended to the pipeline template have to be > > shell functions. I'd like to try to build the dynamic pipelines > > using the python functions or callable objects. > > > > In other words, i'd like to modify the pipeline - > > its functional components on-the-fly depending on > > the results of running the pipeline (its output). > > > > I'm sure the real Pythoneers know how to do that. > > Any pointers/help would be highly appreciated. > > Take a look at http://tothink.com/python/dataflow for a library that > implements pipelines (I call them flows) using Python iterators and > generators. > > I also have a library for intergrating external commands more easily > into Python scripts. http://tothink.com/python/shell > > I'm working on merging the two so it will be possible to create flows > with mixed Python functions and external commands. > > I do not intend to support modification of the flow while it is running > because its elements may be delicate stateful components that have > different input and output rates, buffering, etc. Changing it on the > fly could lose data. But one of the elements in the flow can change its > functionality or even embed a separate flow object inside it if you > want. > > Oren > > From mbec at gemini.edu Tue Jul 30 05:50:52 2002 From: mbec at gemini.edu (Matthieu Bec) Date: 30 Jul 2002 02:50:52 -0700 Subject: condensed syntax? Message-ID: <7d5281ea.0207300150.1fcef017@posting.google.com> is there any way to condense the following: # scan subdir(s) within mydir for d in os.listdir(mydir): dd=os.path.join(mydir,d) if os.path.isdir(dd): self.subdir.append(dd) what follows doesn't work, but I'm thinking of a something like: self.subdir=[(os.path.isdir(dd=os.path.join(mydir,d))?dd:pass) for d in os.listdir(mydir) ] Thanks, Matthieu PS: please fwd. answer to mbec_AT_gemini_DOT_edu as I am not actively monitoring this newsgroup From aleax at aleax.it Sat Jul 20 04:30:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 08:30:13 GMT Subject: Funny behaviour of MySQLdb References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> Message-ID: Heiko Wundram wrote: > Hi List! > > I just tried the single-threaded way, and that works... Hmm... Nothing > apparently different, except that I took out the base class > SocketServer.ThreadingMixIn from the definition of the server class... > > Strange... Not really. Rule of thumb: always ensure a single thread interacts with any given external entity, be it a file, a database, the user, or even a global shared variable subject to updates. Have all other threads make requests to that guardian thread by posting work requests on a Queue; the guardian thread loops getting a request from the Queue, servicing it, returning the results back on another Queue indicated as part of the work request. Note that this is quite simple to program -- Queue's handle their own synchronization needs, so no further locks or whatever are needed. In some cases you can get by with threading a bit freer than this, but -- don't count on it. It's anything BUT surprising if you get anomalies any time two or more threads interact directly with the same entity without a dedicated guardian/mediator thread. Threads are a minefield and it's well worth threading lightly there:-). This is my own opinion, of course, but I expressed it quite strongly in the Threading chapter of the forthcoming Python in a Nutshell, and two threading experts (Aahz and Tim Peters) kindly agreed to review the chapter and give me their opinions about it -- neither objected to the general approach and Aahz in fact especially commended the general suggestion (the same rule of thumb as given in the first paragraph of this post). I suspect I'm in for some flames about this, but I think it's worth the price in order to spread the word. If you are a threading expert, know exactly what you're doing, and are totally familiar with all components involved and their behavior under multihreaded use, go right ahead, you need no advice. For the remaining 99.44% of use, dedicated guardian threads and Queue's to mediate is THE way to maintain sanity when we do have to multithread. One last reminder: event driven processing is often preferable to multithreading... Be sure to check out www.twistedmatrix.com -- I used to be an asyncore/asynchat fan (well, I still AM!), but the current release of twisted.internet and twisted.protocols at least (haven't used the upper layers) is rapidly winning me over. twisted's architecture is just TOO much cleaner, and more elegant and powerful, than asyncore's simple (and still quite effective) one. They both scale better than threading in most cases (you can ALSO mix some threading in, of course -- haven't tried that, but twisted supports it directly -- but I don't think it would be needed ALL that much). There, a bit more fuel for the flames... Alex From rs at onsitetech.com Mon Jul 8 14:41:18 2002 From: rs at onsitetech.com (Robb Shecter) Date: 08 Jul 2002 18:41:18 GMT Subject: Why self? References: Message-ID: <3D29DC83.4020205@onsitetech.com> An even more unreadable example is the coding I had to do in a class that sovled a linear equation and uses the computed values: return self.__m * aNumber + self.__b I'm doing y = mx + b here, and do the variable names 'm' and 'b' are completely reasonable. And here, it's not just the fact that there's 7 extra characters, but that the variable names are now 7 times longer than they could be: return m * aNumber + b Robb From ajw126NO at SPAMyork.ac.uk Wed Jul 31 12:18:18 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Wed, 31 Jul 2002 17:18:18 +0100 Subject: Embedding/API question References: <215127f6.0207301417.65343257@posting.google.com> Message-ID: Can you post some code? That'd make it a lot easier to spot any mistakes. Andrew Wilkinson "Michelle L. Murillo" wrote in message news:215127f6.0207301417.65343257 at posting.google.com... > Hi - I have successfully used PyArg_Parse and > PyInt_AsLong to parse data from python into C. The > data are being returned to C from a python script > that does a look up into a dictionary. I can > successfully return and print out an integer and > a string. But what I can't figure out is how to > get PyArg_Parse (or which ever API works) to > correctly parse a python tuple - that is we > have a value in the dictionary that is in the > form of (8,8,8). If I make this a string all > works fine - but with out the quotes all that > is returned and printed out is garbage. > > Any ideas? > > TIA > Michelle From amuys at shortech.com.au Mon Jul 29 22:45:45 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 29 Jul 2002 19:45:45 -0700 Subject: lexing nested parenthesis References: Message-ID: <7934d084.0207291845.41ad81e9@posting.google.com> Dave Cinege wrote in message news:... > It's nice when you open up your reference book, and immediately > find a section on what you want to do. > > It sucks large donkey rocks when that section is titled: > "Difficulties and Impossiblies" (Mastering Regular Expressions) > > I've been playing with shlex, and think in my application I'm > better off minimizing or avoiding it. > > Primarily I want to do search, evaluate, modify, and replace > on a line by line basis. The diffculty comes with matching > arbitrary nested constructs, IE nested parenthesis. > > IE > if 1 and (var1 or ?(-d /etc/)): Congratulations, you've just discovered the classic example of a pattern that regexes can't match no matter how hard you try[0] :). Regular Expressions are traditionally compiled into either a DFA or an NFA[1]hich are just two differnt types of state machines. The input then gets fed into the state machine, and you either reach an "accept state" (ie. the regex matched), or you reach an "error state"/run out of input (ie. it didn't ;). Looking closer at a DFA. As it receives input, it just uses the input symbol and its current state to lookup in a table the next state and repeats. In pseudo-code: def executeDFA(dfaTable, input): state = dfaTable[(None, None)] # Start state for c in input: try: state = dfaTable[(state, c)] catch KeyException: return "No Match" # If state not in table, state is "error state" if state.accept: return "Match" # An accept state signals the pattern matched return "No Match" # If we run out of input, no pattern matched (ok, so it's 'executable pesudo-code' ;) The key issue that concerns you is that there is only so much information a single state and one character of input can provide. An arbitrarily nested structure (such as your nested parentheses) requires an equivelent amount (ie. arbitary) of information so it can track the current nesting level. The fixed information capacity in a DFA/NFA simply isn't enough :(. So when our fixed data-structure runs out of space, it's time to move to a dynamic data-structure. In this case we go looking for a stack, and we find two readily available options. We can use the call stack. Each time we find something 'interesting' (in this case an opening parenthesis), we call a method that will continue running the state-machine until it finds a matching 'interesting' feature (ie. a closing parentesis) and then return. So the call stack will track the number of ('s we have seen, and as we find )'s we'll unwind the stack, and so we end up with enough information to track the nesting level... and incidentally have written a recursive descent parser. Or we can use an external stack, and as we find interesting features we will push them onto the stack, and when we see that the top of the stack looks like a complete interesting feature, we will pop it off (and possibly push onto the stack the fact that we've seen a complete interesting feature here). Actually recognising the 'complete interesting feature' on the top of the stack is a little involved, but effectively that's what LR parsers do (ie. yacc and friends). > I want to find ?(.*), but not runneth under or over. > Evaluating a token at a time will become disgusting. It also > seems redundant as you can see it's the same parsing rules as > Python has. (And in fact that is what the line will be > converted to.) ...and you are right. Surprise surprise! You need a parser to parse parsing rules ;). What you have at the moment (regexes and shlex) is a lexer. Lexers just aren't smart enough to track the context as you require[2]. > Can anyone recommend a 'Better Way'? I'm thinking maybe subclassing > generate_tokens. Write a simple recursive descent parser that sits on top of shlex and handles the parentheses. Andrae Muys [0] My understanding of Regular Expressions is restricted to undergraduate compilers augmented with a little of my own reading. I recognise that modern regex engines most likely go beyond the basic DFA/NFA approach I'm personally aware of. I'd be interested in learning exactly how, but time of course is always an issue :). [1] Deterministic Finite Automata or Non-deterministic Finite Automata. ie. a state machine that always knows where to go next, vs. one that dosn't. Still they're both still just finite state machines. [2] "Yep that's handwriting. Recognise it anywhere. All those squiggles and dots and stuff". From martin at v.loewis.de Sat Jul 6 17:09:10 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Jul 2002 23:09:10 +0200 Subject: Python version of STL multimap? References: Message-ID: Roy Smith writes: > try: > dict[key].append (value) > except KeyError: > dict[key] = [value] [...] > So, the question is, is there a standard way in Python to do multimaps, > or should I just continue to roll my own with one of the above idioms > whenever I need one? There is no standard data type in Python for multimaps; dictionaries of lists is the standard idiom. If you want a convenient notation and can accept creating temporary unused list, you can write it as dict.setdefault(key,[]).append(value) HTH, Martin From fredrik at pythonware.com Sat Jul 27 08:10:26 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 12:10:26 GMT Subject: ?Module re documentation bug, error, or misunderstanding? References: Message-ID: David LeBlanc is having a bad RE day ;-) > > >>> import re > > >>> re.search("(.+) \1", '55 55') > > >>> > > >>> re.search("(.+) (.+)", '55 55') > > > > Your quantifiers are greedy, so the first + matches the whole string. "\1" > is "55 55", not the "55" you expect. ...but when the engine discovers that the string doesn't match, it'll try some other interpretation of ".+". And it will keep trying until it is reasonably sure that there's no way the string could match the pattern... > (BTW, it's a good habbit to always make re strings raw: r"".) Exactly. Did you try that on the original expression ;-) > Of course, this might not work either - it's asking a lot to want an "any > character" specifier with a "one or more" quantifier to magically decide > that it should stop on a space. Doesn't stop it from trying, though. If you read the code, you'll find that it's a pretty weak kind of magic (for true magic, see tim's sort and dictionary stuff). From pinard at iro.umontreal.ca Wed Jul 24 16:27:49 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 24 Jul 2002 16:27:49 -0400 Subject: syntax questions In-Reply-To: References: Message-ID: [Fredrik Lundh] > for some reason, people doing internationalization (i18n) and localization > (l10n) stuff seem to prefer to use functions called "_", probably only > to confuse people like you and me. The habit came into Python from C, and it came into C from me! :-) In C, `_()' is implemented as a C pre-processor macro, as a short form for the `gettext()' macro which, we soon discovered, was visually obtrusive. Marking strings for localisation should consume as little horizontal space as possible, and not be too distracting for people reading source code, while not conflicting with other usages. For example, using a single letter would surely have been source for a lot of conflicts! :-) In C, `_' had no previous meaning. To check it, I implemented `_()' in a few widely ported packages (the `tar' program among others), and since no user complained for a few releases, we took this as a kind of proof that it was safe to use more generally, and the habit sprout from there. I'm not sure `_' is ideal in Python, even if not bad. `_' in Python has already the meaning, in interactive mode, of the last computation. Moreover, by fully being a run-time function, it is a bit late to get help from the Python compiler, if more sophisticated usages ever asks for such help. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From emile at fenx.com Thu Jul 11 20:00:56 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Jul 2002 00:00:56 GMT Subject: writing output to file References: Message-ID: > flout = open('/tmp/otherfile', 'w') > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue And if you're dealing with files that may have blank lines: if line.strip()[:1] in ('', '#'): continue has an advantage of not failing on resulting zero length strings. -- Emile van Sebille emile at fenx.com --------- From hst at empolis.co.uk Fri Jul 19 04:28:44 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Fri, 19 Jul 2002 09:28:44 +0100 Subject: regex substitution question Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C94@hendrix.empolisuk.com> Eric Arnold wrote > > I have a question about a regex substitution. Lets say that with the > following string: > > x11111x22222x33333x44444x > > I wanted to find anything that looked like this: 'x([^x]*)x[^x]*x' and > replace only the first group with something (say "-") > so the first match would be: > "x(11111)x22222x" > which would change the line to: > x-x22222x33333x44444x > > and so on ... then the last match would be: > "x(33333)x44444x" > which would change the line to: > x-x-x-x44444x > > but the last "44444" would never get substituted. What would > be the easiest > way to accomplish this? > > Thanks! > Eric > Use a RE with lookbehind and lookahead assertions, i.e. specify that 'x' must precede and follow the matched string, but not be part of the matched string: >>> r=re.compile('(?<=x)[^x]*(?=x)') >>> r.sub('-','x11111x22222x33333x44444x') 'x-x-x-x-x' >>> HTH Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From dgallion1 at yahoo.com Sat Jul 20 12:59:00 2002 From: dgallion1 at yahoo.com (Darrell) Date: Sat, 20 Jul 2002 16:59:00 GMT Subject: Tkinter vs. wxPython References: <09OZ8.376$rb.152305@news.uswest.net> Message-ID: Kevin Altis wrote: > What do you mean wants to display images from BMPs? Could it be you are > confusing the wxBitmap class with BMPs? Well, yes I thought that wxBitmap was the same as a BMP. > The pictureViewer sample that comes with PythonCard can open all of these. > Took a look at PythonCard and was impressed. But my issues persist. I use PIL to process a 40meg black and white image. With eight bits per pixel. To display this with wx it must be converted to RGB which grows the image by 3x and might loose bits on the pixels. The result didn't look that good. I just want to view/pan/zoom which PIL was perfect for. Tk displayed the image with out any problems. Although a decent pan and zoom UI seems to be beyond me 8( --Darrell From peter at engcorp.com Mon Jul 22 20:09:20 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 20:09:20 -0400 Subject: XML Style-sheet question References: Message-ID: <3D3C9EB0.CD7BF8CE@engcorp.com> Christopher wrote: > > I am working on implementing a Python program to interface with > FileMaker 6 and I had a question. The ability to use XML Stylesheets > is very nice with the new FileMaker version, but I've run into a bit > of a problem (I am in the middle of learning XML and all that entails > but I am oblivious to some of the details). I am going to assume that by "XML Stylesheets" you are referring to the Extensible Stylesheet Language (XSL) and XSLT from http://www.w3.org/Style/XSL/ . If that is not in fact the case you can probably ignore the rest of the response. > that formatting). What I want to know is if there is a way to design > a stylesheet template so that even custom exports are formatted > correctly. Let me give a brief example (I know everybody is quite > busy). By default there is a built-in template rule (see section 5.8 of the standard) which recursively processes all elements which are not otherwise handled. You should be able to override this with your own template that does something more useful for you. Replace the contents of that template with whatever you want otherwise-unrecognized elements to have done to them and you should be all set. -Peter From warlock at eskimo.com Thu Jul 25 02:48:15 2002 From: warlock at eskimo.com (Jim Richardson) Date: Wed, 24 Jul 2002 23:48:15 -0700 Subject: Requesting a reference for a book on NNTP References: <30770aa4.0207241752.ace193b@posting.google.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 24 Jul 2002 18:52:51 -0700, TuxTrax wrote: > Hi all > > I am beginning a project in python, that will require a greater > understanding of NNTP protocols (and python!) than I currently > possess. It is a definite learning process and I suspect it will take > me a long time to have a working beta up and running. > > I need to learn how clients query nntp servers for specific messages, > what protocols are involved, how those protocols and commands are > used, syntax involved, authentication methods: in short, I need a book > that will teach me everything I would need to know to write a > newsreader (as far as interfacing with the usenet servers are > concerned), although that is not the project I am embarking on. > > Since I know that many programmers both amateur and professional, are > active and lurking, I would like to ask for a reference to a good > *beginners* book on the subject of NNTP and usenet that helps the > inexperienced to understand the information. > > cheers, > > Mathew > > Xposted to comp.lang.python, comp.os.linux.advocacy Check out the nntplib module in python 11.10 nntplib -- NNTP protocol client This module defines the class NNTP which implements the client side of the NNTP protocol. It can be used to implement a news reader or poster, or automated news processors. For more information on NNTP (Network News Transfer Protocol), see Internet RFC 977. unless you really *want* to reinvent the wheel :) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE9P58ud90bcYOAWPYRAragAJsEXphlaxpg3KC3u6TTnScbUa20XACeMBlU Ozsb+vurflQtBpCHs6QbNqw= =/n/Z -----END PGP SIGNATURE----- -- Jim Richardson Anarchist, pagan and proud of it http://www.eskimo.com/~warlock Linux, from watches to supercomputers, for grandmas and geeks. From markus.vonehr at ipm.fhg.de Mon Jul 22 10:48:25 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 22 Jul 2002 16:48:25 +0200 Subject: set Pmw.EntryField ? References: <3D3C10DD.A6D472E9@ipm.fhg.de> Message-ID: <3D3C1B39.BAFE1F66@ipm.fhg.de> Thanks, works fine. Markus From aleax at aleax.it Sat Jul 27 16:42:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 20:42:03 GMT Subject: How to detect the last element in a for loop References: Message-ID: Tom Verbeure wrote: > > Hello All, > > I often have the case where I need to loop through a bunch of elements, > but do something special on for the last line of code. That's not what you're doing below: > Currently, I can solve it this way: > > first = 1 > for port in self.portDefsList: > if first == 0: > string += ", " > else: > first = 0 > string += str(port) > pass Here, you're doing something special (avoiding the += ", ") the FIRST time. The pass is unconditional and adds absolutely nothing -- just take it away. Anyway, this specific need is met to perfection by: string += ", ".join([ str(port) for port in self.portDefsList ]) joiner.join(sequenceOfStrings) is a powerful way to meet many problems of the "I must do something each time except the first/last" variety -- all those problems which boil down to joining strings with some joiner. As a nice plus, it's also *WAY, WAY* faster. A loop with += takes O(N squared) time, joiner.join takes O(N) time, where N is the size of the input. Don't use loops of += on strings except in really short, trivial cases -- prepare a list and join it at the end, or use a cStringIO instance x and call x.write, etc, etc. For more general needs, you can sometimes use slices to good effect. I.e., instead of: first = 1 for item in somelist: if first: processfirst(item) first = 0 else: processnormal(item) you can do: processfirst(somelist[0]) for item in somelist[1:]: processnormal(item) and if the special case needs to be the LAST one: for item in somelist[:-1]: processnormal(item) processlast(somelist[-1]) This does assume that you have a sequence, not just an iterator, and can thus slice off the first or last items easily. It's trickier but not difficult to do special-on-first on an iterator: processfirst(iterator.next()) for item in iterator: processnormal(item) the .next call returns and "consumes" the first item, so the following for starts from the second one, and all is sweetness and light. Detecting the LAST item for special processing is trickier still if what you DO have is an iterator. You basically have to "stagger" the output, e.g.: saved = iterator.next() for item in iterator: processnormal(saved) saved = item processlast(saved) There's no way out here from the "extra variable" -- you may hide it somewhere, but SOMEwhere it does have to be. Alex From john.abel at pa.press.net Fri Jul 12 08:58:38 2002 From: john.abel at pa.press.net (John Abel) Date: 12 Jul 2002 13:58:38 +0100 Subject: SimpleXMLRPCServer help In-Reply-To: <3D2ECA2B.B1CA01EB@millfilm.co.uk> References: <3D2ECA2B.B1CA01EB@millfilm.co.uk> Message-ID: <1026478718.25053.146.camel@lestat.howden.press.net> You need to be doing something like import xmlrpclib if __name__== "__main__": ServerConn = xmlrpclib.Server ("http://localhost:8000") print ServerConn.add (1,2 ) print ServerConn.pow (2,1 ) Hope that helps (hope even more that it works! :). Regards John On Fri, 2002-07-12 at 13:23, Eric Texier wrote: help(SimpleXMLRPCServer) describe how to install an instance on the server: 2. Install an instance: class MyFuncs: def __init__(self): # make all of the string functions available through # string.func_name import string self.string = string def pow(self, x, y): return pow(x, y) def add(self, x, y) : return x + y server = SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(MyFuncs()) server.serve_forever() BUT I cannot figure out the syntax to access it from a client point of view I will appreciate a quick example even not tested. Thanks, Eric -- http://mail.python.org/mailman/listinfo/python-list From chris.myers at ingenta.com Thu Jul 25 11:12:55 2002 From: chris.myers at ingenta.com (Christopher Myers) Date: Thu, 25 Jul 2002 11:12:55 -0400 Subject: Jython newbie question Message-ID: <3D401577.65D61189@ingenta.com> I just downloaded Maxq (http://www.bitmechanic.com/projects/maxq/) - a web testing application, which is written in Java, and it uses Jython for a scripting language. I've never used Jython before, and consider myself an intermediate Python programmer. It seems I can code in normal Python when editting the Jython scripts generated by Maxq, with one BIG exception: I can't import standard Python modules, such as 'string'. Anybody know what I'm doing wrong? The code is executed from a shell script following: #!/bin/sh # # maxq -- Startup script for MaxQ on *nix # # shamelessly stolen from the ant shell script # # ## resolve links - $0 may be a link to our home PRG=$0 progname=`basename $0` while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '.*/.*' > /dev/null; then PRG="$link" else PRG="`dirname $PRG`/$link" fi done MAXQ=`dirname "$PRG"`/.. CLASSPATH=$MAXQ/lib/maxq.jar:$MAXQ/lib/junit.jar:$MAXQ/lib/jython.jar:$MAXQ/lib\/HTTPClient.zip export CLASSPATH java com.bitmechanic.maxq.Main "$@" And the test script begins as follows: (My addition is the 'import time, string' line). Note - there are no complaints about the time module, only the string module. # imports from com.bitmechanic.maxq import HttpTestCase from junit.textui import TestRunner from java.util import HashMap import time, string # defintition of test class class MaxQTest(HttpTestCase): def __init__(self): HttpTestCase.__init__(self, "") self.page = "" (etc . . .) -- Christopher Myers, Graduate Software Developer Ingenta, Inc. 12 Bassett St. Providence, RI 02903 ph: 401.331.2014 x 102 em: chris.myers at ingenta.com aim: chrismyers001 From emile at fcfw.fenx.com Mon Jul 15 13:43:20 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: 15 Jul 2002 12:43:20 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 15) Message-ID: QOTW: "Wise artisans learn a tool's strengths and use those strengths rather than fighting against the tool. Your 'design philosophy', *actively* _hiding_ information, may be OK with other languages, but it's definitely not the most productive way to use Python." -- Alex Martelli on comp.lang.py "XML combines all the inefficiency of text-based formats with most of the unreadability of binary formats :-)" -- Oren Tirosh "I've seen no reason to suspect that code, concepts, data structures, interfaces, programmers or managers have an advantage over rats in this respect." -- timbot, on sociopathology-inducing density Does the debugging information clear from your screen too quickly? Duncan Booth shows how to use excepthook to catch it. http://groups.google.com/groups?selm=Xns924697C465A36duncanrcpcouk at 127.0.0.1 Barry A. Warsaw announces the creation of a new SIG focussed on producing a common persistence and transactional framework for Python programs http://groups.google.com/groups?selm=mailman.1026158718.20974.python-list at python.org Alex Martelli provides tips and ideas for performance gains in an overview of multi-threading on multi-CPU machines. http://groups.google.com/groups?selm=j2yW8.46899$Jj7.1315070 at news1.tin.it The group has fun debunking anti-python FUD in this thread... http://groups.google.com/groups?threadm=96c7f32.0207081518.52ea644a at posting.google.com ...and Curt Finch subsequently posts a link to a nice advocacy piece... http://groups.google.com/groups?selm=96c7f32.0207091153.7b2484be at posting.google.com ...meanwhile, an article exploring python in the enterprise by Dan Shafer... http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm ...evokes clarification, but is generally well received. http://groups.google.com/groups?threadm=33e8a47f.0207101302.1bd3d902 at posting.google.com Gerhard Kalab has started an integration effort for Python and Eclipse. Included is an incomplete Python editor and the possibility to launch Python scripts. http://groups.google.com/groups?selm=bf340738.0207090014.7fd2a74 at posting.google.com Joe Woodward ask about a problem with stat and a 4.2Gb file. http://groups.google.com/groups?threadm=28bbdc67.0207091119.6d9ecd48 at posting.google.com Remi Delon releases CherryPy-0.2, a Python-based tool for developing dynamic web sites. http://groups.google.com/groups?selm=585c0de9.0207080609.1c969d5a at posting.google.com Want to work in the __future__ environment without importing? Thomas Bellman shows an admittedly inelegant hack to do so. http://groups.google.com/groups?selm=agdcbu$pu3$1 at news.island.liu.se Mike C. Fletcher announces the alpha-2 release of SimpleParse, a BSD-licensed Python package providing a simple parser generator for use with the mxTextTools text-tagging engine. http://groups.google.com/groups?selm=mailman.1026278895.13402.python-list at python.org Max Ischenko posts a link to info on running PyUnit from inside the Vim editor. http://vim.sourceforge.net/tips/tip.php?tip_id=280 Richard Jones announces the release of GadflyB5 1.0.0, an SQL Relational Database in Python. http://groups.google.com/groups?selm=mailman.1026322806.21298.clpa-moderators at python.org Keith Dart Introduces pyNMS, SNMP, MIB and other tools for Python. http://groups.google.com/groups?selm=mailman.1026322807.21301.clpa-moderators at python.org Gregory P. Smith releases pybsddb 3.4.0, a python interface to Sleepy Cat's BerkeleyDB 3.x - 4.0 data base. http://groups.google.com/groups?selm=mailman.1026322806.21293.clpa-moderators at python.org Barry A. Warsaw releases Mailman 2.0.12, and recommends all users to upgrade as it fixes a cross-site scripting vulnerability. http://groups.google.com/groups?selm=mailman.1026416898.13906.python-list at python.org Mark this day in your calendar: Daniel Dittmar revives the Python Web Programming Wiki by seeding it with Paul Boddie's pages on "Web Programming Frameworks". http://groups.google.com/groups?selm=agm580$r2q$1 at news1.wdf.sap-ag.de Graham Fawcett, with pointers from Thomas Heller, adds distutils capabilities to Greg Ewing's Pyrex, adding a distutils.command.pyrexc as a subcommand of "build_ext" to handle the .pyx compilation. http://groups.google.com/groups?threadm=3d799735.0207101234.7ca3288d at posting.google.com Rodney Somerstein asks "Any Python distribution solutions for Mac?" but gets no on-list answers... can anyone help? http://groups.google.com/groups?selm=080720021958161862%rodneys at nospam.io.com Bjorn Pettersen finds out about automating the MSDEV studio build process using the command line interface. http://groups.google.com/groups?threadm=mailman.1026422483.9226.python-list at python.org If you've ever needed to cycle through a list repeatedly, this thread started by Mark McEahern leads to a simple solution using generators. http://groups.google.com/groups?threadm=mailman.1026501403.17010.python-list at python.org Mark Charsley asks for techniques to help in debugging embedded python. http://groups.google.com/groups?threadm=memo.20020712144413.1996A at a.a Henk gets help on the __init__ requirements when subclassing Exception. http://groups.google.com/groups?threadm=3d2bf4b6.183387921 at news.skynet.be Wenshan Du releases a version of IDLE with unicode support. http://groups.google.com/groups?selm=e786d63d.0207110431.53499a4a at posting.google.com Trent Mick posts a work-around for bug #513572 where Windows UNC paths don't quite work with isdir properly. http://groups.google.com/groups?selm=mailman.1026333317.11630.python-list at python.org Michael Hudson releases pyrepl-0.7, a readline-a-like in Python with features like sane multi-line editing, a searchable history, completion, including displaying of available options, and more. http://groups.google.com/groups?selm=mailman.1026508742.2710.clpa-moderators at python.org J.Jacob announces emPire v. 0.59, a portable open source multi player game for the default Python distribution, so you can have fun with programming and learn Python. http://groups.google.com/groups?selm=mailman.1026508743.2716.clpa-moderators at python.org Rick Hightower announces a new book, "Python Programming with the Java Class Libraries" http://groups.google.com/groups?selm=6ec68a4c.0207130745.58d2fa07 at posting.google.com Michael Schmitt gets help when he finds that updating mutable shelve contents doesn't seem to work as expected. http://groups.google.com/groups?threadm=agqegm$abr$00$1 at news.t-online.com Rubin Marquez releases WeaselWeb, a Python program that allows the converter to handle http://groups.google.com/groups?selm=8a27e309.0207131624.6c73be50 at posting.google.com Ivan V. Begtin adds a recipe to the ActiveState cookbook that extends ConfigParser class to make it able to read and write configuration settings from specified registry key. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/138944 C?dric Dutoit announces the release of PyUt 1.1, a UML 1.3 editor with plugins and roundtrip support. http://groups.google.com/groups?selm=3D31E517.1020700 at shimbawa.ch Itamar Shtull-Trauring releases Twisted 0.19.0, an event-based framework for internet applications written in Python. http://groups.google.com/groups?selm=mailman.1026699622.26878.python-list at python.org ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From max at alcyone.com Sat Jul 6 15:56:28 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Jul 2002 12:56:28 -0700 Subject: Why self? References: Message-ID: <3D274B6C.DD1640D5@alcyone.com> Brian McErlean wrote: > I don't entirely agree. The thing that really irritates me about > hungarian notation is that you're mangling the human readable names of > things to provide information that is related to the internals of the > language. The real problem with Hungarian notation, as far as I'm concerned, is that the solution is worse than the disease. I have never seen a non-trivial project that used Hungarian notation that did not do so incompletely, inconsistently, and in many cases incorrectly (variables have Hungarian notations that are incorrect). Changing the type (or purpose, depending on how strictly you use Hungarian notation) of one variable results in a cascade effect, often so substantial that people don't bother changing the annotations when a variable changes its type/purpose, meaning that rapidly many of them become inconsistent. Since the idea behind Hungarian notation is that you can simply look at a variable and tell its type (or what it's for) without having to look up a declaration (in C, C++, Java, etc.), this defeats the whole purpose -- you can never really be sure that the Hungarian annotations are accurate (since they often aren't), so you end up having to defer to the declaration anyway. The entire point of Hungarian notation just collapsed in on itself. Hungarian notation with Python seems almost worse, since there is no authoritative declaration to defer to when you're not sure if an annotation is accurate or not. All of the benefits and none of the drawbacks of Hungarian notation can be gained simply by giving variables appropriate and meaningful human-readable names. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From paul at boddie.net Tue Jul 2 16:28:53 2002 From: paul at boddie.net (Paul Boddie) Date: 2 Jul 2002 13:28:53 -0700 Subject: Web templating/db tool with best designer/coder separation? References: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> Message-ID: <23891c90.0207021228.6809cf9b@posting.google.com> Stefan Franke wrote in message news:<0663iuskkqrjui7rg4ut5b80vmo556jo8k at 4ax.com>... > > HTML offers a standard way to address tags by using id attributes. > Can't we leave the HTML alone, just mark the affected tags by giving > them IDs, and put all the replacement/iteration commands into a > separate place? This is what Enhydra's XMLC does, and one uses a DOM-like API to access the elements marked in this way in the document. I've been experimenting with a system which doesn't modify or replicate the elements programmatically; instead, the marked elements reflect the structure of the data being presented. > What do you think about it? There might well be big things I > left out of consideration, since I'm quite out of web business (my > last bigger project was with Zope 1.10.2 and its DTML...). I think that this is really the way to go for anyone interested in investigating the subject area further, rather than inventing yet another "source code in HTML" solution and hoping to find out new ways of working from that. Paul From mlh at vier.idi.ntnu.no Sun Jul 14 13:19:28 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 14 Jul 2002 17:19:28 +0000 (UTC) Subject: "Tickets" and XML-RPC authentication Message-ID: If I have only one server/service, and that service takes care of its own authentication (i.e. no Kerberos-like stuff), is there any point to using a ticket/cookie-based system? In other words, is there any point to doing this: ticket = server.authenticate('username', 'password') server.performService(ticket, some, other, params) rather than server.performService('username', 'password', some, other, params) ? I see the Advogato XML-RPC interface uses a ticket (or, as they call it, a cookie) like in the first example. They don't explain why, and I can't see any good reason, except perhaps making the client code a tiny bit simpler... But you could always do something like ticket = {'user': 'foobar', 'pass': 'babar'} anyway, so... (Perhaps there is some session tracking going on?) Any thoughts? -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From cbbrowne at acm.org Thu Jul 11 11:08:58 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 11 Jul 2002 15:08:58 GMT Subject: Good SOAP lib for Python 2.2 References: <3D2D9B2C.3030606@NOSPAMREMOVETHISxs4all.nl> Message-ID: Irmen de Jong wrote: > I'm using Python 2.2.1 and I'm searching a current, up-to-date > SOAP library for Python. > I tried ZSI but it fails because apparently it uses an old XML api. > > What should I try instead? Something's odd there. There hasn't been any activity with ZSI since about mid-May. And zolera.com (home of Rich Salz, main ZSI developer) seems dead (as in "DNS doesn't think it exists anymore"). Have Zolera/Rich Salz disappeared? As for what's "up-to-date", your options are limited, as the latest release _was_ ZSI, in mid-May 2002. The last release of anything else was of SOAP.py 0.9.7, in June 2001. (The developers thereof were at a DotCom that has gone under.) -- (reverse (concatenate 'string "ac.notelrac.teneerf@" "454aa")) http://cbbrowne.com/info/soap.html Honuphrius is a concupiscent exservicemajor who makes dishonest propositions to all. From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 06:55:36 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 03:55:36 -0700 Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: <7xd6taahcn.fsf@ruckus.brouhaha.com> Michael Hudson writes: > > I may be wrong about this, but I don't think regular expressions > > qualify as turing complete. No branching for one thing... > > Somewhere you can find a (perl) regexp that matches prime but not > composite numbers, which suggests Turing completeness -- and rather > takes the mickey out of the word "regular". Formally, regular expressions can be recognized by finite state machines, thus no hope of recognizing primes. Perl regexps aren't really regexps because of the tricks you can play with back-substitution etc. They're a superset of traditional regexps. From curt at journyx.com Tue Jul 9 10:30:14 2002 From: curt at journyx.com (curt finch) Date: 9 Jul 2002 07:30:14 -0700 Subject: j2ee and python and evil competitors... Message-ID: <96c7f32.0207090630.7a19b2c1@posting.google.com> > curt finch wrote: >> >> Our free web timesheet app is written totally in Python. >> One of our competitors is saying the following >> things about python to our customers. Help me make them >> look stupid. Please? >Which competitor? Please post a link to the information >they've provided to your customers. If it's not online, >please provide at least a link to their home page so we >can check them out for ourselves. >Many of the things in that list smell a lot like they're >made up just for a troll. Is any of this actually true? >-Peter in my original post, i posted the doc they wrote. They sent it to a 200k opportunity after we won it. the competitor is clockware. i doubt if they have that particular doc available from their site but instead that they give it to select prospects in deals where we show up (i.e. all of them.) as to being a troll, well, if trolls drive traffic and want you to use their software for free then i'm guilty as charged. i do always with all my communications try to drive traffic to http://journyx.com , so i can see why you might get the (wrong) impression that i'm just a ruthless spammer. ultimately developer acceptance of our soap/xml api is what will enable us to succeed, so we of course want all the mind share from the python/linux/soap/xml developer communities we can get thanx everyone for your feedback, it has at the very least been entertaining. Want free Web Time Management Software??? --> http://journyx.com/wts.html ------------------------------------------------------------------------- From tim.one at comcast.net Fri Jul 12 03:20:43 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Jul 2002 03:20:43 -0400 Subject: Guido van Rossum Tutorial - .PDF or other format? In-Reply-To: Message-ID: [David Wright] > Could someone please advise if this suberb document is available > on the Web in a printer friendly format, such as .pdf or even > .doc. (other than the hypetext version on line and on my PC). Yes, I'd > like the *address* too ;-) You can get all the docs in several formats (including .pdf, but not .doc) here: http://www.python.org/doc/current/download.html From theller at python.net Tue Jul 30 13:34:24 2002 From: theller at python.net (Thomas Heller) Date: Tue, 30 Jul 2002 19:34:24 +0200 Subject: PEP 298 - the Fixed Buffer Interface Message-ID: Here is PEP 298 - the Fixed Buffer Interface, posted to get feedback from the Python community. Enjoy! Thomas PS: I'll going to a 2 weeks vacation at the end of this week, so don't hold your breath on replies from me if you post after, let's say, thursday. ----- PEP: 298 Title: The Fixed Buffer Interface Version: $Revision: 1.3 $ Last-Modified: $Date: 2002/07/30 16:52:53 $ Author: Thomas Heller Status: Draft Type: Standards Track Created: 26-Jul-2002 Python-Version: 2.3 Post-History: Abstract This PEP proposes an extension to the buffer interface called the 'fixed buffer interface'. The fixed buffer interface fixes the flaws of the 'old' buffer interface as defined in Python versions up to and including 2.2, see [1]: The lifetime of the retrieved pointer is clearly defined. The buffer size is returned as a 'size_t' data type, which allows access to large buffers on platforms where sizeof(int) != sizeof(void *). Specification The fixed buffer interface exposes new functions which return the size and the pointer to the internal memory block of any python object which chooses to implement this interface. The size and pointer returned must be valid as long as the object is alive (has a positive reference count). So, only objects which never reallocate or resize the memory block are allowed to implement this interface. The fixed buffer interface omits the memory segment model which is present in the old buffer interface - only a single memory block can be exposed. Implementation Define a new flag in Include/object.h: /* PyBufferProcs contains bf_getfixedreadbuffer and bf_getfixedwritebuffer */ #define Py_TPFLAGS_HAVE_GETFIXEDBUFFER (1L<<15) This flag would be included in Py_TPFLAGS_DEFAULT: #define Py_TPFLAGS_DEFAULT ( \ .... Py_TPFLAGS_HAVE_GETFIXEDBUFFER | \ .... 0) Extend the PyBufferProcs structure by new fields in Include/object.h: typedef size_t (*getfixedreadbufferproc)(PyObject *, void **); typedef size_t (*getfixedwritebufferproc)(PyObject *, void **); typedef struct { getreadbufferproc bf_getreadbuffer; getwritebufferproc bf_getwritebuffer; getsegcountproc bf_getsegcount; getcharbufferproc bf_getcharbuffer; /* fixed buffer interface functions */ getfixedreadbufferproc bf_getfixedreadbufferproc; getfixedwritebufferproc bf_getfixedwritebufferproc; } PyBufferProcs; The new fields are present if the Py_TPFLAGS_HAVE_GETFIXEDBUFFER flag is set in the object's type. The Py_TPFLAGS_HAVE_GETFIXEDBUFFER flag implies the Py_TPFLAGS_HAVE_GETCHARBUFFER flag. The getfixedreadbufferproc and getfixedwritebufferproc functions return the size in bytes of the memory block on success, and fill in the passed void * pointer on success. If these functions fail - either because an error occurs or no memory block is exposed - they must set the void * pointer to NULL and raise an exception. The return value is undefined in these cases and should not be used. Usually the getfixedwritebufferproc and getfixedreadbufferproc functions aren't called directly, they are called through convenience functions declared in Include/abstract.h: int PyObject_AsFixedReadBuffer(PyObject *obj, void **buffer, size_t *buffer_len); int PyObject_AsFixedWriteBuffer(PyObject *obj, void **buffer, size_t *buffer_len); These functions return 0 on success, set buffer to the memory location and buffer_len to the length of the memory block in bytes. On failure, or if the fixed buffer interface is not implemented by obj, they return -1 and set an exception. Backward Compatibility The size of the PyBufferProcs structure changes if this proposal is implemented, but the type's tp_flags slot can be used to determine if the additional fields are present. Reference Implementation Will be uploaded to the SourceForge patch manager by the author. Additional Notes/Comments Python strings, Unicode strings, mmap objects, and maybe other types would expose the fixed buffer interface, but the array type would *not*, because its memory block may be reallocated during its lifetime. Community Feedback Greg Ewing doubts the fixed buffer interface is needed at all, he thinks the normal buffer interface could be used if the pointer is (re)fetched each time it's used. This seems to be dangerous, because even innocent looking calls to the Python API like Py_DECREF() may trigger execution of arbitrary Python code. Neil Hodgson wants to expose pointers to memory blocks with limited lifetime: do some kind of lock operation on the object, retrieve the pointer, use it, and unlock the object again. While the author sees the need for this, it cannot be addressed by this proposal. Beeing required to call a function after not using the pointer received by the getfixedbufferprocs any more seems too error prone. Credits Scott Gilbert came up with the name 'fixed buffer interface'. References [1] The buffer interface http://mail.python.org/pipermail/python-dev/2000-October/009974.html [2] The Buffer Problem http://www.python.org/peps/pep-0296.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From mathieu at nouvelempire.net Fri Jul 26 13:03:43 2002 From: mathieu at nouvelempire.net (Mathieu) Date: 26 Jul 2002 10:03:43 -0700 Subject: Python and XML help Message-ID: Hello, I'm new to Python and having some problems parsing the following XML : I use the xmllib module based on an example I've seen in the archives of this newsgroup : import xmllib, string class myparser(xmllib.XMLParser): def __init__(self): xmllib.XMLParser.__init__(self) self.currentdata = [] def handle_data(self, data): self.currentdata.append(data) def start_first(self,attrs): print "List of the items:" def start_item(self,attrs): print attrs['name'] def end_item(self): pass def end_first(self): pass if __name__ == "__main__": p=myparser() p.feed(data) p.close() I would like the script to write only the "name" variables that are within the "first" brackets and ignore the others. Please note that my code must stay compatible with Python 1.5 and that this example might not work or contain errors, because it is a simplified version of the code I have written. Thanks for your help! From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 20:44:25 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 17:44:25 -0700 Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> Message-ID: <7xu1nb59qu.fsf@ruckus.brouhaha.com> William Park writes: > > http://www.nightsong.com/phr/python/setclock.py > > > > I find it pretty useful for adjusting my computer clock every > > now and then, without the hassle of setting up a real NTP system. > > Thanks for the pointer, Paul. Exactly what I needed. Do you know any pure > shell script that does the same thing? I don't have Python installed on > every machine. I don't know about shell but it should be simple to write the same thing in Perl or even in C. From jonathan at onegoodidea.com Mon Jul 8 11:06:13 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 08 Jul 2002 16:06:13 +0100 Subject: Why isn't this a bug? References: Message-ID: On 7/7/2002 21:12, in article aga7af$jsvv9$1 at ID-76829.news.dfncis.de, "Russell Blau" wrote: > As the above example shows, the str() built-in function represents long and > float values one way if they are passed directly as the argument of the > function, but a different way if they are found inside a list or tuple (or > dict, although I didn't illustrate that above). [...] > Ah hah, I thought, I've found a bug. However, I did a search on > sourceforge.net and found that this issue (or at least part of it) had > already been submitted as a bug and rejected! (It was number 506741, for > anyone who wants to look.) [...] > Of course, if someone would like to explain why something so simple and > intuitive is a "bad idea," please enlighten me. ;-) I think the problem is that you're considering an implicit behaviour to be a feature. The rough meaning of 'str' and 'repr' is: repr - return a string representation of an object (ideally such that the string can be 'eval'ed to re-produce the object) str - convert an object into a string For numbers, these two behaviours are easily defined. But for tuples and lists there is no obvious behaviour for 'str'. What does it mean to turn a tuple or a list into a string? In the absence of a defined behaviour, the interpreter falls back on just returning 'repr' of the object. You have to ask yourself: why am I converting a tuple into a string? Perhaps the behaviour you want would be better written explicitly like: >>> c = (0.5, 0.7) >>> str(c) '(0.5, 0.69999999999999996)' >>> "(%s, %s)" % c '(0.5, 0.7)' >>> It's best not to rely on implicit conversions. -import-this-ly-y'rs, Jonathan From postmaster at 127.0.0.1 Mon Jul 29 12:16:35 2002 From: postmaster at 127.0.0.1 (Dr. Marco) Date: 29 Jul 2002 18:16:35 +0200 Subject: problem recursively removing directories on an NFS mount References: <3D17579F.9030905@bioeng.ucsd.edu> Message-ID: On Mon, 24 Jun 2002 10:32:15 -0700, Curtis Jensen wrote : > fine. However, sometimes nfs files of the form ".nfs07D7761" get > created. This causes the os.rmdir( full_name ) command to throw an Such files appear when you remove a remote file that is still opened by another program. They should disappear when the file is closed. A solution could be to move them to another directory but I confess I don't know if this can be done safely. -- Dr. Marco From pedronis at bluewin.ch Wed Jul 31 05:33:19 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 31 Jul 2002 11:33:19 +0200 Subject: A generic question: idiom for a paramterized base class? References: <3D47042E.33823879@irl.cri.nz> Message-ID: <3d47b1b4$1_3@news.bluewin.ch> > ############ example.py ########### > class GenericBase(object): > def __iadd__(self,other): > return TAdd(self,other) # Problem!! return self.__class__(self,other) > def __add__(self,r): > return GenericBase.__iadd__(self,r) > def __radd__(self,l): > return GenericBase.__iadd__(l,self) > From oliver.smith at removethisbit.baesystems.com Mon Jul 15 12:06:44 2002 From: oliver.smith at removethisbit.baesystems.com (Olly Smith) Date: Mon, 15 Jul 2002 17:06:44 +0100 Subject: HTTP_USER_AGENT Parsing Message-ID: <3d32f2ac$1@pull.gecm.com> I'm a bit of a newbie to Python, and in my quest to generate nice HTML content, I need a way to work out what browsers clients are using from their HTTP_USER_AGENT strings. Any pointers? Thanks muchly Olly From jayant at tam.cornell.edu Mon Jul 22 23:29:49 2002 From: jayant at tam.cornell.edu (Jayant Kulkarni) Date: Mon, 22 Jul 2002 23:29:49 -0400 Subject: Adding Modules to precompiled installation of Python Message-ID: My problem I guess is very specific so I doubt if somebody has run into it before but any general help would be appreciated. I am using the finite-element package Abaqus which comes with precompiled Python (ver 1.5). I want to interface this with Matlab using Pymat. (PyMat utility by Sterian). The problem is that as the python is precompiled I do not know how to import new modules.. Additional info: The PyMat utility comes with PyMat.cpp and Pymat.pyd. I am on a Windows OS. (Though I have access to Linux, and I can work on that system as well.. So solution to the problem in any OS should be of help) Thanks for any help! -- jayant kulkarni From ddw at mcw.net Fri Jul 19 10:14:10 2002 From: ddw at mcw.net (David Wilson) Date: Fri, 19 Jul 2002 10:14:10 -0400 Subject: Newbie Word & Text file access? Message-ID: <3D381EB2.1030506@mcw.net> Newbie question after checking about 500 messages on comp.lang.python : Using W2K on Intel, Python 2.2.1, and IDLE 0.8 Unsuccessful open() of MS Word (.doc) , Abiword (.abw) and text (.txt) files after successfully opening and reading HTML (.html) and LOG files. Sample IDLE output: >>> open("C:\DownLoad\test1.txt","r") Traceback (most recent call last): File "", line 1, in ? open("C:\DownLoad\test1.txt","r") IOError: [Errno 2] No such file or directory: 'C:\\DownLoad\test1.txt' 1) What else is necessary to open these types of files? 2) Please advise where I can find documentation on IDLE and/or Python errors such as "[Errno 2]" above? 3) Is there a parser utility which can massage these formatted document files for faster/easier subsequent manipulation? Thanks in advance. ddw From loewis at informatik.hu-berlin.de Wed Jul 17 09:16:53 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Jul 2002 15:16:53 +0200 Subject: string encoding - how to make it work References: Message-ID: "Henry Baumgartl" writes: > Still, what i can't get my head around is that when entering short cut > generated extended characters into, for instance, IDLE it works without any > problem. > > It is only when i try to save it that the Error is raised. That's an independent IDLE problem. IDLE is inherently a Unicode editor, as the underlying Toolkit uses Unicode. When saving the file, IDLE needs to know what encoding to use, but doesn't. IDLE uses the system default encoding, which is 'ascii'. As a work-around, you can change the system default encoding, see the FAQ. In future Python versions, you can indicate the desired source encoding in the source file itself. Regards, Martin From cce at clarkevans.com Tue Jul 16 14:27:12 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 16 Jul 2002 14:27:12 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: <20020716151830.A10625@prim.han.de>; from pyth@devel.trillke.net on Tue, Jul 16, 2002 at 03:18:30PM +0200 References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> <20020716151830.A10625@prim.han.de> Message-ID: <20020716142712.A70366@doublegemini.com> On Tue, Jul 16, 2002 at 03:18:30PM +0200, holger krekel wrote: | Huaiyu Zhu wrote: | > The basic idea is quite simple: consider a data structure as a tree; denote | > the type of branching at each node; indent the subtrees. It appears to me | > that indentation is easier to handle than quotes and escapes. Here's a | > simple example: | | It does and it's very interesting. It does sound a lot like | http://yaml.org to me, though (They even have an RFC). | Don't you think YAML might be a superset of your ideas? Yes, Steve Howell even has a python implementation of it... http://yaml.org/python/PyYaml_14jul2002.tgz I'm sure he'd love your comments/contributions. | Let me add some random thoughts/questions about your/yaml's scheme | (i hope i am not missing something obvious): | | - how is a binary data-stream's size determined? What about | open-ended streams? Embedding of arbitrary data-streams | is very useful (IMO). In YAML, we have a built-in BASE64 type which hopefully most implementations will support. As for handling embedded streams, this works as long as they are indented properly and only use printable characters (see specification). | - somehow your and yaml's scheme remind me of todays wiki techniques. | E.g. Wikis have methods of sequence-detection (bullets ...) and they | have a commitment to readability. Of course, they are generally more | concerned with graphical views than with beeing a concise persistence | scheme. Yes; Ward Cunningham's WikiWiki is a very cool concept and I'm sure we borrowed from it sub-conciously. | - Is there a canonical conversion between XML and your scheme/YAML? | Shouldn't be too hard, anyway... http://yaml.org/xml.html | - how do you express external addresses akin XPATH? | Ideas: | - Mappings are easy, just take the 'key'. | - Sequences are easy (take the sequence number) but not very robust | to deletions and insertions of items. | - tag-names (IDs) which can be associated with any item might be interesting. | readability is likely to suffer, probably. I'm toying with making IDs a "special" key so that a YPATH like mechanism would work well... similar to XPATH/XSLT's "keys()" | btw, I wonder whether some form of your and/or YAML's ideas should play a | role in the new persistence-SIG. While the actual persistence mappings | are not in the focus there are certainly some interesting connections | between the two areas. One of our other members, Brian Ingerson, is working on getting YAML into the core of Parrot (http://parrot-code.org) | this sure is useful. Especially for me since i work with a (perl-) | friend on a project which needs to address the persistence-question. And | we want to have it interoperable, simple and fast. I guess looking | at YAML might avoid that you have to dig too much into old harddisks :-) Also, there is a Perl implementation of YAML sited in the downloads section of the website written by Brian Ingerson. Having more members would be great! We could use more implementations, and generic YAML tools (like YAML-DIFF) Best, ;) Clark -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From mwh at python.net Wed Jul 10 06:56:02 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 10 Jul 2002 10:56:02 GMT Subject: try/finally question References: <7xd6twow3x.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > So the obvious way to use it is: > > try: > db.begin() > x = db.do_action(first_thing) > y = db.do_action(second_thing) > db.commit() > finally: > db.cancel() > > The trouble is db.cancel() is an ordinary method call--it's not atomic > in the interpreter. It can be interrupted and blast out of the > finally block before finishing, and then control returns to some > higher level with the database still locked. With you so far, I think. > In a C program I'd use sigsetmask to turn off interrupts during the > critical section, but Python doesn't have that. Might do in 2.3 (if I can get it to work more than 50% of the time... signals and threaded libc's really seem to disagree quite a lot). > All I can think of are yet more try/finally blocks, which is ugly > and which still might not close all the gaps. In particular, I > don't know whether calling a method from a finally block is > guaranteed to execute the first Python statement in the method, if > an interrupt comes at that exact instant. Probably not. The signal handler might get executed between the LOAD_FAST "db" and the LOAD_ATTR "cancel", after all. > What's the right way to handle this? Dunno, sorry. Cheers, M. -- Screaming 14-year-old boys attempting to prove to each other that they are more 3133t than j00. -- Reason #8 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From sholden at holdenweb.com Fri Jul 26 23:44:45 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 26 Jul 2002 23:44:45 -0400 Subject: how to count lines in a file ? References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> Message-ID: "Jonathan Hogg" wrote ... > "Steve Holden" wrote: > > > So what you appear to dislike is that there is now a *chance* that __del__() > > will be called on cyclic garbage, when there wasn't before. > > Not quite. Any cycle containing an object with a __del__ method will be > skipped and left to languish in memory-limbo forever. > You mean the garbage collector doesn't *collect* data that appears in cycles? That's not my understanding (which doesn't nevessarily mean it's dissonant with reality). > If the objects exist in a cycle then "logically" they must exist for ever. This simply isn't true. If you create a list or a dictionary that refers to itself (perfectly possible), that object is collectable as soon as *nothing else* refers to it. For example: >>> a = [1,2,3,4] >>> a.append(a) >>> a [1, 2, 3, 4, [...]] >>> Notice how the interpreter cleverly avoids an infinite recursion in the repr() of that list. The fact that it contains references to itelf need not stop its collection, and that is precisely why [I understand] the new GC scheme was introduced to supplement reference counting. If I now execute the following statement: >>> a = "No more references" there is absolutely no reason why the list's elements, and the space occupied by the list, need not be returned to the free poll (assuming other references have not been created). > Luckily, for most simple containers, throwing them away is semantically no > different from keeping them around - a dictionary or a list on it's own > doesn't do anything. However, if something has a __del__ method then > throwing it away requires executing some code which may have unknown > side-effects - so you can't do it. > So, what you *seem* to be saying is that it would be p[erfectly possible to collect objects thatdon't have __del__() methods, but once they acquire such they are no longer collectible even when only cyclic references exist? That seems an odd asserion. > At the very simplest level, the object's dictionary/slots may be meaningless > at the time that you would execute __del__ (because you're in the middle of > breaking all the cyclic references), so executing __del__ might cause > horrible things to happen. > Well, certainly you *always* have to be careful that references haven't been invalidated before use. > It's a sort of philosophical thing. If you can be sure that having closed > the door, no-one will open it again then the room on the other side is > allowed to simply disappear ;-) > > __del__ only has sensible semantics in the presence of reference counting. > Either have reference counting or throw away __del__. When it comes down to > it you gotta pick one or the other. > I'm afraid you're going to have to explain that one. I don't think there is any great philosophical difference bvetween ourpositions, but I'm not yuet completely sure I understand what you are saying. As the Reverend Sydney Smith observed upon seeing two women shouting at each other from opposite windows: "I fear they will never agree, for they are arguing from different premises". wanting-to-agree-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From zopestoller at thomas-guettler.de Mon Jul 22 06:54:12 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Mon, 22 Jul 2002 12:54:12 +0200 Subject: NEWBIE: Removing HTML/JavaScript from a webpage References: <3D3B0491.4000605@NOSPAM.bardstowncable.net> Message-ID: <3D3BE454.4060508@thomas-guettler.de> Owen Marshall wrote: > Ok...here is my question. I have this bit of code: > > import urllib > > response = > urllib.urlopen('http://movies.go.com/cgi/movielistings/request.dll?ZIPSPECIFIC&zip_code=40004&date=07/20/2002') > > > resp = response.read() Use the htmlparser from htmllib. The parser gives you an event for every encountered tag. Ignore the tags you don't like. If you want to know the parent-tags use a list as a stack to keep track of the tags. Use push() if an start-tag occurs and pop() if a end-tag occurs. The example below uses in_td, which is worse than using a stack. Here is an example for parsing the html output of excel: class MSExcelHTMLParser(htmllib.HTMLParser): def __init__(self): htmllib.HTMLParser.__init__( self, formatter.NullFormatter()) self.content='' self.translateDict={} self.in_td=0 self.in_tr=0 self.column_count=0 self.table_header=0 def start_tr(self, attributes): if self.in_tr: raise "Parse Error:
tags' else: self.table_header=1 elif len_rd!=2: raise 'Parse Error: Row with not 2 tags' # Hash "deutsch" --> "bulgarisch" self.translateDict[self.rowData[0]]=self.rowData[1] def start_td(self, attributes): self.content='' if self.currColumn>1: raise "Parse Error: Table has more than 2 columns" if self.in_td: raise "Parse Error: in " self.in_td=1 def end_td(self): self.in_td=0 self.content=self.content.strip() if len(self.content)==1 and ord(self.content)==160: self.content='' self.rowData.append(self.content) self.currColumn+=1 def handle_data(self, content): self.content+=content fd=open(filename) def main(): #Remove Microsoft's non standard conforming HTML-Tags content=[] while 1: line=fd.readline() if not line: break if re.match(r'\s*$', line): #Ignore non standard conforming HTML of MS-Excel while 1: line=fd.readline() if not line: raise 'Parsing error: EOF in Microsoft special tag' if re.match(r'\s*', line): break #print "Ignoring:", line else: content.append(line) fd.close() content=string.join(content) parser=MSExcelHTMLParser() parser.feed(content) parser.close() thomas From schull at digitalgoods.com Mon Jul 29 12:12:37 2002 From: schull at digitalgoods.com (Jon Schull) Date: 29 Jul 2002 09:12:37 -0700 Subject: getting an image-bearing widget to refresh its image (bonus question: at regular intervals) Message-ID: <2621b014.0207290812.5258379c@posting.google.com> Can anyone tell me why this code fails to display b2.gif... ------------------------------------------ from Tkinter import * root = Tk() root.title("Images") picture = PhotoImage(file="c:\\temp\\buchananst.GIF") L1=Label(root, image=picture) L1.grid() def update(): global b print 'update' pic2 = PhotoImage(file="c:\\temp\\b2.gif") L1.config(image=pic2) L1.grid(row=3,column=0) b.config(text="updated") b=Button(root,text='update', command=update) b.grid() #showpic() root.mainloop() ------------------------------------------ ...whereas if instead of b.config(text="updated") I write b[text]="updated", I get an error message on that line AND b2.gif *IS* updated? Is there a right way to get an image-bearing widget to load a new (or updated) image? ...at regular intervals? (I'm currently planning on using Threads.py at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 ) Thanks! From shagshag13 at yahoo.fr Tue Jul 9 09:59:20 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 15:59:20 +0200 Subject: sorting many arrays from one... References: Message-ID: "Duncan Booth" a ?crit dans le message de news: Xns924692F5BE4Cduncanrcpcouk at 127.0.0.1... > drive, other1, other2, other3 = map(list, zip(*aux_list)) fine ! and with map ! but i still have another question i didn't understand how this works (i think i didn't get zip(*aux_list)) s13. From aahz at pythoncraft.com Tue Jul 23 13:46:24 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2002 13:46:24 -0400 Subject: threads and Tkinter References: Message-ID: In article , Petr Klyushkin wrote: > >I have one more question about Tkinter. This time it is related with >threads. I have a program which uses Tkinter as its GUI toolkit. It >runs a separate "worker" thread for doing some time-consuming >operation. Sometimes worker thread has to update GUI. See the thread tutorial on my web page. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jonathan at onegoodidea.com Fri Jul 19 11:35:10 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 19 Jul 2002 16:35:10 +0100 Subject: Anybody using 4suite for xslt processing? References: Message-ID: On 19/7/2002 15:44, in article ah98hv$rfsrm$1 at ID-108329.news.dfncis.de, "Marko Faldix" wrote: > sometimes I think I am first man on earth want to process xslt. > > I got python on windows 2000 Server with iis and 4suite, I could change to > linux if necessary. Heh. Maybe not the first man. I gave up trying to get 4Suite to work. I couldn't get it to build cleanly (failed on building the documentation) and had to manually install it. After that I tried the simple example from their instructions and it died - a similar missing attribute error, but somewhere deep in the code. I've tried wading through it to see what's going on, but it proved to be too impenetrable. I have no idea what's going on in the PyXML-SIG at the moment, but there seem to be plenty of choices when it comes to XML toolkits. I think my next move is going to be to play with a SWIG version of libxslt, Sablotron, or Xalan: It looks like someone has already had a go at libxml/libxslt: so I'll probably start there. Let me know if you get anywhere with 4Suite. Jonathan From see_reply_address at something.invalid Wed Jul 3 01:14:07 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 03 Jul 2002 17:14:07 +1200 Subject: Singleton technique (Re: metaclasses vs. inheritance) References: Message-ID: <3D22881F.10204@something.invalid> > "Ian McMeans" wrote: >>Can someone give an example of a problem that is solved with metaclasses, I came up with an idea today for making practical use of the funky ability in 2.2 for a "class" statement to create something other than a class. Here's an example of how it's used: >>> from singleton import singleton # First let's define an ordinary class: >>> class C: ... def spam(self): ... print "spam:", self ... # Now here's a singleton which inherits from it: >>> class s(singleton, C): ... def grail(self): ... print "grail:", self ... # At this point, s is *not* a class, it's an # *instance* of an anonymous class which inherits # from C. >>> s >>> s.spam() spam: >>> s.grail() grail: # (There's a slight problem with the naming of the # singleton's class at the moment -- it should really # be called "__main__.s", not "singleton.s"! Suggestions # on how to fix this are welcome.) #----------------------------------------------------- # # singleton.py # #----------------------------------------------------- import types class SingletonMaker(object): pass def __new__(self, name = None, bases = None, dict = None): if not name: # for bootstrapping return object.__new__(self) bases = bases[1:] # discard bases[0] == singleton if bases: metaclass = type(bases[0]) else: metaclass = types.ClassType return metaclass(name, bases, dict)() singleton = SingletonMaker() #----------------------------------------------------- # # End of singleton.py # #----------------------------------------------------- -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From thomas.berglund at minpost.nu Wed Jul 3 20:17:40 2002 From: thomas.berglund at minpost.nu (Thomas Berglund) Date: 3 Jul 2002 17:17:40 -0700 Subject: Parsing Message-ID: Hello all I'm new to this group and new to python =). I was thinking, as a first project, to have a program that would download a random quote from a homepage that gives such, parse all the html out of it and print it. Should be simple, no? Well, i've been messing around with something like this: urllib.urlretrieve("http://kisrael.com/quotes/", "temp.txt") f = open("temp.txt") for line in f.readlines(): if line[0] != "<": print line f.close() but, that's not really working out. I was just wondering if there was some kind of standard parsing library for python to help me get rid of those nasty html tags. Any pointers would me much appreciated. Have a nice day, and thanks. /Thomas From dstuart at orsys.com Wed Jul 31 11:12:06 2002 From: dstuart at orsys.com (Doug Stuart) Date: Wed, 31 Jul 2002 10:12:06 -0500 Subject: pyexpat error References: <3D47EB6A.344FE6FE@orsys.com> Message-ID: <3D47FE46.7DB7CACD@orsys.com> **** Post for FREE via your newsreader at post.usenet.com **** After doing some digging around I found where to set the LD_LIBRARY_PATH. After that I eventually got python compiled. Thanks for the help Doug Doug Stuart wrote: > **** Post for FREE via your newsreader at post.usenet.com **** > > "Martin v. Loewis" wrote: > > > Doug Stuart writes: > > > > > I am attempting to compile python with the Expat library included. > > I am > > > running Solaris 7 and python 2.2.1. Originally, I did the > > > 'configure-make dance' for python, then was told that I needed to > > add > > > the Expat library. I did the 'configure-make dance' for Expat > > (version > > > 1.95.4). I then went to redo my python doing a configure, make > > clean > > > and make. During the build of the pyexpat extension I get an > > warning > > > from line 1518 of Modules/pyexpat.c saying that subscript has type > > > char. It then removes the library because 'an error occurred." In > > the > > > setup.py script there is a setting for the EXPAT_DIR. I have tried > > > setting that to the directory where the Expat source files are > > located > > > and to the location of the library the Expat install creates. > > > > > > What am I missing here? > > > > Precise bug reporting. When it said 'an error occurred' - what > > precisely did it say? > > > > Could it be the case that you have compiled Expat as a shared library, > > > > and that your operating system won't find that shared library because > > the shared library is in /usr/local/lib? In that case, you need to set > > > > LD_LIBRARY_PATH, or apply one of the other 4 strategies to make > > Solaris find shared libraries. > > > > Regards, > > Martin > > I'm sorry but I am new to this sort of thing....here is the text of the > "error"... > > building 'pyexpat' extension > /orion/pkg/Python-2.2.1/Modules/pyexpat.c: In function > `get_version_string': > /orion/pkg/Python-2.2.1/Modules/pyexpat.c:1518: warning: subscript has > type `char' > gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DHAVE_EXPAT_H=1 -I. > -I/orion/pkg/Python-2.2.1/./Include -I/usr/local/include -IInclude/ -c > /orion/pkg/Pytho > n-2.2.1/Modules/pyexpat.c -o build/temp.solaris-2.7-sun4u-2.2/pyexpat.o > gcc -shared build/temp.solaris-2.7-sun4u-2.2/pyexpat.o -L/usr/local/lib > -lexpat > -o build/lib.solaris-2.7-sun4u-2.2/pyexpat.so > WARNING: removing "pyexpat" since importing it failed > > Where would I set the LD_LIBRARY_PATH? In my environment, the Setup > script or where? > And what are the 'other 4 strategies"? If you could point me in the > right direction it would be > most appreciated. > > TIA > Doug > > -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** > http://www.usenet.com > Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored > -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From joec at mill.co.uk Tue Jul 23 12:54:34 2002 From: joec at mill.co.uk (Joe Connellan) Date: Tue, 23 Jul 2002 17:54:34 +0100 Subject: passing a tuple of floats to C++ References: <3D3D761B.7925CC36@mill.co.uk> Message-ID: <3D3D8A4A.B3F2A67D@mill.co.uk> only that I didn't know about it ;) (new to extending) got it sorted now, thanks. Michael Hudson wrote: > Joe Connellan writes: > > > How would I go about passing a tuple of floats of an arbitrary (but > > large) size to C++ - would I use PyArg_ParseTuple()? > > I wouldn't. What's wrong with PyTuple_GetItem? > > Cheers, > M. > > -- > ARTHUR: Don't ask me how it works or I'll start to whimper. > -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From philippe.gendreau at savoirfairelinux.com Wed Jul 24 13:56:16 2002 From: philippe.gendreau at savoirfairelinux.com (Philippe Gendreau) Date: Wed, 24 Jul 2002 13:56:16 -0400 Subject: syntax questions In-Reply-To: ; from fredrik@pythonware.com on Wed, Jul 24, 2002 at 04:56:07PM +0000 References: Message-ID: <20020724135616.B23105@xmailer.ods.org> * Fredrik Lundh [2002-07-24 16:56]: > Philippe Gendreau wrote: > > I'm fairly new to python and there a thing I don't understand in the > > syntax. What is it with the "_". I have seen it used in many places for > > what seems to be different puposes like: > > > > from x import _ > > here, you're importing something named "_" (most likely > a function) from the x module. > > judging from your example, the "_" function is probably > used to translate strings from english to the local language. > > for some reason, people doing internationalization (i18n) and > localization (l10n) stuff seem to prefer to use functions called > "_", probably only to confuse people like you and me. lol, it is indeed a translation function. > > > Also, I'd like to understand this syntax: "((_(name),))" > > the _(name) part is simply a call to the translation function. > it could have been written like, say > > local_name = _(name) > > or even > > local_name = translate(name) > > the (x,) part creates a tuple containing a single item (see the > tutorial and the language reference for more info on tuples). > > a_tuple = (local_name,) > > the outermost () belongs to the append method call: > > theme.append(a_tuple) > > (according to the python style guide, and common sense, it's > bad style to put a space between the function/method name > and the parentheses...) I agree, I didn't write this code, but it just felt wrong. I'll have a look at the styleguide, thanks for the help. -- Philippe Gendreau From bogusdrop at myself.com Wed Jul 24 21:52:51 2002 From: bogusdrop at myself.com (TuxTrax) Date: 24 Jul 2002 18:52:51 -0700 Subject: Requesting a reference for a book on NNTP Message-ID: <30770aa4.0207241752.ace193b@posting.google.com> Hi all I am beginning a project in python, that will require a greater understanding of NNTP protocols (and python!) than I currently possess. It is a definite learning process and I suspect it will take me a long time to have a working beta up and running. I need to learn how clients query nntp servers for specific messages, what protocols are involved, how those protocols and commands are used, syntax involved, authentication methods: in short, I need a book that will teach me everything I would need to know to write a newsreader (as far as interfacing with the usenet servers are concerned), although that is not the project I am embarking on. Since I know that many programmers both amateur and professional, are active and lurking, I would like to ask for a reference to a good *beginners* book on the subject of NNTP and usenet that helps the inexperienced to understand the information. cheers, Mathew Xposted to comp.lang.python, comp.os.linux.advocacy From fredrik at pythonware.com Tue Jul 9 19:41:56 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 09 Jul 2002 23:41:56 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: <8xKW8.47005$n4.11322657@newsc.telia.net> Matt Gerrans wrote: > Anyway, that's assuming you have no control over the input; if that is the > case, you could filter it easily enough: > > if re.match(r'0x(\d|[a-f])*', string, re.I ): > n = eval(string) > else: > n = 0 # Could alternatively raise a ValueError, or something like that, > here. string = "0x0+__import__('os').system('echo 7h1s b0x 1s 0wn3d')" From fredrik at pythonware.com Thu Jul 4 11:13:54 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Jul 2002 15:13:54 GMT Subject: sending a file through sockets References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > so the trick is to convert a file to a string representation right? don't trust everything you read on comp.lang.python. I suggest reading the socket how-to before you start coding: http://py-howto.sourceforge.net/sockets/sockets.html From mis6 at pitt.edu Tue Jul 23 17:48:47 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 23 Jul 2002 14:48:47 -0700 Subject: A better self References: Message-ID: <2259b0e2.0207231348.7496eca0@posting.google.com> Personally, I have no problems in conforming myself to the established tradition and to use the standard self. However many people don't like self. It has not been mentioned in this thread, but there a simple way to cope with this problem without changing the language: a Python preprocessor. Suppose one define the pseudocode --begin pseudo.py-- from math import sin,sqrt class Example: y,z,t=1.0,1.0,1.0 def f(,x): return sin(.t)*x**.y+sqrt(.z) example=Example() print example.f(1.0) --end pseudo.py-- where the comma in f(,x) remind us that the first argument self is omitted. One can easily create a preprocessor that convert this code on standard python code converting (, ---> (self, and .something ---> self.something For instance the following code does the job (if you work on Red Hat Linux the first line has to be #!/usr/bin/python2): --begin pp-- #!/usr/bin/python from re import compile import sys def process(pseudocode): comma=compile(r'\(\s*,') dot=compile(r'[^\w_]\.[a-zA-Z_]+') code=comma.sub('(self,',pseudocode) end=0; newcode='' for found in dot.finditer(code): start=found.start() newcode+=code[end:start+1]+'self' end=found.end() newcode+=code[start+1:end] return newcode+code[end:] try: name=sys.argv[1] except: print "Usage: ./p2 programname.py" sys.exit() inp=file(name) out=process(inp.read()) inp.close() print out --end pp-- This is not perfect because it converts "(," and ".something" everywhere in the file, even in comments and in strings, however it can be refined. The point is that pp (Python Preprocessor) convert the pseudo code in normal code which can be executed. After a chmod u+x pp the user can type $ ./pp pseudo.py > normal.py to convert the pseudocode in standard code or even directly execute the pseudocode with $ ./pp pseudo.py | python Notice that the preprocessor also works with function with no explicit arguments, since f(,) is converted to f(self,) which is equivalent to f(self). The preprocessor idea is interesting, not only for people who want to create their own shortcuts to the language (I think it is better to use good habits and to use the standard language), but even for more serious jobs. -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From mwh at python.net Fri Jul 12 05:27:17 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 12 Jul 2002 09:27:17 GMT Subject: Recomendations on Books References: Message-ID: "Ray Tux" writes: > Hello I am a beginer to programming and I have chose Python. I was > just wandering if you guys could recomend some good Python Beginers > books. If you have a good internet connection, you may not need a book at all. There are a bunch of recommended guides here: http://www.python.org/doc/Newbies.html I have precisely one book on Python -- which I got for free because I did tech review for it -- and more than a shelf's worth of books on other languages. I guess one could draw conclusions from this :) Cheers, M. -- The only problem with Microsoft is they just have no taste. -- Steve Jobs, (From _Triumph of the Nerds_ PBS special) and quoted by Aahz Maruch on comp.lang.python From gmfawcett at operamail.com Thu Jul 4 15:13:33 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 4 Jul 2002 12:13:33 -0700 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 Message-ID: <3d799735.0207041113.3a830bdf@posting.google.com> Hi folks, I downloaded and am using version 0.3.2 of the fantastic Pyrex extension language ( http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ ) and am happily speeding up some crucial code using this marvellous product. However, I ran into a hitch when trying to build an extension class on my Win32 machine: the compiler complained with "initializer not a constant" errors. This is a known issue in Python; see the FAQ at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp . So I did a very ugly little hack on the pyrexc.py script to fix the problem. (The hacked script just runs pyrexc as usual, but then traverses each C file that pyrexc builds and applies the advice given in the Python FAQ. This is a brute-force and brittle approach. I expect it will break against a release of Pyrex > 0.3.2. (I should have taken the time to read Greg's compiler code and fix it there, but I've a temporary shortage of Copious Free Time.) Here's the revised script. #!/usr/bin/env python # # Pyrex -- Main Program, Unix # import Pyrex.Compiler.Main Pyrex.Compiler.Main.main(c_only = 1, use_listing_file = 0) # ---- added by Graham Fawcett # ---- fixes "Initializer not a constant" while building DLL on MS-Windows # ---- http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp HEAD_INIT = 'PyObject_HEAD_INIT(0)' TYPESTART = 'statichere PyTypeObject __pyx_type_' GETATTR = 'PyObject_GenericGetAttr, /*tp_getattro*/' SETATTR = 'PyObject_GenericSetAttr, /*tp_setattro*/' ALLOC = 'PyType_GenericAlloc, /*tp_alloc*/' FREE = '_PyObject_Del, /*tp_free*/' TYPEINIT ='''__pyx_type_%(typename)s.ob_type = &PyType_Type; __pyx_type_%(typename)s.tp_getattro = PyObject_GenericGetAttr; /*tp_getattro*/ __pyx_type_%(typename)s.tp_setattro = PyObject_GenericSetAttr; /*tp_setattro*/ __pyx_type_%(typename)s.tp_alloc = PyType_GenericAlloc; /*tp_alloc*/ __pyx_type_%(typename)s.tp_free = _PyObject_Del; /*tp_free*/ ''' def fix_c_file(pyx_filename): filename = pyx_filename.split('.')[0] + '.c' f = open(filename, 'r') lines = f.readlines() f.close() lines = [line.rstrip() for line in lines] types = [] f = open(filename, 'w') for line in lines: # strip the injurious assignments from the PyTypeObject def'n if line.startswith(HEAD_INIT): print >> f, 'PyObject_HEAD_INIT(NULL)' elif line.startswith(TYPESTART): typename = line[len(TYPESTART):].split(' ')[0] types.append(typename) print >> f, line elif line.startswith(GETATTR): print >> f, 'NULL,' + GETATTR.split(',')[1] elif line.startswith(SETATTR): print >> f, 'NULL,' + SETATTR.split(',')[1] elif line.startswith(ALLOC): print >> f, 'NULL,' + ALLOC.split(',')[1] elif line.startswith(FREE): print >> f, 'NULL,' + FREE.split(',')[1] elif line.startswith('void init') and line.endswith('(void) {'): print >> f, line # put the assignments in the module init function for typename in types: print >> f, TYPEINIT % locals() else: pass print >> f, line f.close() import sys if sys.platform == 'win32': for pyx_filename in sys.argv[1:]: fix_c_file(pyx_filename) # ---- end of addition Best wishes, -- Graham From ianb at colorstudy.com Wed Jul 17 02:37:00 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 17 Jul 2002 01:37:00 -0500 Subject: Using search fields on websites In-Reply-To: References: Message-ID: <1026887820.2095.525.camel@lothlorien.colorstudy.net> I would recommend using urllib/urllib2 to retrieve the web pages (using just the open function). If you aren't familiar with how forms work, you can probably figure out by example by looking at the URL you get from various searches -- in most search forms all the information you entered in the form gets passed through the URL. (If you don't see your search terms in the URL, you are probably using a POST form -- save the page and replace the POST in with GET, and replace the url with an absolute url, and try again). You should use urllib.quote to quote your search terms (since, for instance, you can't have a space in a URL -- urllib.quote will encode that space properly). On Wed, 2002-07-17 at 01:25, Jen wrote: > Hi All, > > I'm trying to use python to do searches on a website by entering a > string into a search field to search against the website's database. > > Currently I have a list of strings which I want to automate to enter > each into a textfield on a website, select a different radio button > from the default and submit for searching. Is there a way that I can > do this easily? > > If anyone could suggest not only the modules to use but also any > possible functions within the modules, that would be greatly > appreciated. Thanks. > > Jen > -- > http://mail.python.org/mailman/listinfo/python-list From correia_j at hotmail.com Thu Jul 4 16:44:44 2002 From: correia_j at hotmail.com (Jose Correia) Date: Thu, 04 Jul 2002 20:44:44 GMT Subject: Corrupt mxODBC installation? Message-ID: <0t2V8.25132$YC4.386257@news0.telusplanet.net> Decided to finally upgrade to Python 2.2.1 (from 1.5.2) and downloaded latest versions of everything incl mxBase 2.0.3 and mxODBC 2.0.4 Windows installer packages. Problem is the mxODBC module seems to be corrupt. The mx stuff is installed under the \site-packages\mx\ directory. Results on NT4 SP6 with (ActiveState) Python 2.2.1 build 222 installed: >>> sys.path ['', 'D:\\Python\\lib\\site-packages\\Pythonwin', 'D:\\Python\\lib\\site-packages\\win32', 'D:\\Python\\lib\\site-packages\\win32\\lib', 'D:\\Python\\lib\\site-packages', 'D:\\Python\\DLLs', 'D:\\Python\\lib', 'D:\\Python\\lib\\lib-tk', 'D:\\Python'] >>> import mx.ODBC.Windows >>> dbc = mx.ODBC.Windows.Connect('configdb', user='', password='', clear_auto_commit=0) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Connect' >>> mx.ODBC.Windows >>> mx.ODBC.Windows.__file__ 'mx\\ODBC\\Windows\\__init__.pyc' >>> dir(mx.ODBC.Windows) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> This last bit shows that there is indeed no "Connect" in the module. My previous version (also 1.5.2) on another machine shows loads of functions,etc when I used the dir() command on it. Does this sound like there's a problem with the module or am I completely missing something here? Been googling for prior version of the package but couldn't find any anywhere. If anyone has a link please let me know (any other suggestions would be welcome too, trying to beat the clock on this one). Alternatively, please e-mail the package (if my version size is correct it's only 130k). If emailing, remove Z's in address. Thanks in advance, Jose correia_jZ at Zhotmail.com From aleax at aleax.it Thu Jul 4 13:42:22 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 4 Jul 2002 19:42:22 +0200 Subject: metaclass & __slots__ In-Reply-To: References: Message-ID: On Thursday 04 July 2002 07:11 pm, Mark McEahern wrote: > [Alex Martelli] > [snip] > > > But, let's get into details: > > [snip] > > Alex, thank you for this very patient explanation of the fine details of > Python class creation. This helps me tremendously. You're most welcome! And, thanks right back for the feedback -- finding out which explanatory "takes" on hard subjects work best in written form is very helpful to me in determine how to write articles and book chapters about those subjects. I think the part that most needs to be fully explained and explored today is WHY one would want to write customized metaclasses, rather than HOW to write them (although the HOW is of course also necessary). There are, I think, few and somewhat marginal things that can ONLY be done with a customized metaclass (e.g., determining what comes out when the class object itself, rather than an instance, is printed). Most metaclass tasks could alternatively be handled with suitable __init__, __getattr__ &c special methods. But metaclasses can be simpler AND offer better performance. Moreover, what complexity remains inevitable can better be moved into a "framework", in such a way that a class-author does not need to worry all the time about niggling details, but can just rely on framework-supplied metaclasses to build the resulting class objects "just right", with whatever tweaked semantics are necessary. Still, until we get a good, solid tutorial set of examples comparing and contrasting the metaclass-way and the classic-way to perform some such set of tasks, I think this will remain rather hard to grasp in practice. And I'm still thinking about WHAT "good, solid tutorial set of examples" might be most appropriate for this... Alex From rs at onsitetech.com Tue Jul 9 13:03:26 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 17:03:26 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: <3D2B1710.4000101@onsitetech.com> I think we're actually agreeing about a lot here. Alex Martelli wrote: > ...The boundaries of any subsystem should be clean, with emphasis on > simplicity and clarity of working code rather than architectural > elaboration... I like how Python basically gives you access to whatever you want. Similar to Smalltalk. And then Python has ways to flag design intentions, which can be either heeded or ignored. I see "__." like this. I'm not looking to lock out 'junior' programmers, just to make the workings of the class clear when used from tools like help() or PythonWin IDE. Without using this flagging system, all variables and methods appear to be equally 'public'. So, back to my original gripe. I hate having to do 'self.__x' instead 'x' for an instance variable that: 1. Is part of the implementation, not the interface of a class. 2. Shouldn't be trampled over inadvertently by subclassers. ... and because, it's of course not just self.__x. It's also self.__b, etc. all being used together, combining to some unreadable code. Again, I'm not looking to 'lock other programmers out', just use Python's own tools correctly to flag design intentions or to document how code works. > I wrote: >> >>String name = (String) aVector.element(0) >> >>Python doesn't have any problems with implicitness here... > > > If you want to force a _string_ representation of aVector's first > element to be bound to variable name, you'll code: > name = str(aVector[0]) > which is roughly on a par with the Java construct Actually, AFAIK, that is _not_ on par with the Java construct. That ugly Java code isn't changing any kind of representation... All it is doing is allowing you to send a message to the object 'name' that's part of the String API. The message send may still fail "be not understood". In Java, you'd get a class cast exception. In Smalltalk, you'd get "Message not understood". Robb From shalehperry at attbi.com Wed Jul 31 16:20:18 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 31 Jul 2002 13:20:18 -0700 (PDT) Subject: ANN: Python Spread Module 1.3 Released In-Reply-To: <200207311455.g6VEtqQ00460@odiug.zope.com> Message-ID: On 31-Jul-2002 Guido van Rossum wrote: > I've released version 1.3 of the Spread Module for Python: > > http://www.python.org/other/spread/ > The spread site lists C++, Java, Perl and Ruby. You should get them to list python as well. From erno-news at erno.iki.fi Tue Jul 9 09:50:52 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 09 Jul 2002 16:50:52 +0300 Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: In article , m.faassen at vet.uu.nl (Martijn Faassen) writes: | They do kick you out a bit readily, I agree. I got somewhat annoyed | when I got kicked out while apologizing for spamming with a misfired | copy & paste buffer. it seems to be a part of the life cycle of an irc channel. first it is only a few people with an intimate atmosphere, then it starts attracting lots of people because of the friendly atmosphere, and in a while the intimate atmosphere gradually dissolves. then the "old timers" leave or start policing with an iron fist... it doesn't always go like that, but often. -- erno From logiplexsoftware at earthlink.net Wed Jul 3 14:13:54 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 11:13:54 -0700 Subject: HT clear some wxPython fram? In-Reply-To: References: Message-ID: <20020703111354.0c3320e9.logiplexsoftware@earthlink.net> On Wed, 03 Jul 2002 19:39:04 +0200 Klaus Reinhardt wrote: > >> HOW I CAN CLEAR SOME FRAME? > --------------------------------------------------------------------- BTW, you'll get a much better response to wxPython-specific questions if you post them to the wxPython users list rather than this one. You can subscribe at: http://www.wxpython.org/maillist.php Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From mwh at python.net Tue Jul 30 08:35:57 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 12:35:57 GMT Subject: lexing nested parenthesis References: Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > [Kristian Ovaska] > > > The language category you're dealing with is called context-free grammars. > > It's more expressive than regular languages, and it can parse any > > programming language. > > Any? :-) > > I would not go that far. There are strange beasts out there. I was once told that this doesn't even cover Python: the meaning of "a=b" depends on whether you're in an argument list or not. > Moreover, people usually throw good parts of the complexity in > "semantic analysis" passes. This is true of Python. Hopefully life will be better in the wonderful world of 2.3. > In the caricatural case, your grammar may parse individual > characters and leave it all to later compilation stages, so a > fortiori, any kind of parser will do. We are diving in the complex > art of compromises! :-) Even Python 2.2 doesn't go quite this far . Cheers, M. -- But since I'm not trying to impress anybody in The Software Big Top, I'd rather walk the wire using a big pole, a safety harness, a net, and with the wire not more than 3 feet off the ground. -- Grant Griffin, comp.lang.python From loewis at informatik.hu-berlin.de Fri Jul 26 04:00:42 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 26 Jul 2002 10:00:42 +0200 Subject: setup.py OS X issue References: <20020725194854985-0400@news.mindspring.com> Message-ID: "Chris Gonnerman" writes: > Have you considered giving more details? > > (perhaps the PSU was here... there's no punctuation at the > end of his last sentence... maybe they are But now they know your name. You should be afraid, very From malachi at NOSPAM.bardstowncable.net Sun Jul 21 14:59:29 2002 From: malachi at NOSPAM.bardstowncable.net (Owen Marshall) Date: Sun, 21 Jul 2002 14:59:29 -0400 Subject: NEWBIE: Removing HTML/JavaScript from a webpage Message-ID: <3D3B0491.4000605@NOSPAM.bardstowncable.net> Ok...here is my question. I have this bit of code: import urllib response = urllib.urlopen('http://movies.go.com/cgi/movielistings/request.dll?ZIPSPECIFIC&zip_code=40004&date=07/20/2002') resp = response.read() This grabs the movie playtimes for my area. Now, my big question -- how do I remove all of the junk Javascript and HTML? I stole this bit of code from somewhere: import re split = re.sub("<[^>]*>","",resp) But, this only removes the HTML -- the Javascript is still there; and I have no idea on how to modify that so it eliminates the script. Thanks! -o From wurmy at earthlink.net Mon Jul 1 18:36:58 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Mon, 01 Jul 2002 22:36:58 GMT Subject: Docstrings (was: Re: private) References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: <3D20D951.6040104@earthlink.net> James Kew wrote: >>I would think docstrings, comments, and naming conventions sufficient >>to provide a method for documenting what a class ought to be accessing. > > I think that's a journey I'm only just beginning. > > Is there any good newbie documentation for docstrings? After reading the > Tutorial, Library Reference, and most of Dive Into Python as shipped with > the ActiveState distribution they're still very much a mystery to me... Not sure there's much to document; the tutorial pretty much says it all. People use docstrings to document functions, classes and modules. This information can later be retrieved with the __doc__ attribute, for example: >>> def foo(x): """ Do something. """ return dosomething(x) >>> foo.__doc__ ' Do something. ' It is also used by the help() function: >>> help(foo) Help on function foo in module __main__: foo(x) Do something. The above is one of the reasons to use a docstring rather than a comment (which would serve the same purpose when eyeballing code). Another reason is that there are various tools out there that extract docstrings, and use them for e.g. generating documentation automatically, etc. HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From aleax at aleax.it Wed Jul 24 03:55:20 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 07:55:20 GMT Subject: A better self References: <2259b0e2.0207231348.7496eca0@posting.google.com> Message-ID: Michele Simionato wrote: > Personally, I have no problems in conforming myself to the established > tradition and to use the standard self. However many people don't like > self. It has not been mentioned in this thread, but there a simple way to > cope with this problem without changing the language: a Python > preprocessor. > > Suppose one define the pseudocode > > --begin pseudo.py-- > > from math import sin,sqrt > > class Example: > y,z,t=1.0,1.0,1.0 > def f(,x): > return sin(.t)*x**.y+sqrt(.z) ... > The preprocessor idea is interesting, not only for people who want to > create their own shortcuts to the language (I think it is better to use > good habits and to use the standard language), but even for more serious > jobs. Yes, but it doesn't fit smoothly with Python's normal work organization. Using an extension different than .py for the preprocessor-sources makes it OK for languages normally handled with makefiles, but that's not how you usually work in Python. If you want preprocessing, I suggest you integrate it differently: class Example(Prepro): ''' y,z,t=1.0,1.0,1.0 def f(,x): return sin(.t)*x**.y+sqrt(.z) ''' Prepro is an otherwise empty class whose metaclass is MetaPrepro. MetaPrepro's __new__ method gets Example's dict, containing only the __docstring__ with all the above source. It can change that source at will, the prepare the real dict with the needed entries and finally delegate up to type.__new__. I suggested a similar approach based on bytecodes, but even for source to source transformation (which is easier and better portable across different bytecode/VMs) I think it would be the right tack. Alex From Bill.Scherer at VerizonWireless.com Thu Jul 11 14:58:34 2002 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Thu, 11 Jul 2002 14:58:34 -0400 (EDT) Subject: struct unpack help? In-Reply-To: Message-ID: On 11 Jul 2002, Erno Kuusela wrote: > In article , "Scherer, > Bill" writes: > > | Here's a sample string of the struct: > > | sampleStructString = "_782c1a08_p_void" > > | I know that the struct defines only two unsigned shorts. That > | would imply (to me, anyway) a format of 'HH'. But calcsize of > | that is 4, while my string is 16 bytes. So > > it appears you have a different definition of a struct than the > struct module. if struct.calcsize('HH') returns 2, then it means > that on your platforms shorts are 2 bytes each. > > the "p_void" in your string makes me think it might encode a c pointer > (void *). the characters "782c1a08" might be a machine address, > interpreted as an ascii string containing a hexadecimal number. I received an off-list email that got things moving. I wasn't looking at a struct after all. The string came out of a swig generated module, and swig produces various _get and _set functions for dealing with the underlying structs from Python. Thanks to the help, Python can now answer the phone... > > -- erno > -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From aleax at aleax.it Sat Jul 20 03:37:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 07:37:23 GMT Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: eugene kim wrote: > thx again.. > > i got PyGreSQL(pyPgSQL gave me error ImportError: No module named libpq) > i looked at >>>>help(pgdb) > that was about all docs i could get including from web Can't help you much here -- I use psycopg for the same task (interfacing to PostgreSQL). You'll find that most DB interface modules more or less follow the Python DB API, http://www.python.org/topics/database/DatabaseAPI-2.0.html http://www.amk.ca/python/writing/DB-API.html (excellent, though it explains the previous DBAPI 1.0 so some detailed differences are inevitable) http://initd.org/pub/software/psycopg/dbapi20programming.tar.gz (you need TeX to format this one) etc, etc. > python looks really clean(<->perl), and requires a lot less > coding(<->java) so i'm trying to learn python.. Here we agree. > compared to other languages such as java/perl > it seems like it's really hard to find docs about python.. Here we don't. OK, in google python gives "just" 3,870,000 hits while perl gives 9,900,000 and java 25,800,000 -- but you're not going to read even 3 or 4 million documents anyway, are you? Sympathize rather with the plight of users of really unnown languages such as cobol (just 619,000 hits), fortran (1,470,000) or pascal (2,880,000)...:-) Seriously, if you know how to use google (and it's really easy) it's never really hard to find docs about anything: _filtering_ the overwhelming amounts of docs you get is the main problem, really. www.python.org has a lot of good links (and oodles of great docs on the site itself), too. > should i buy bunch of books? such as python cookbook? As a co-editor of the Python Cookbook I can hardly be unbiased, of course. It's a unique book, combining lots of recipes from the Python community in general (200+ of them), chapter introductions from over a dozen leading Python figures, AND lots of hard editing work from me, David Ascher, and the unsung heroes in O'Reilly's staff, putting it all together into a consistent, complete whole while leaving the distinctive "voices" of the 100+ authors as intact as we could. I think we made it, but, of course, what matters is the _readers_' opinion, and we can't know that yet (the book's going to be formally launched at OSCON in a few days). But, while unique, it IS just one book out of many excellent Python titles! Steve Holden's "Web Programming with Python", for example, is an excellent introduction (I'm biased about it too, because Steve's a friend and I was a technical reviewer for his book, but to a lesser extent than for the Cookbook!-) -- not just to Python, but to the host of technologies you need to build a really good site, including HTML, HTTP, relational databases with a bit of entity-relation design and SQL, XML. Unless you already master the basics of most of these, it would be THE book to get even if you planned to use all of these technologies _except_ Python...!-) More generally, I'm biased because I just LOVE books. The web's just fine, and there's a LOT of good stuff out there, but, ah, a book! Holding it in my hands, touching and smelling and hefting it, carrying it around to read on buses, planes, trains -- it will be a long time before any technology can really compete with it:-). Alex From wdraxinger at darkstargames.de Wed Jul 10 17:12:14 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 10 Jul 2002 23:12:14 +0200 Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> Message-ID: <3D2CA32E.9060203@darkstargames.de> Ok, I took a very carefull look into the sources, and it seems, that the problem is not that hard I thought before and ripping the code is just mad, though not impossible: Many of the builtin modules can be removed at compile time using config.h. All the modules that can be problematic can be removed without problems except 3: sys and some builtin functions. Now my question. How can I replace them with my own stuff? I don't want to do things like Py_RunSimpleString("import engine; import sys; sys.stdout=engine.stdout") I'd appreciate if I could replace it on a pure 'C' basis. Replacing the original code were ideal. An absolute must is overriding file access, due to the virtual file system. So where can I hook? -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From aleax at aleax.it Tue Jul 9 11:21:49 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 15:21:49 GMT Subject: Converting a hex string to a number References: <4b628986.0207090252.5338178d@posting.google.com> <3d2adb64$0$12283$e4fe514c@dreader4.news.xs4all.nl> Message-ID: me wrote: ... > Like this solution. Is there a way to use that long as hex, so bit > operations can be done on it piecewise? Slice a byte, then xor it or > and it, and put it back? Longs, like ints and other kinds of numbers, are immutable -- so each time you change even one bit you're allocating a new one and copying all the rest. Use an array.array with a typecode of 'B' (unsigned bytes), it may prove substantially better-performing as it's mutable. Alex From peter at engcorp.com Sun Jul 21 01:12:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Jul 2002 01:12:38 -0400 Subject: maximum recursion depth References: Message-ID: <3D3A42C6.EB9EA9A@engcorp.com> Paul wrote: > > My question to you: Is there a way to change the limit of the recursion > depth? Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 >>> import sys >>> dir(sys) [ ...snippety snip, 'setcheckinterval', 'setprofile', 'setrecursionlimit' ... ] >>> print sys.setrecursionlimit.__doc__ setrecursionlimit(n) Set the maximum depth of the Python interpreter stack to n. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform- dependent. >>> sys.setrecursionlimit(2000) >>> :-) From whisper at oz.net Thu Jul 18 21:50:24 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 18 Jul 2002 18:50:24 -0700 Subject: win32com: makepy causes ie problems. Message-ID: While trying to figure out how to make the recently posted (by Paul Rubin) ie navigation example work, I had occasion to run makepy.py on "Microsoft Internet Controls". After doing this, the sample would fail on "ie.visible = 1". Removing the generated file would return the sample to working order. Sample: from win32com.client import DispatchEx import time ie = DispatchEx('internetexplorer.application') ie.visible = 1 ie.navigate('http://www.w3.org') time.sleep(2) # let the browser get to it, but sloppy - how to wait on browser ready? dom = ie.document I'm also interested, as the comment suggests, on how to wait for a browser to finish navigating before I query it's state? Come to think of it, is there any way to get back an error status like "403"? :) David LeBlanc Seattle, WA USA From aleax at aleax.it Wed Jul 17 03:15:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 17 Jul 2002 07:15:03 GMT Subject: simultaneous iteration of lists References: Message-ID: Dave Harrison wrote: > Evenin' all, > > Looking for advice on simultaneous iteration of two lists. ... > for i,j in list1,list2: for i, j in zip(list1, list2): Alex From mh at esh-online.de Mon Jul 15 10:40:49 2002 From: mh at esh-online.de (Michael Hoffmann) Date: Mon, 15 Jul 2002 16:40:49 +0200 Subject: could not import mod_python.apache Message-ID: Hi, I've the folowing Error when I try to run my pythonscript: make_obcallback(): could not import mod_python.apache. make_obcallback(): could not call init. [Mon Jul 15 16:12:46 2002] [error] [client 62.226.50.138] python_handler: make_obcallback returned no obCallBack! but httpd start is ok: [Mon Jul 15 16:14:54 2002] [notice] Apache/1.3.19 (Unix) (SuSE/Linux) mod_python/2.7.2 Python/2.0 mod_ssl/2.8.3 OpenSSL/0.9.6a PHP/4.0.6 mod_perl/1.25 mod_th rottle/3.0 mod_layout/1.0 mod_fastcgi/2.2.2 mod_dtcl configured -- resuming normal operations [Mon Jul 15 16:14:54 2002] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) The directives are: AddHandler python-program .py PythonHandler mptest PythonDebug on Options +ExecCGI the script ist: from mod_python import apache def handler(req): req.content_type = "text/plain" req.send_http_header () req.write ("Hello World!") return apache.OK any Idea????? Regards Michael From martin at v.loewis.de Tue Jul 2 03:22:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Jul 2002 09:22:43 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: "Mike C. Fletcher" writes: > Well thinks I (stupid I), I'll just use the natural 8-bit transfer > format for Unicode, utf-8. When I do that, I get weird "Unicode > errors". For instance (simplified example): > > >>> unicode( u'\ud800\udb7f\udb80\U0010fc00\udfff'.encode('utf8'),'utf8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: UTF-8 decoding error: unexpected code byte > >>> u'\ud800\udb7f\udb80\U0010fc00\udfff'.encode('utf8') > '\xa0\x80\xad\xbf\xae\x80\xf4\x8f\xb0\x80\xed\xbf\xbf' > >>> > > I was under the impression that utf-8 was supposed to be able to > support any Unicode character with full back/forth translation. That impression is incorrect: Surrogates (as reserved in Unicode, for use with UTF-16) are special. Regards, Martin From nmclean at evokeit.com.au Wed Jul 24 07:02:30 2002 From: nmclean at evokeit.com.au (Nick) Date: Wed, 24 Jul 2002 19:02:30 +0800 Subject: visual basic 6 Message-ID: <001301c23301$9fe3b740$0c00a8c0@Sanchez> Hi my name is Nicholas and I am using visual basic 6 at school but I am have difficulty with understanding what my teachers is trying explaining and I was wondering if you had any information like a beginners guides that could help me. Thanks Nicholas Mclean nmclean at evokeit.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From SBrunning at trisystems.co.uk Wed Jul 3 05:13:06 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 3 Jul 2002 10:13:06 +0100 Subject: Useful RE patterns (was: Variable Interpolation - status of P EP 215) Message-ID: <31575A892FF6D1118F5800600846864DCBD49B@intrepid> > From: Simon Brunning [SMTP:SBrunning at trisystems.co.uk] > Interesting project. But you might want to call it something else - there > is > already a SimpleParse. See > ml > > and > ml > >. Doh! That 2nd URL should have been . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From mertz at gnosis.cx Thu Jul 4 00:53:09 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 04 Jul 2002 00:53:09 -0400 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: <1S9I9kKkXwHQ092yn@gnosis.cx> |> if isinstance(source, type) or isinstance(source, types.ClassType) |> return source() |> else: |> return copy.copy( source ) |that is exactly what i did. but i dont like this solution cause |as i told before it is rather implicit than explicit. FWIW, I faced much the same sort of problem answering these niggly questions across Python versions, and old- and new-style classes. While I can't promise I have the final and best solutions to such questions, I collected a bunch of (mostly binary) functions together in my gnosis.util.introspect module. The package encompassing introspect.py can be found from: http://gnosis.cx/download/Gnosis_XML_Util.ANNOUNCE Btw. introspect.py works perfectly well in Python 1.5.1 through 2.2 (with just a slight bit of version checking involved). I welcome any suggestions on what other helper functions might be useful in answer these introspective questions. I'd love to include more; and I'd especially love to have a well-known module (like mine :-)) that collected the best answers in one place. -- ---[ 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 jonathan at onegoodidea.com Thu Jul 25 04:40:58 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 25 Jul 2002 09:40:58 +0100 Subject: how to count lines in a file ? References: Message-ID: On 25/7/2002 0:18, in article mailman.1027552836.24420.python-list at python.org, "Delaney, Timothy" wrote: > Another patch is being worked on because putting a file in a cycle would > kill *lots* of (broken) code written as above. Although the above is not as > bad as *writing* to a file and not closing it ... but the principal is the > same. > > The python developers don't want to break code if they can avoid it - I > personally would be in favour of files not being collected immediately as it > would remove *any* legitimacy from arguments that "this is OK because it's > what the implementation does". I don't want to start an old flamewar, but "broken" depends on your point-of-view. Before Python had garbage collection, the semantics of object allocation and deallocation were quite simple and could be relied upon. This meant that Python was one of the few languages that had useful semantics for __del__. Reference counting wasn't a particular implementation, it was the way Python worked. Such usage only became "broken" when cycle garbage collection was introduced and people started to rely on the fact that they could create cycles and let the cycle-gc sort it out later. Unfortunately, "later" is a woolly concept with cycle-gc. -bah-this-is-why-I-was-against-cycle-gc-in-the-beginning-ly y'rs, Jonathan From gerhard.haering at gmx.de Tue Jul 23 00:21:56 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 23 Jul 2002 04:21:56 GMT Subject: Alex Martelli is off the net for a few days :-( References: <200207221011.g6MABTVa009663@ratthing-b246.strakt.com> <3D3C9AF9.BB6D1AC7@engcorp.com> Message-ID: Peter Hansen wrote in comp.lang.python: > Gerhard Haering wrote: >> >> * Laura Creighton [2002-07-22 12:11 +0200]: >> > Some construction workers have severed his phone and internet lines. >> > Expect him back in a few days, not a few hours. :-( >> >> Laura, don't lie. I saw you sneek in at night to cut off his cables in order to >> make him work productively again ;-) > > Ouch! Is "cut off his cables" a euphemism for something very painful? Well, I supposed that Laura only cut off his internet and phone lines and is now framing the construction workers. As bots don't feel pain - they even don't need any sleep, as Alex's recent message mentioning 40 hours weeks shows - I don't think anybody would attack them /physically/. Messing with the bot's software is much more fun. That's an interesting topic btw., I'll put it on the agenda of the next meeting of the P From sbalu at nyx.net Wed Jul 17 11:32:44 2002 From: sbalu at nyx.net (sarayu balu) Date: 17 Jul 2002 09:32:44 -0600 Subject: Sharp Zaurus Message-ID: <1026919964.826307@irys.nyx.net> Hi, Is there any Python, more appropriately Jython, for this PDA ? Is Jython Open Source ? Thanks, SB From claird at starbase.neosoft.com Thu Jul 11 09:04:48 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 11 Jul 2002 08:04:48 -0500 Subject: Python in the enterprise: Pros and cons References: Message-ID: <3962B981CBF8BA3C.FC44CF01C7D6700F.D17D6744589A142C@lp.airnews.net> In article , Bo M. Maryniuck wrote: >On Thursday 11 July 2002 11:47, Tim Peters wrote: >> > What the buzzword "the enterprise" is? >> It's an especially annoying American buzzword for "business use, as opp= >osed >> to consumer, research, or educational use". =20 > >Ah, Bill Gates buzzword again. Excuse me... Therefore according to this=20 >explanation, seems that LISP or Scheme are enterprise too, except of=20 >"high-phrases" AKA "...our very educated managers...", "...our high=20 >business...", "...our success in the market..." and so on. . . . While you probably recognized the humor in timbot's reply, it's hard to appreciate from the outside its analytic perfection. His definition PRECISELY cap- tures the arrogance and anti-intellectualism that "enterprise" generally bears. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From tim at remove_if_not_spam.digitig.cix.co.uk Mon Jul 1 08:47:26 2002 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Mon, 01 Jul 2002 12:47:26 GMT Subject: xslt on windows References: Message-ID: <3d204ef7.15906605@usenet.plus.net> I suspect that's the same problem I'm having with 4suite under Windows ME, but nobody has come back to me, either. I don't really know where to go next except maybe to report it as a bug (at least in the installation script if not in 4suite itself) On Fri, 28 Jun 2002 17:26:01 +0200, "Marko Faldix" wrote: >Hello, > >I tried installing 4suite's xslt on Win 2000, but I really don't know how to >deal with pathes. > >I used > > Python-2.2.1.exe > win32all-146.exe > 4Suite-0.12.0a2.win32-py2.2.exe > >All scripts, wether if command-line or through web server, doesn't know >module xml.xslt. > >Unfortunately, you can't import a module *.site-packages.*, where * is >anything, because "-" is forbidden as part of module names. > >Also, you can't copy directories from site-packages to c:\python22, they >don't work properly then. > >Is there anybody using xslt with python? Maybe better with linux in place of >windows? > >Best wishes, >-- >Marko Faldix >M+R Infosysteme >Hubert-Wienen-Str. 24 52070 Aachen >Tel.: 0241-93878-16 Fax.:0241-875095 >E-Mail: marko.faldix at mplusr.de > > From fredrik at pythonware.com Tue Jul 9 20:04:11 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jul 2002 00:04:11 GMT Subject: php function "addslashes" / "removeslashes" in python References: Message-ID: <%RKW8.47006$n4.11323296@newsc.telia.net> Lowel Stern wrote: > Does anyone know if this exists already? if you're doing database, you really should learn to use bound parameters... but if you insist, this might be a pretty good approximation: import re def addslashes(string, sub=re.compile(r"[\\\"']").sub): def fixup(m): return "\\" + m.group(0) return sub(fixup, string) def removeslashes(string, sub=re.compile(r"(?s)\\(.)|\\").sub): def fixup(m): ch = m.group(1) if ch is None: raise 'Parse Error: backslash at end of string' if ch not in r"\\\"'": raise 'Parse Error: unsupported character after backslash' return ch return sub(fixup, string) From Chris.Barker at noaa.gov Wed Jul 17 13:23:41 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Wed, 17 Jul 2002 10:23:41 -0700 Subject: python2 import trouble (linux - redhat) References: <20020714141757.128895ce.mmellor1@yahoo.com> Message-ID: <3D35A628.A9ADF9B6@noaa.gov> Joseph Wilhelm wrote: > I believe, off the top of my head, that all of the Python packages you > have installed are only for Python 1.5.2, since this is the default > Python distribution provided in RedHat (Although this appears to have > changed in the most recent beta! Woohoo!). What have they changed it too? Please, please tell me that they are using something like: #!/usr/bin/python2.2 (or whatever version) for their admin tools. The point is that the problem with redhat has not been that it uses 1.5.2. but that all the admin tools require 1.5.2 to by what "python" invokes. If they has specified the version on thei #! lines, then it would be no problem to install newer versions as well, and they probably would ahve provided packages to do so as well. If all they have done is upgrade to 2.2 or whatever, then we'll all have the same problem in a another year or two :-( -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From smarsh at hotmail.com Thu Jul 4 21:22:45 2002 From: smarsh at hotmail.com (scott) Date: Fri, 05 Jul 2002 01:22:45 GMT Subject: Is Python growing? References: <3D1D3D34.6080001@hotmail.com> <3D22263A.8090007@hotmail.com> Message-ID: <3D24F4D1.D136D730@hotmail.com> Gerhard H?ring wrote: > > * scott [2002-07-02 22:16 +0000]: > > Gerhard H?ring wrote: > > [help builtin only available in Python 2.2 or later] > > > > You are mistaken Gerhard. 2.1.1 (Activestate on NT4) is demonstrated > > below: > > > > bash-2.02$ python > > ActivePython 2.1.1, build 212 (ActiveState) > > Python 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32 > > Type "copyright", "credits" or "license" for more information. > > Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman > > It's either ActiveState or your Alternative ReadLine that's installing > pydoc.help as a builtin. In the standard Python 2.1.x, it isn't there. > > Gerhard bash-2.02$ cd /Python21 bash-2.02$ cat changes-ActivePython.txt ActivePython changes to Python ------------------------------ This document describes changes made to the core Python sources by ActiveState Tool Corp. for the ActivePython distribution. 1. The Python interactive shell version/copyright-info message was extended to properly identify the Python executable as ActivePython (with the appropriate ActivePython version number). 2. Aesthetic changes were made to the standard Python documentation. ****3. Add the "help" command which calls Ping's pydoc.help**** 4. Include the Tools/ directory in the installation. (a change to the Un*x make install target). 5. Minor build system changes to compile the _tkinter Python extension module. 6. Improve the error messages for Ping's pydoc when it is called from Unix with a wrong version of Python. -- ActiveState Tool Corp. 18 April, 2001 From donn at u.washington.edu Tue Jul 16 12:46:00 2002 From: donn at u.washington.edu (Donn Cave) Date: 16 Jul 2002 16:46:00 GMT Subject: Making code 2.1 compatible References: Message-ID: Quoth Tim Peters : ...(quoting me) |> Matter of perspective. I would probably have picked 2.2 if it |> had been left to me, just because it's current. But when I've |> proposed it in the past I've suggested the recently out-of-current |> release, because that makes it immediately an issue. | | Toward what end? They're business people, not Crusaders . Oh, don't be so hard on them, sure they're crusaders (though not in the sense of the European military adventures some centuries back or the popular music group known in better days as Jazz Crusaders.) They aren't going to be as hasty and radical, but I bet you won't be disappointed, they're on their way. (Now if a certain Redmond, Wa. software company were in the host, I'd sweat it, but "business people" here seems to be actually a pretty respectable assemblage.) Donn Cave, donn at u.washington.edu From peter at engcorp.com Sat Jul 20 13:25:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Jul 2002 13:25:57 -0400 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: <3D399D25.F766A041@engcorp.com> Rhymes wrote: > > On 20 Jul 2002 11:21:00 -0400, aahz at pythoncraft.com (Aahz) wrote: > > >Yes, it is, unless you're using some strange meaning for "built-in" far > >removed from its normal meaning. > > sorry, "default" not "built-in" Well, neither are regular expressions, trigonometric math functions, graphics, sockets, access to many operating system features, and a host of other useful "standard" features. That's the whole point of packages of course. Just treat the "from __future__" statements as any other package and you'll be fine. -Peter From oliver.eichler at dspsolutions.de Wed Jul 17 06:07:55 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Wed, 17 Jul 2002 12:07:55 +0200 Subject: get a list printed in hexadecimal notation Message-ID: Hi Is it possible to print a mixed list with strings and numbers and having the numbers printed as hexadecimal notation? something like: >>>l = ('spam',10,15,'more spam') >>>print l ('spam',0xA,0xF,'more spam') or similar... The only way I could think of is to write my own print function. Is there an easy way? Oliver From mgerrans at mindspring.com Wed Jul 10 13:30:05 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 10 Jul 2002 10:30:05 -0700 Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: Excellent explanation -- thanks! I wrote a simple little DOS/Python shell a while back that allowed me to keep Python loaded and run any script like a normal command (using execfile) or any DOS command -- it was quite useful on my laptop, epecially combined with a simple make (Python) script for a Java project. With this combination and using Jikes, it beat the pants off ANT for performance. I was doing this: def runScript(filename): namespace = { '__name__' : '__main__' } execfile(filename, namespace) return namespace Which was suggested to me by someone in this group. Now I see it is setting up an almost empty dictionary for the called script -- just the __name__=='__main__' so it will think it was being called from the command line. From claird at starbase.neosoft.com Wed Jul 10 16:01:37 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 10 Jul 2002 15:01:37 -0500 Subject: Pyrhon language dedicated Wiki References: Message-ID: In article , Jean-Claude Wippler wrote: . . . >It's a mindset issue. Get three people together, then four, then five, >and just do it. Fill pages, create lists, set up a page of who's who, >of conference info, of little tricks and treats, of companies, whatever. >Ignore the naysayers, and don't think about how "important" it is. > >Oh, and don't fall into the trap of debating how to improve the wiki :) > >It worked for Tcl, it'd be grand to see it work for Python too. > >-jcw It's working spectacularly for Tcl. Any time Jean-Claude writes, "Just do it", his advice deserves attention. The counsel above is wise. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jnana4 at DELETEhotmailCAPS.com Wed Jul 31 02:33:06 2002 From: jnana4 at DELETEhotmailCAPS.com (jano) Date: Wed, 31 Jul 2002 06:33:06 GMT Subject: beginner's question References: <66o19.694966$352.150300@sccrnsc02> Message-ID: "Jonathan Hogg" wrote in message news:B96C0D6C.EC62%jonathan at onegoodidea.com... > On 30/7/2002 4:54, in article 66o19.694966$352.150300 at sccrnsc02, "jano" > wrote: > > > /usr/lib/python2.1/site-packages/Ft/Lib/TestSuite does exist, and I am > > uncertain why python does not see this. I would expect python to check in > > the /usr/lib/python2.1/site-packages directory to look for 'Ft', but it > > doesn't seem to be doing this. I am probably making a silly mistake, and > > any help would be appreciated. > > Try checking first that you're running the right Python (or the test script > is) - just in case you have two copies installed. Then try invoking Python > (the right one ;-)) and do: > > >>> import sys > >>> sys.path > [ .... ] > >>> > > to see where it's looking for modules. Hmm, thanks for your help. I did as you suggested. I do have 2 versions installed, but verified that it was running the correct version (1 is 2.1 under cygwin, and the other is 2.2 under win2k), and it was running 2.1 as is correct. And checking sys.path shows that the directory that contains Ft (/usr/lib/python2.1/site-packages) is in the path. Any other suggestions? From chad_pettit at xontech.com Fri Jul 12 11:02:40 2002 From: chad_pettit at xontech.com (Chad Pettit) Date: Fri, 12 Jul 2002 11:02:40 -0400 Subject: XPM Message-ID: <3D2EEF90.60408@xontech.com> Does Python 2.2 support XPM image formats? If so, how can I load an existing xpm image independent of the current working directory? (Import like functionality) Thanks From kalab at gmx.net Tue Jul 9 04:14:54 2002 From: kalab at gmx.net (Gerhard Kalab) Date: 9 Jul 2002 01:14:54 -0700 Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> <81CC01E58BF2A99B.DFCD5EC6E4654907.32D731380951B9CA@lp.airnews.net> <3D189A8A.577C8186@earthlink.net> <3D18A6D2.5080404@dmsware.com> <3D18D159.2F66A9E8@earthlink.net> Message-ID: Joseph A Knapka wrote in message news:<3D18D159.2F66A9E8 at earthlink.net>... > Paolo Invernizzi wrote: > > Concerning elipse and python, I think there are 2 roads. > > The first one is using jpe (http://sourceforge.net/projects/jpe) the > > python-java framework. I've tried it some time ago... and I managed to > > execute python code from a java VM (a jython prompt in reality! ;) but > > I stopped there. Perhaps Frederic Giacometti and jython folks can give > > some help! > > > > The second one is to use socket (is possible?) to connect to a python > > server application... (with the plus that switching various python > > versions is very easy)... and move some logic in python (fast > > development times ;) > > > > The problem, as usual It's that I have no time ;( > > I think the latter is the best way. It's not clear, though, > that these are the only two roads. But in any case, we must > IMO be able to debug code under any Python version, preferably > selectable among a number of different installed versions > on the same machine (Eclipse allows this with the JVM, so > I don't see why it would be a problem for Python). That > way we could support CPython and Jython equally well. > I've had a quick look at HAP remote debugger and it looks promising. The client part has to be compiled whith each CPython version. I don't know about Jython. IMHO it's the fastest way to get startet since the client portion can be used immediately. I've put something to start at http://www.kalab.com/freeware/pythoneclipse/pythoneclipse.htm Included is an incomplete Python editor and the possibility to launch Python scripts. Currently it's only possible to specify one python interpreter for the launch configurations. Gerhard From ruediger.maehl_nospam at web.de Thu Jul 4 03:11:36 2002 From: ruediger.maehl_nospam at web.de (Ruediger Maehl) Date: Thu, 4 Jul 2002 09:11:36 +0200 Subject: Reportlab References: Message-ID: "Marcus Vinicius Laranjeira" schrieb im Newsbeitrag news:mailman.1025728208.17535.python-list at python.org... > Does anyone here uses Reportlab to create charts !? If you means buisness charts like bar or pie charts, then yes, I am using the ReportLab Toolkit for that kind of stuff. > I need some help about this, but I could'n find anywhere .... Since > reportlab is a library to create graphics, pdf and charts with python... I > hope someone here uses it ! > > then we could talk in pvt ! R?diger From walton.102 at osu.edu Mon Jul 8 03:19:43 2002 From: walton.102 at osu.edu (daniel walton) Date: Mon, 8 Jul 2002 03:19:43 -0400 Subject: linking OpenGL frameworks in osx Message-ID: I have a python module that I am trying to build using distutils under osx. I need to link against the OpenGL framework. I tried 'extra_link_args=['-framework OpenGL'], as well as specifying it as a regular library. any ideas? on a side note, does anyone know the status of pyopengl on osx? dan From mmellor1 at yahoo.com Sun Jul 14 14:17:57 2002 From: mmellor1 at yahoo.com (Mike Mellor) Date: Sun, 14 Jul 2002 14:17:57 -0400 Subject: python2 import trouble (linux - redhat) Message-ID: <20020714141757.128895ce.mmellor1@yahoo.com> Hello - I am using RH7.2, and have the following python packages installed: python-devel-1.5.2-35 rpm-python-4.0.3-1.03 pygtk-0.6.8-3 python2-docs-2.2.1-1 pygnome-libglade-1.4.1-3 python-xmlrpc-1.5.0-1 pygtk2-1.99.8-2 pygtk-glarea-0.6.8-3 python2-devel-2.2.1-1 PyXML-0.6.5-4 pygtk-devel-0.6.8-3 python2-2.2.1-1 pygtk2-libglade-1.99.8-2 python-1.5.2-35 pygtk-libglade-0.6.8-3 python2-tkinter-2.2.1-1 pygnome-1.4.1-3 python2-tools-2.2.1-1 I am having trouble importing modules with python2 (Python 2.2) that I think should be there, for example, _gtk and GTK. What do I need to do to get python (actually python2) to import these modules? Thanks. Mike From phr-n2002b at NOSPAMnightsong.com Tue Jul 30 06:05:43 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 30 Jul 2002 03:05:43 -0700 Subject: signature for a file ? References: Message-ID: <7xeldlh6o8.fsf@ruckus.brouhaha.com> You don't say what OS you're running. Anyway if two files have the same MD5 checksum, it's basically certain that the files are identical. So your basic strategy is: for each file in your system: c = md5 checksum of the file print c and the pathname leading to the file Then take the output of the above and sort it so all the identical md5's end up next to each other in the output. Then find all the sets of files with identical md5's and print out their paths so you can investigate further, get rid of one copy, etc. From shagshag13 at yahoo.fr Mon Jul 8 12:33:01 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 8 Jul 2002 18:33:01 +0200 Subject: Numarray vs Numpy Message-ID: Which one is the best ? thanks s13. From markus.vonehr at ipm.fhg.de Thu Jul 25 05:04:26 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 25 Jul 2002 11:04:26 +0200 Subject: DOS-Shell hangs up, python/Tkinter Message-ID: <3D3FBF1A.C1531FB3@ipm.fhg.de> Hi, when I start my python/Tkinter apps out of a MS-DOS shell and kill the app, very often the DOS-prompt doesn't come back, the Shell hangs-up. Anyone can tell me where the problem is? Thanks in advance, Markus From Gabe.Newcomb at noetix.com Thu Jul 25 14:30:23 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Thu, 25 Jul 2002 11:30:23 -0700 Subject: Tkinter Grid manager question redux Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F613F@NOXMAIL.noetixad.com> (Re-posting, since posting as a RE: message didn't seem to help my cause :)) This has gotten me the answers I need (thanks), but for one thing: I can't seem to get sticky to position a widget within a cell. I'm wondering what I could be doing wrong. Try this little example: root = Tk() f1 = Frame(root) f2 = Frame(root) f1.grid(row=0,column=0,sticky=N+E+W+S) f1.grid(row=0,column=1,sticky=N+E+W+S) l1 = Label(f1,text='L1 here',relief=SUNKEN) l2 = Label(f2,text='L2 here',relief=SUNKEN) l1.grid(sticky=W) l2.grid(sticky=E) I would expect it to create a root window with two frames next to each other (it does that). In each frame, the label should appear, and the one on the left should be all the way to the left of the frame, while the one in the right frame should be all the way to the right of the frame. In practice, however, both labels end up on the opposite sides of the frames (the left one is on the right side of the frame, and vice-versa. Am I doing something wrong here, or do I need to approach this a different way? FYI: If I try fixing the size of the frames and then using frame.grid_propagate(0) for each frame, the labels end up in the center of each frame. Thanks, Gabe -----Original Message----- From: jepler at unpythonic.net [mailto:jepler at unpythonic.net] Sent: Tuesday, July 23, 2002 7:56 PM To: Gabe Newcomb Cc: python-list at python.org Subject: Re: Tkinter Grid manager question By default, a frame ignores the width= and height= it is given, and instead calculates the amount of space needed by the widgets it manages via grid or pack. You can tell the grid manager that it should not behave in this way, and should instead take the width= and height= you select for the frame and parcel that space out to the managed widgets: f1.grid_propagate(0) now, f1 will be 900x100 Similarly, if you "grid" things into f1_1 you need to run f1_1.grid_propagate(0) if you "pack" things into f1_1, you need to run f1_1.pack_propagate(0) If you want to make sure the rows are the same width, you need to set the weight (again on the master): for row in range(4): f1.grid_rowconfigure(row, weight=1) now, f1_1, f1_2, f1_3, and f1_4 will be configured to get equal shares of the height of f1. If you still don't get a layout exactly 225 pixels wide, this is probably because of the borderwidth. For instance, if you configure a frame width a thick border and then make another frame inside, the inner frame is smaller (shifting to tcl since that's easier to do): %frame .f -bd 25 -relief raised -width 100 -height 100 frame .f.f pack prop .f 0 pack .f pack .f.f -expand 1 -fill both wm geo . winfo geo .f winfo geo .f.f . and .f have geometries of 100x100, while .f.f is only 50x50, due to the border of .f. Geometry management in Tk is a somewhat complex issue, and you have to expect to play with the options before you get what you want. Usually you will want to have as few intervening levels of frames as possible. Jeff -- http://mail.python.org/mailman/listinfo/python-list From mgilfix at eecs.tufts.edu Fri Jul 26 17:04:56 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 26 Jul 2002 17:04:56 -0400 Subject: Let's Talk About Lambda Functions! In-Reply-To: <030801c234de$00827950$5f01000a@opentable.com.ot>; from shecky@experimentzero.org on Fri, Jul 26, 2002 at 12:52:38PM -0700 References: <20020726024901.2725.176.Mailman@mail.python.org> <030801c234de$00827950$5f01000a@opentable.com.ot> Message-ID: <20020726170456.B10773@eecs.tufts.edu> Now this one could start a flame war and the answer itself is impenetrable, I'm sure. I assume you do know what functional programming is... But a few key highlights to start you off in your quest for why: proponents of FP believe the software to be much less error prone and easier to maintain (as it's easier to track down the source of bugs). Much of this stems from the fact that proper functional programming makes the use of side-effects more difficult and makes the general program flow much easier to follow; implied iteration via the map() function, for example, reduces code clutter and a possible error in the looping code. Functional programs also tend to make use of the generate and test paradigm, one which can offer the most straight-forward solution (not necessarily the most efficient) in many situations. However, functional vs. imperative can be a very religious thing. But I'm sure most people here in this group, myself included, will agree that functional stuff is a good thing and the functional style of programming tends to lead to very concise, easy to maintain, and readable code. -- Mike On Fri, Jul 26 @ 12:52, Britt A. Green wrote: > I guess that begs the question: what's the advantage of functional-style > programming? :) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From linuxbrad at rogers.com Mon Jul 8 20:58:04 2002 From: linuxbrad at rogers.com (Brad Fonseca) Date: Tue, 09 Jul 2002 00:58:04 GMT Subject: Getting IDLE 0.8 to recognize Pyhthon 2.2.1 References: <115W8.7627$Xg%.3561@news01.bloor.is.net.cable.rogers.com> Message-ID: Gerhard H?ring wrote: > * Brad Fonseca [2002-07-08 00:28 +0000]: >> Hi! >> >> I've upgraded to python 2.2.1 but when I start IDLE it still starts >> Python 2.1.1. How do I get IDLE to start Python 2.2 > > Two possibilites. > > 1) Preferrable: Install the IDLE that comes with your Python 2.2.1. On > Debian: apt-get install idle-python2.2. Other distributions like the > KRUD RPMs from jafo available on python.org have idle in a seperate > package (in python2-tools-2.2.1-1.i386.rpm, IIRC). > > 2) A little more hackish: Find your idle: "which idle". Then change the > first line from > > #! /usr/bin/python > > to > > #! /usr/bin/env python2.2 > > Gerhard I tried this and it starts up but I get error if I try to use it. -- --- Brad Fonseca From gerhard.haering at gmx.de Mon Jul 1 16:19:53 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 1 Jul 2002 20:19:53 GMT Subject: Pyrhon language dedicated Wiki References: Message-ID: Kerim Borchaev wrote in comp.lang.python: > It seems to me that C.l.py is too overloaded today. I just ignore threads where I see from the subject that they don't interest me. The downside is that I'll miss some gems hidden in these threads. > Wouldn't it be nice if someone(not me - I think I don't have > resources for it) bothered to setup a wiki for discussion about > python language? I don't think wikis are useful for discussion, that's where email, news and irc shine. I see wikis as an iterative way of collecting and organizing content, with the addition that they can also contain some half-finished content. Just my 2 EUR ?. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From eric.brunel at pragmadev.com Wed Jul 24 06:27:45 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 24 Jul 2002 10:27:45 +0000 Subject: accessing a file's creation time References: Message-ID: hejduk wrote: > i'm running 2.2 on linux 2.4.5 (slak 8.0.) my question is whether > there is any way to access a file's creation time . os.stat provides > access to constants that represent a file's last access time, last > modification time, and last inode change time, but seemingly no way to > get it's actual time of creation. i know the os stores this > information somewhere (a simple "ls -l" demonstrates this), but i just > can't seem to find a way to access it. ??? ls -l gives the last modification time, not the creation time. AFAIK, the "creation" time is not stored... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From mwh at python.net Tue Jul 9 10:49:49 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 9 Jul 2002 15:49:49 +0100 (BST) Subject: [snake-farm] Broken build system as of 2002-06-04 In-Reply-To: <20020709143842.GU20301@lysator.liu.se> Message-ID: On Tue, 9 Jul 2002, Anders Qvist wrote: > [...] > However, I can reproduce the error manually on my local Linux box, so > it's not likely to be directly related to the scripts. Yeah, yeah, finish reading your email :) I've proposed a fix to python-dev (I'd have just checked it in, but I don't understand why the code doesn't do what I'm proposing anyway, so I may have missed something). At any rate, it should be fixed by tomorrow. > "We've all heard that a million monkeys banging on a million typewriters > will eventually reproduce the entire works of Shakespeare. Now, thanks > to the Internet, we know this is not true." -- Robert Wilensky Do you really need an explanation of why this is bogus? :) Cheers, M. From tdelaney at avaya.com Tue Jul 9 21:03:21 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 10 Jul 2002 11:03:21 +1000 Subject: j2ee vs. python (and what our evil competitors are saying abo ut python) Message-ID: > http://www.journyx.com/pdf/PythonAtAGlance.pdf A very good document. I would suggest a couple of possible changes for the next revision. I would probably change the "Python and Web Applications Development" section to exclude JPython (and note please that JPython is an old version - the current version is called Jython - no "P"), and have another section called "Python and Java". "Java/Python integration" acctually suggests the JPE (Java/Python Extension) which is another alternative for integrating Java and (C)Python (and could possibly be mentioned, but is not used anywhere near as much, simply because Jython is so complete). Additionally, I would change the text to read along the lines of: Python has an implementation written in Java called "Jython". Jython has full access to all Java class libraries as well as the majority of the Python libraries. It is usable in any situation where Java is appropriate, including client-side web applets and complete applications. I would also change the "It is not J2EE compliant." myth to read: It is certainly possible to write a J2EE compliant application using Jython, and many developers are doing so. and would have the links as: http://www.python.org http://www.jython.org (definitely include the link to Jython, the http:// is my preference ;) Cheers. Tim Delaney From brueckd at tbye.com Sat Jul 6 14:34:45 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sat, 6 Jul 2002 11:34:45 -0700 (PDT) Subject: sending a file through sockets In-Reply-To: <3D26C135.3000001@nowhere.org> Message-ID: On Sat, 6 Jul 2002, Bryan Olson wrote: > >>No, cutting the cord will not do the same thing. You only get the zero- > >>byte successful read on graceful shutdown. > > > > Actually, you get 0-byte successful read when you simply call close() > too. > > I assume you mean when the other side calls close. Yes, of course, as it would be goofy to call close and then recv all on the same side of the connection. I'm just pointing out that a call to shutdown() is not needed. And in fact in many cases it would be not wanted since you'd probably want to use the connection for something else later. > > Finally, I just tried killing the > > server process and the client side immediately came back with a 0-byte > > successful read. > > That's the system doing the shutdown for you. If you think it's too > dangerous, well, ?? Not sure what you're talking about here. I don't remember saying anything was too dangerous. > the code you posted didn't actually check the length. > The explicitly sent length only protected against the server sending > more data than that. Yes, as I already pointed out, I failed to include the standard disclaimer of "this works in my brain's Python interpreter, YMMV". I actually spend most of my days writing network agents in Python (so I do know how to do it "right" or whatever), but I was just posting some code from memory to help the guy out; I think it's pretty obvious that you don't cut code from a Usenet post and paste it into your production system and expect no problems. > > FWIW, latest CVS version of sockets has timeout support. Yay! > > Actually the sockets in the Python 2.2 (Windows) library I have support > timeouts and select(). The problem is that the protocol libraries don't > use them. What I'm saying is that, in CVS, Modules/socketmodule.c has Michael Gilfix's timeout socket implementation, e.g. socket objects have settimeout(). Also, once you have timeout sockets, most of the protocol libraries don't _need_ to worry about them. For example, in the Python version of timeoutsocket.py, you can just set a global timeout value and then the protocol libraries work automatically because an exception gets raised on timeout and control returns to your app. There's not much more than this they could do intelligently even if they _did_ know about timeouts themselves. > > The other side detects it immediately, for other problems you tend > > to get a socket.error exception. > > On pull-the-plug a recv won't detect the connection loss until the local > system tries a keepalive probe, which is typically two hours. Apparently we're talking about different things because I just tried it and got a socket.error exception ('connection reset by peer') on Windows. Or, you misunderstood the point of Donn's appliance analogy - I believe he was just saying, "yeah, technically in some cases you can get by without a length prefix, but it's handy and more reliable to include it and so darn easy that you might as well". -Dave From fperez528 at yahoo.com Sun Jul 7 19:32:13 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sun, 07 Jul 2002 17:32:13 -0600 Subject: NumPy Question: Audio Frequency Spectrum / Signal Analysis - pe_audioLevels.py [0/1] References: Message-ID: Perry Kivolowitz wrote: > [This followup was posted to comp.lang.python and a copy was sent to the > [cited author.] > > I'm having a little touble writing a graphical view of an audio > spectrum. I'm using NumPy, and Useful Things - a Python programmable > plug-in for Adobe After Effects. > > I am totally inexperienced with respect to signal processing, so please > excuse my (possibly) bogus use of terminology. > > It seems to work, with the exception that sounds close to silence > (highly negative DB) are putting out enormous amplitudes. So much so, I > have to put in a base DB check - squelching anything more negative to 0. > > This is the code which converts from samples to frequency data: > > m = 2.0 / float(numSamples) > halfSamples = numSamples / 2 > samplePeriod = 1.0 / float(sampleRate) * numSamples > firstHarmonic = 1.0 / samplePeriod > fftData = fft(samples) > realTerms = fftData[1 : halfSamples + 1] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary. Use FFT.real_fft() which takes into account the periodicity of the fft of a real signal and only returns the first half. Just remember to invert with FFT.inverse_real_fft() > then I do: > > frequencyAmplitudes = [ 0 ] * halfSamples > for i in xrange(halfSamples): > frequencyAmplitudes[i] = convertToDecibels(m * abs(realTerms[i])) This is probably taking forever and a day. Write it as a single Numeric array operation. As much as possible, try to avoid explicit python loops over numeric arrays like the plague. We're talking factors of 100-1000 in performance difference here. Something like (untested) should do: realTerms = FFT.real_fft(samples) frequencyAmplitudes = toDB(m*Numeric.absolute(realTerms)) > to gather up data from a specific band I finish with (to show the min DB > test): > > outputData[i] = 1.0 - (abs(bandAccumulator / bandCounter) - minDB) > / (maxDB - minDB) > if outputData[i] > 1: outputData[i] = 1 > if outputData[i] < 0: outputData[i] = 0 Again, no looping. Use Numeric.clip() for this. > where convertToDecibels is: > > amp2db = 20.0 / log(10.0) > > def convertToDecibels(a): > if a < 1.0e-30: return -600 > else: return amp2db * log(a) This can be written as a Numeric operation with no looping. Just mask out the values below your clipping threshold with where() or clip() so your log doesn't blow up. > When the min DB setting is played with, I get great results. Without it > being set right, I get blown out in the lower frequencies. > > If this isn't enough, I have enclosed the entire source. If you're an > After Effects user, I can supply a free license to Useful Things so you > can actually see what's going on (and code your own After Effects plug- > ins in Python!) in exchange for your help. > > Thanks cheers, f From buzzard at urubu.freeserve.co.uk Sat Jul 20 09:59:10 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 20 Jul 2002 14:59:10 +0100 Subject: Lists & two dimensions References: Message-ID: "Pichai Asokan" wrote in message news:bed1f696.0207200546.2bca2e34 at posting.google.com... > I am a trainer and in a training session a participant came up with a > problem that stumped me: > > Here is the code snippet that isolates what I want: > -------------------- > board = [[-1] * 3 ]*3 > print board > board[1][2] = 'x' > print board > -------------------- > Output > ----------------------- > [ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ] > [ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ] > ----------------------- > > I thought > board = [[-1] * 3 ]*3 > should give me a list of 9 elements; > but ... > > What is going on? > Where can we read more to understand what is goingg on? > > P Asokan >>> b = [[-1] * 3 ] >>> b [[-1, -1, -1]] # a list containing a list >>> b * 3 [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]] >>> >>> b = [-1] * 3 >>> b [-1, -1, -1] >>> b * 3 [-1, -1, -1, -1, -1, -1, -1, -1, -1] >>> Maybe >>> b = ([-1] * 3 ) * 3 >>> b [-1, -1, -1, -1, -1, -1, -1, -1, -1] but the braces are not needed. Does this help? Duncan From markvkane at hotmail.com Thu Jul 11 20:08:47 2002 From: markvkane at hotmail.com (Mark) Date: 11 Jul 2002 17:08:47 -0700 Subject: Python to XML to Python conversion Message-ID: Hello, Recently my employer has asked me to do some computer work though I'm just savvy enough to write minor programs of little significance. My job is to write a program that will be generic enough to take any form of Python dictionary and be able to convert it to XML and back. Ladies and gentlemen I am completely at a loss, I'm not a good programmer. If anyone one has any good, simple and complicated examples, or tips I would be eternally greatful if you'd share them with me. I have searched desperately through every posting I could find on the subject, but to no avail. Please Help! Regards,______ ______ | Markus|_______| ______| From curt at journyx.com Thu Jul 11 15:34:17 2002 From: curt at journyx.com (curt finch) Date: 11 Jul 2002 12:34:17 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207091153.7b2484be@posting.google.com> Message-ID: <96c7f32.0207111134.22add705@posting.google.com> "Matt Gerrans" wrote in message news:... > > There are two basically, one is clockware and the other is timewizard. > > I don't like to give them publicity at all, even bad publicity. > > Okay! Now we can call up their sales people and ask them why they haven't > implemented their technology in Python. Are their developers masochistic > or something? don't tease me like that ___________________________________________________________________ FREE Project Management Software??? --> http://journyx.com/wts.html ------------------------------------------------------------------- From printers at sendme.cz Tue Jul 9 16:47:44 2002 From: printers at sendme.cz (A) Date: Tue, 9 Jul 2002 22:47:44 +0200 Subject: How to grab a part of web page? Message-ID: <3D2B6810.13895.8A3A7A@localhost> Hi, Is it possible to download only a part of web page? Say I need to find out an information about a customer that starts at 1500 byte position and ends at 2000 byte position. If the whole page has about 100 kb it seems to me waste of time to load all the page. What is the best, yet easy, solution? Is it possible to use httplib or necessary socket module? Thank you for help. Ladislav From b.maryniuk at forbis.lt Thu Jul 11 03:52:21 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 09:52:21 +0200 Subject: Python in the enterprise: Pros and cons In-Reply-To: <33e8a47f.0207101302.1bd3d902@posting.google.com> References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: <200207110952.21663.b.maryniuk@forbis.lt> On Wednesday 10 July 2002 23:02, builder wrote: > Python has many fans in the open source community, but is it ready for > the enterprise? What the buzzword "the enterprise" is (as other buzzwords, aka XML, Java etc)? -- Sincerely yours, Bogdan M. Maryniuck "...Deep Hack Mode--that mysterious and frightening state of consciousness where Mortal Users fear to tread." (By Matt Welsh) From nospam at bigfoot.com Tue Jul 30 08:30:40 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 30 Jul 2002 14:30:40 +0200 Subject: Good XML tools? References: Message-ID: I know that plaiying with pyXML is a mess for newbies because of its lack of good documentation. But PyXML is always said to be in beta status. If you're on a Win32 platform and don't care about portability, you can play with MSXML 4.0 that's a full featured, fast and fully documented XML suite. Examples are mainly in VBS or JavaScript but easily translatable to Python. 1/ Install Mark Hammond's Python Win32 extensions http://starship.python.net/crew/skippy/win32/Downloads.html 2/ Install MSXML4 http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?ur l=/msdn-files/027/001/766/msdncompositedoc.xml --Gilles glenfant AT bigfoot DOT com "M" a ?crit dans le message de news: c0abefc3.0207300242.2ab2cf7f at posting.google.com... > Hi all, > > > Can you recommend any good XML packages for Python? I looked at the > PyXML but it seems to be lacking proper documentation (=unusable). > > Are you aware of any package that provides DOM/XPath for Python? > > Good documentation is a must, only hackers doing their favorite > OSS project in their spare time can spend time reading source > code instead of proper documentation... > > Thanx. > > /M From fredrik at pythonware.com Wed Jul 10 06:38:09 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jul 2002 10:38:09 GMT Subject: sorting many arrays from one... References: <%KCW8.60416$vm5.2194409@news2.tin.it> <3D2B0973.B553A25F@info.unicaen.fr> <15FW8.61099$vm5.2221340@news2.tin.it> <3D2C0117.89BCDC43@info.unicaen.fr> Message-ID: Jerzy Karczmarczuk wrote: > Shall I repeat it once more? I think that the call overhead should be > perhaps better optimised, and if it seems difficult, I would like to > know why. you have the full source code, like everyone else. I suggest starting in the docompare() function in Objects/listobject.c... if you find some small change that would cause a major speedup, try it out, and post the patch if it seems to work. if you suggest that we throw away what we have and start over from scratch, please bring lots of food and money to the party... From Maric.MICHAUD at cirec.com Thu Jul 18 06:36:27 2002 From: Maric.MICHAUD at cirec.com (Maric MICHAUD) Date: Thu, 18 Jul 2002 12:36:27 +0200 Subject: audio dev for linux Message-ID: <27E327AB8201B54495D54105FBBBB1485D2053@SRVMSG.GERLAND2.local> Do anyone know a way to play a cdrom track on linux. From shagshag13 at yahoo.fr Mon Jul 29 07:15:23 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 29 Jul 2002 13:15:23 +0200 Subject: Size in byte of a string ? References: Message-ID: "Shagshag13" a ?crit dans le message de news: ai37ij$10tmvq$1 at ID-146704.news.dfncis.de... > [sorry for the previous incomplete post] > > hello, > > i had the following problem : i had huge files > 1,5 go. each of theses files contain some other small files and they are separate > by a header. i need to do some kind of random access to the small files so i wish to write a script which would build some kind of a > table of content for theses huges files. > > i would like to have something like > samllfile_header_name_i : start_at_byte : end_at_byte > > and i will do : > f.seek(start_at_byte) > samllfile_header_name_content = f.read(end_at_byte) > > but to do this i need to be able at the building time to know how much bytes take a string ? > > (i think there is something with the size in byte of CR/LF but how to measure it ? i hope i won't have to do some > start_at_line, end_at_line as it will need to always read file from start...). i forget to write that theses are text files, that what i call "header" is more some kind of separator ("name_of_the_file\n"). thanks in advance, s13. From peter at engcorp.com Mon Jul 15 00:16:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Jul 2002 00:16:51 -0400 Subject: Fakes... References: Message-ID: <3D324CB3.418C5F87@engcorp.com> Matt Gerrans wrote: > > [snipped harangue] > > ... With 6 billion people... > [snipped diatribe] > > ... 99.9999999% of the > > population. I know this because I've searched, and in > > my search have so far only found one true ally... > > Well, I didn't have time to peruse this rant, but since you posted this to > comp.lang.python, I skipped to the relevant (loosly speaking!) part: > > >>> round((1.0-99.9999999/100)*6*math.pow(10,9)) > 6.0 > > Looks like good news: you only have 4 more like yourself to find -- You > probably have better odds in high-population areas like China, India and > Africa than you do in comp.lang.pytyon... Or maybe check in comp.sys.autocoding.... From tdelaney at avaya.com Tue Jul 9 20:29:17 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 10 Jul 2002 10:29:17 +1000 Subject: Why self? Message-ID: > From: Louis M. Pecora [mailto:pecora at anvil.nrl.navy.mil] > > self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) > > is a LOT uglier than > > y= x**2 * t/z + a * FFT(tseries) x, t, z, a, tseries = self.x, self.t, self.z, self.a, self.tseries self.y = x**2 * t/z + a * FFT(tseries) Tim Delaney From markus.vonehr at ipm.fhg.de Thu Jul 4 08:38:55 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 04 Jul 2002 14:38:55 +0200 Subject: Tk.mainloop and glutMainLoop parallel? Message-ID: <3D2441DF.1CC2AE80@ipm.fhg.de> Hi, within a thread in a TkInter App I open a window using: glutCreateWindow() command and call glutMainLoop afterwards. It happens that the Tkinter windows don't update any more and only the openGL window is running. How can I open a openGL window with glutCreateWindow() within a TkInter app and running both mainloops? I would prefer using glutCreateWindow() for the 3D window instead of using OpenGL.Tk for the "normal" TkInter windows and OpenGL.GL for the 3D stuff. Thanks for any comments, Markus From chris.gonnerman at newcenturycomputers.net Tue Jul 9 23:06:55 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 9 Jul 2002 22:06:55 -0500 Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: <001701c227be$dc4d05e0$0101010a@local> ----- Original Message ----- From: "William Park" > Chris Gonnerman wrote: > > I use chrony for time maintenance. If your computer has intermittent > > Internet access (i.e. dialup) it is hands-down the best way to do it > > IMHO. > > > > If this package has already been mentioned, sorry... I haven't followed > > this thread closely. > > > > http://chrony.sunsite.dk/ > > > > Off-topic since it's C, but I love it. > > I've seen it, but it's a tarball which you have to download and compile. This is a problem? > Whereas, 'netdate', 'ntpdate', and 'telnet 13' are ready to run on all > Linux distribution. I have DSL connection, so I run it once a day in > Crontab. If you dialup, then you can run it from '/etc/ppp/ip-up'. True. chrony doesn't update the time by "lurches" though, but by "skew," which is better in most cases. To each his own. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From debl2nonspammyno at bellatlantic.net Mon Jul 29 19:57:34 2002 From: debl2nonspammyno at bellatlantic.net (David Lees) Date: Mon, 29 Jul 2002 23:57:34 GMT Subject: How to install Jython? References: <3D44C9CC.A0DBC792@bellatlantic.net> Message-ID: <3D45D697.58B47F30@bellatlantic.net> Got it. Thanks Gerhard. Gerhard Haering wrote: > > * David Lees [2002-07-29 04:50 +0000]: > > I need very basic configuration advice to install jython-21 on my > > win98SE box. I am doing something wrong. I downloaded > > jython-21.class.exe but am unable get it do self-extraction. I gather > > that this is not an windows .exe, > > Yes, it's a class file. Your broser is pulling your leg. > > > but some sort of machine independent self extracting file that you run java > > to extact. > > Indeed, a Java class file :-) > > Just rename it to jython-21.class, then follow the instructions from > http://www.jython.org/install.html > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 > public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From aleax at aleax.it Thu Jul 25 10:09:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 14:09:44 GMT Subject: how to count lines in a file ? References: Message-ID: Bo M. Maryniuck wrote: ... > Therefore code: > ----------8<------------ >>>> a = open('file') >>>> a.close() >>>> del a > ----------8<------------ > > ...and just... > ----------8<------------ >>>> open('file') > > ----------8<------------ > > ..."make" different garbage in the memory and second one provides more > "crap"? I would DEFINITELY hope so -- else how could this work...? >>> open('/etc/motd') >>> print _.read(), Welcome to FOOBAR INC! >>> _.close() Don't forget that the interactive interpreter keeps your latest non-None expression statement's result as an attribute of the builtins module with a name of '_'. If you do forget it, understanding what's garbage, what not, gets tricky:-). Alex From jonathan at onegoodidea.com Tue Jul 9 06:22:40 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 09 Jul 2002 11:22:40 +0100 Subject: Clumsy threading (was Re: [OT] Corrections about Java) References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091041.07136.b.maryniuk@forbis.lt> Message-ID: On 9/7/2002 10:08, in article mailman.1026205814.27172.python-list at python.org, "Gerhard H?ring" wrote: > The difference is that Java has some support in the language (only the > "synchronized" keyword, AFAIK) that supports synchronized methods and > objects. Python's higher-level threading module was modelled after > Java's and has everything Java has. It even has Queue.Queue, which Java > hasn't. Python's features for thread synchronization also appear a lot > more flexible than Java's to me. Gah! It always annoyed me immensely that after decades of multi-threading research the best model Sun could come up with for Java was Monitors (synchronised methods). Seems Hoare and Dijkstra wasted their time... On a related note I've been playing with adding guarded methods to Python. Here's what my guarded version of a queue looks like: >>> class queue( object ): ... ... def __init__( self, max=sys.maxint ): ... self._max = max ... self._items = [] ... ... def _put( self, item ): ... self._items.insert( 0, item ) ... def _put_guard( self ): ... return len(self._items) < self.max ... put = guardedmethod( _put, _put_guard ) ... ... def _get( self ): ... return self._items.pop() ... def _get_guard( self ): ... return len(self._items) > 0 ... get = guardedmethod( _get, _get_guard ) ... The basic idea with 'guardedmethod's is that if the guard evaluates to false then the method will block until the guard is true. -Ada's-select-coming-next--ly y'rs, Jonathan From walter at livinglogic.de Wed Jul 3 07:59:18 2002 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 03 Jul 2002 13:59:18 +0200 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: <3D22E716.5070307@livinglogic.de> Robert Kuzelj wrote: > hallo walter, > > thanks for the reply. > > >>>class metatype(type): pass >>> >>>class A1: pass >>>class B1(object): pass >>>class C1: __metaclass__ = metatype >>> >> > > >>This is not a bug, it's one of the main features of new style >>classes. > > what is a feature of 2.2? that you cant distinguish between > a class and an instance? hardly! That you can't distinguish between types and classes. Every object is an instance of it's type in 2.2 (at least for new style objects/classes). Even a class object is an instance of it's type. >>>of what type are B1() and C1()? >> >>B1 and C1. > > i am very well aware of this. but it doesnt solve my problem. I think it would be helpful, if you descripe what problem you're trying to solve. > because > C1.__class__ =~ metatype > C1().__class__ =~ C1 > > there is no _direct_ possebility to find out if > a given object is an instance or a class (new style one that is). > > well there is a workaround: > > if not isinstance(obj, types.ClassType) and \ > not isinstance(obj, types.TypeType): > print "its an instance!" > > but isn't explicit better than implicit? Yes, but "type checks are evil". > i think > i have read this somewhere on the python pages? didnt i? ;-) Right, do an "import this"! ;) > imo it should be very clear that there is a difference between > the following two statements: > class A(object): #defines a class which is an object of type type. > A() # creates an instance > > and the information on how the object was created should be explictly > accessibly. Every object foo was created by a call to foo.__class__.__new__() and initialized by foo.__class__.__init__(). Bye, Walter D?rwald From peter at engcorp.com Tue Jul 16 18:04:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Jul 2002 18:04:11 -0400 Subject: Newbie: Capture output of compile_dir References: Message-ID: <3D34985B.5AAE5B10@engcorp.com> "Denis S. Otkidach" wrote: > > On Tue, 16 Jul 2002, Peter Hansen wrote: > > PH> By the way, "sys" has _stdout and _stderr already, which I > PH> believe > PH> point to the originals, so I believe you don't need to > PH> preserve > PH> these in your own locals unless you're expecting to have to > PH> nest > PH> these sorts of redirections. > > Certainly, sys module have __stdout__ and __stderr__. But we > should restore values being before our definition. For instance > if I have colored python shell with already redefined > sys.std{out|err} to add ANSII escape sequences then falling back > to __std{out|err}__ will break this. In a small enough script, __stdout__ and friends (thanks for the correction on the spelling) *are* the values before your definition. That's why I said "if you expect to have to nest". I was merely pointing out the presence of those items. Nobody has to use them, nor should they except when it's appropriate, which I agree it would not be in many situations. -Peter From aleax at aleax.it Tue Jul 16 05:29:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 16 Jul 2002 09:29:37 GMT Subject: switch recipe? References: Message-ID: <5IRY8.85116$vm5.3089324@news2.tin.it> Mark McEahern wrote: > [Alex Martelli] >> Right. So what about a direct implementation of what you just said? >> >> def weave(setn, setm): >> n = len(setn) >> m = len(setm) >> if not n or not m: >> raise ValueError, "Weaved sets cannot be empty" >> yield setn[0], setm[0] >> i = 1 >> while i%n or i%m: >> yield setn[i%n], setm[i%m] >> i += 1 > > I like this. The 'or' in the while statment means this will loop until > lcd(n, m)--easily fixed. I modified this slightly: I'm not sure what an lcd is in this context, but I did mean to loop least-common-multiple(m, n) times, treating the two sets as equivalent. So I guess I had misunderstood the specs! > def weave(setn, setm): > """Return a generator that iterates over setn and setm until setn is > exhausted. If setn is larger than setm, cycle over setm. > """ > m = len(setm) > if not setn or not setm: > raise ValueError, "Weaved sets cannot be empty" > for i in range(len(setn)): > yield setn[i], setm[i%m] > > This means you have to specify the alternator/cycler second--it doesn't > treat the two sets as interchangeable. Slightly less general than the > direction your solution points. Yep. Nicer in Python 2.3 of course: def weave(setn, setm): """Return a generator that iterates over setn and setm until setn is exhausted. If setn is larger than setm, cycle over setm.""" if not setn or not setm: raise ValueError, "Weaved sets cannot be empty" m = len(setm) for index, item in enumerate(setn): yield item, setm[index%m] Here, actually, an empty setn SHOULD be quite acceptable -- as no cycling is done on it, that should be OK, and only an empty setm should be a problem. So, I'd prefer: def weave(setn, setm): """Return an iterator that iterates over iterator setn and sequence setm until setn is exhausted. If setn is larger than setm, cycle over setm.""" m = len(setm) if not m: raise ValueError, "Set to be cycled on cannot be empty" for index, item in enumerate(setn): yield item, setm[index%m] Alex From xeon at dacreations.cjb.net Fri Jul 19 14:41:02 2002 From: xeon at dacreations.cjb.net (xeon) Date: 19 Jul 2002 11:41:02 -0700 Subject: PDB question Message-ID: Hi, Any tuts on using python debugger (pdb)? Does pdb list function only works with funtions defined on a seperate modules? I've tried to write a function in the intepreter then debug it with pdb.run(), when the prompt appears, issuing list command only gives me '[EOF]' (python 1.5.2 for windows 3.1). What does these mean (in pdb prompt) : > (1)?() > (1)foo() TIA From Chris.Barker at noaa.gov Wed Jul 24 15:02:07 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Wed, 24 Jul 2002 12:02:07 -0700 Subject: Numeric data question References: <%Nz%8.15893$A72.86385@news1.mts.net> Message-ID: <3D3EF9AD.A0F661BC@noaa.gov> terry wrote: > I'm guessing now (from lack of real experience) that being a > 'typeless' language Python is "dynamically, but strongly typed" which is an important distinction. > that I would be forced into contriving a > method for handling money such that I could never code something > straightforwardly like: > TotalCost = Quantity * UnitCost > (where Quantity is integer and the others money). You might have to contrive something, but it would allow you to code: > something straightforwardly like: > TotalCost = Quantity * UnitCost > (where Quantity is integer and the others money). To keep the buzzwards rolling, Python is an Object Oriented language that supports Operator Overloading. What you can do is create a class, "money" that defines the arithmetic operators the way you want them to be used. You can do this is such a way that it interacts appropriately with Python numeric types, and uses all the standard operators. > Am I loonie, or is Python just not inherently suitable for > accounting applications for this reason? Do any programming languages have a built in "money" type? How is this problem solved in them? If this really is a problem that can't be handled by using floating point and rounding appropriately where required, I imagine someone out there has written a money class already. If not you will be doing a service to the community if you do it. no comment on whether you are loonie or not. -Chris Here is a trivial example to get you started. You would obviuosly have to be very carefull about rounidng and all that to do it right: #!/usr/bin/env python2 import string class money: def __init__(self,amount, flag = "dollars"): if flag == "dollars": self.micropennies = long(round(amount,2)*100000000) elif flag == "pennies": self.micropennies = long(round(amount)*1000000) elif flag == "micropennies": self.micropennies = long(amount) def __str__(self): return "$%i."%(self.micropennies /100000000)+ string.zfill(int(((self.micropennies / 1000000) % 100)),2) def __mul__(self,other): return money(self.micropennies * other,"micropennies") def __rmul__(self,other): return money(self.micropennies * other,"micropennies") UnitCost = money(23.45) print "UnitCost is: ", UnitCost Quantity = 5 TotalCost = Quantity * UnitCost print "TotalCost is: ",TotalCost -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From marklists at mceahern.com Fri Jul 12 17:32:35 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 16:32:35 -0500 Subject: switch recipe? In-Reply-To: Message-ID: [Chris Liechti] > > Is switch a bad name for this? > > definetly yes ;-) as a C programmer, i expect something completly > different... (switch() {case x:}) > > > Can anyone suggest a better name? > > how about "repeat"? 'cause that's what it does. I like repeat(). That is, I like repeat! Thanks! > isn't this simpler, more obvious what it does, and still doing what you > want: > > >>> from __future__ import generators > >>> def repeat(*args): > ... if not args: args = [None] #optionaly to catch empty args > ... while 1: > ... for x in args: yield x > ... > >>> zip(range(10), repeat('even', 'odd')) > [(0, 'even'), (1, 'odd'), (2, 'even'), (3, 'odd'), (4, 'even'), > (5, 'odd'), > (6, 'even'), (7, 'odd'), (8, 'even'), (9, 'odd')] > >>> Yes, that's very nice. Here's the latest, with the help of all the suggestions I've gotten. #! /usr/bin/env python from __future__ import generators def make_repeat(*args): """Return a generator that repeatedly loops through args.""" if not args: raise TypeError("make_repeat() takes at least one parameter.") def repeat(): while args: for a in args: yield a return repeat() def colorize(value, *colors): repeat = make_repeat(*colors) template = "<%(color)s>%(item)s" items = [] for item in value: color = repeat.next() formatted_item = template % locals() items.append(formatted_item) return ''.join(items) s = colorize("testing", "black", "red", "green", "blue") print s expected = "t"\ "e"\ "s"\ "t"\ "i"\ "n"\ "g" assert s == expected - From jubafre at zipmail.com.br Mon Jul 15 16:18:40 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Mon, 15 Jul 2002 17:18:40 -0300 Subject: =?iso-8859-1?Q?horizontal=20line=20in=20tkinter=3F=3F=3F=3F?= Message-ID: <3D3308B500000725@www.zipmail.com.br> I want a horizontal line to separate the frames in my tkinter aplication, how can i insert it???? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From dfackrell at DELETETHIS.linuxmail.org Wed Jul 24 14:13:00 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Wed, 24 Jul 2002 12:13:00 -0600 Subject: syntax questions References: Message-ID: <3d3eee2d$1_2@hpb10302.boi.hp.com> "Philippe Gendreau" wrote in message news:mailman.1027530996.5219.python-list at python.org... > * Chris Liechti [2002-07-24 18:50]: > > note that "dir" is somewhat a bad name for that variable because > > a) there is a builtin function that name that you hide > > b) its not a directory name but a filename without path in the above case > > Note taken. > I know about the dir() function, but I'm surprised that my list object > hides a function object (even if they have the same name). > Is that how python treats names all the time? Does it mean you can't > have a class, def and variable of the same name? At least not in the same scope. For example, you could have a function foo in a class instance foo: foo.foo() but having that, doing foo=3 would reassign foo so that the class instance is no longer accessible (unless it's referenced elsewhere), while foo.foo=3 would do the same thing to the function for the instance. On the bright side, this is related to the fact that python tries to treat everything as equally as possible, which leads to useful behaviors as being able to pass functions or classes, along with other objects, to functions. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From hades at silentone.com Tue Jul 23 21:52:41 2002 From: hades at silentone.com (Culley Angus) Date: Wed, 24 Jul 2002 01:52:41 GMT Subject: SOAP.py and complex types References: <3D3BDD02.3997B185@xrce.xerox.com> Message-ID: <3d3e076c.596010898@news.wlg.ihug.co.nz> I had some issues with this as well... My problems were solved using by including the typename in the structType. soapobj=SOAP.structType(data=structdat, name=(namespace, myname)) where 'myname' is the type name of the object to pack, i.e. "Details" Hope this helps. From m.bohlen at tu-bs.de Sun Jul 7 16:36:48 2002 From: m.bohlen at tu-bs.de (Marc) Date: Sun, 07 Jul 2002 22:36:48 +0200 Subject: make cvs pserver/ssh(2) connection with python Message-ID: <20020707.223646.680466996.4043@tu-bs.de> Hi! I am searching a way to make a cvs pserver or/and a ssh(protocol Version 2) connection with python under Linux/Unix. I've tried to control the cvs pserver connection by a python frontend which uses the normal cvs binary, but it won't work without using the 'normal console interaction' for input (maintainly the cvs login). I can get the inputstream, but I can't write correctly to the outputstream. I get the password query, but the answer fails. Perhaps someone have experience in writing a frontend for interactive programms under Linux/Unix and can help me. Thanks Marc From johan at weknowthewayout.com Wed Jul 10 05:15:49 2002 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Wed, 10 Jul 2002 11:15:49 +0200 Subject: PDf creating with Python? Howto? References: <3D2BE41E.3040508@weknowthewayout.com> Message-ID: <3D2BFB45.4040802@weknowthewayout.com> >>Im right now beginning a project where I have to make a generator to PDF >>files. It includes images, and fonts (thats not are embedded in the >>Adobe PDF specification). > > you might get some help from the ReportLab project, try emailing > andy at reportlab.com or the users list reportlab-users at reportlab.com. The > ReportLab toolkit tries to do exactly what you describe. I will try to email andy later today... Thanks :) -- Regards Johan From roy at panix.com Fri Jul 12 07:29:31 2002 From: roy at panix.com (Roy Smith) Date: Fri, 12 Jul 2002 07:29:31 -0400 Subject: What went wrong in Python1.6 ? References: Message-ID: Rhymes wrote: > Now I ask my self: what went wrong in that release? Where i could find > some further infos about this "miscarriage" ? As far as I know, nothing was really "wrong" with 1.6, other than timing. IIRC, the final release announcement for 1.6 came out the very same day that the alpha 2.0 release announcement was made. Most people were running 1.5.2 and didn't see the point in upgrading to 1.6 now and then 2.0 a short time later, so they just waited for 2.0 to go final. From ianb at colorstudy.com Thu Jul 18 18:44:56 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 18 Jul 2002 17:44:56 -0500 Subject: i++ in Python? In-Reply-To: <5606b639.0207181429.2c6d2569@posting.google.com> References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <1027032296.708.145.camel@lothlorien.colorstudy.net> On Thu, 2002-07-18 at 17:29, OtisUsenet wrote: > Python newbie question. How does one do something like this in > Python: > > # assign the value of j to i and then increment j by 1 > i = j++ I'm sure a lot of people are going to pile onto this one, but the answers might go something like this... short answer (conventional way of doing it): i = j j += 1 clever answer: i, j = j, j+1 medium answer: Assignment is a statement (by design), so you can't reassign j inside an expression. longer answer: Unlike C, Python variables are bindings. So, assuming j starts out as 1, j doesn't *contain* 1 -- it *points to* 1. So when you do: j += 1 You are rebinding (repointing) j to 2. In C, j is actually a place in memory, and when you increment j you're taking that piece of memory and changing it. Incrementing in Python doesn't really happen like that. -- Ian Bicking Colorstudy Web Development ianb at colorstudy.com http://www.colorstudy.com 4869 N Talman Ave, Chicago, IL 60625 / (773) 275-7241 From mennis at corvus.net Wed Jul 31 17:54:20 2002 From: mennis at corvus.net (michaelian ennis) Date: Wed, 31 Jul 2002 17:54:20 -0400 Subject: re.search question Message-ID: <3mmgkucn8ga1klgrchkmfifkig9i1r4sse@4ax.com> How would I tell python to give me all the text in a string which falls between the first instance of "!" alone on a line and the first instance of "end" alone on a line inclusively? lines= junk ! important stuff end more junk to cleaned_lines= ! important stuff end From martin at v.loewis.de Fri Jul 26 03:07:36 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 26 Jul 2002 09:07:36 +0200 Subject: new module and class/type unification. References: Message-ID: Fredrik Stenberg writes: > import new > new.instance(str,None) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: instance() argument 1 must be class, not type > > > Is this is a bug? or am i missing the big picture > in type/class unification and the new-module? It's not a bug: new.instance creates only instance objects (i.e. whose type is types.InstanceType). For a type, you can call the type's __new__: >>> str.__new__(str) '' HTH, Martin From b.maryniuk at forbis.lt Tue Jul 9 09:30:29 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 15:30:29 +0200 Subject: win32: Leaving Dos Box open In-Reply-To: <3D2AE438.9030205@thomas-guettler.de> References: <3D2AE438.9030205@thomas-guettler.de> Message-ID: <200207091530.29259.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 15:25, Thomas Guettler wrote: > Hi! > > How can the dos box be left open when I run foo.py from > the windows explorer and there is a syntax error? Way No.1 ------[COOL.BAT]---------- C:\PYTHON\PYTHON.EXE your_cool_program.py pause --------------------------- Way No.2 a) Start->Run->Command b) C:\PYTHON\PYTHON.EXE your_cool_program.py Way No.3 (best of all) a) Insert boot CD with Linux b) Reboot... -- Sincerely yours, Bogdan M. Maryniuck "A word to the wise: a credentials dicksize war is usually a bad idea on the net." (David Parsons in c.o.l.development.system, about coding in C.) From fredrik at pythonware.com Sun Jul 28 04:56:31 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 28 Jul 2002 08:56:31 GMT Subject: how do I create a full screen window with TkInter References: <2621b014.0207272101.7e796bc6@posting.google.com> Message-ID: <3lO09.1361$HY3.370982@newsc.telia.net> Jon Schull wrote: > What would I add to this snippet to ensure to have the image being > displayed be all we see? (no titlebar, full size, etc.) calls to geometry and overrideredirect. you can find sample code here: http://effbot.org/zone/tkinter-toplevel-fullscreen.htm From mbelanger_NOSPAM at NOSPAM_pixelsystems.com Tue Jul 30 11:35:42 2002 From: mbelanger_NOSPAM at NOSPAM_pixelsystems.com (Mathieu Belanger) Date: Tue, 30 Jul 2002 11:35:42 -0400 Subject: Console Installation Message-ID: Hi, We have many PC installed everywhere in the entire country (Canada) and we want to install python 2.2 on each one. The only way for now to do that is to log into each PC with PCAnywhere and run the Wise installer. It is a way too slow. Is there a console installer that don't have to be interactive?? I've search for that everywhere and didn't find anything! All our PC run WinNT4. Thanks! Mathieu Belanger Developper Pixel Systems inc. http://pixelsystems.com From aleax at aleax.it Mon Jul 29 10:49:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 29 Jul 2002 16:49:45 +0200 Subject: [Python-Help] How to redirect output to browser - second request for help In-Reply-To: <3D454D10.11064.218373@localhost> References: <3D454D10.11064.218373@localhost> Message-ID: On Monday 29 July 2002 02:11 pm, A wrote: > Hi, > Is it possible to send output continuously to a web browser?. Module webbrowser lets you direct the browser to any URL of your choice. However, to perform the task you require...: > For example I have the following code > > >>> import httplib > >>> h = httplib.HTTP('www.cwi.nl') > >>> h.putrequest('GET', '/index.html') > >>> h.putheader('Accept', 'text/html') > >>> h.putheader('Accept', 'text/plain') > >>> h.endheaders() > > I would like to send coming bytes ( here coming bytes of > /index.html file) directly to web browser in the same > way as I use a web browser on my computer to open a > webpage where I can see a progress how webpage is being > opened. > In other words I do NOT want to wait for downloading the > whole file and only after that open that downloaded file > in a web browser. ...that URL must also be supplied by your Python program. In other words, you must implement a webserver and feed the data as it comes to the browser. Python supplies modules in its standard library that are web browsers of various capabilities, you can subclass and customize one of those. To get simultaneous operation between the data arriving from the remote server and the data you feed to the waiting browser, you will need either to write your Python program as multi-threaded (and I suggest using module Queue to communicate between the threads, it's simple and natural), or use asynchronous even-driven programming (the Python standard libraries come with two modules that support such programming, asyncore and asynchat, but a vastly more powerful arrangement for both asynchronous servers and clients is found in the vast Python package "Twisted Matrix", www.twistedmatrix.com, specifically in subpackage twisted.internet). In other words: the answer to your question is YES, but the amount of programming (and the necessary skill, in Python in particular and in programming in general) to achieve your goal can be surprisingly high. Were I approached as a freelance consultant by a client requesting such a program, I would size it at about 12 hours (and that's because I'm already somewhat skilled in twisted.matrix, as well as an expert programmer -- i.e., my consulting hours do _not_ come cheap:-). That's for a finished product of course, a rough and ready feasibiliy-check prototype might take me less! Alex From campbells4 at ozemail.com.au Tue Jul 2 01:46:36 2002 From: campbells4 at ozemail.com.au (Alistair Campbell) Date: Tue, 2 Jul 2002 15:46:36 +1000 Subject: [NEWBIE]-Object referencing?? Message-ID: Hi, I have class defined as below ... class Brew: def __init__(self): self.brew_id="" self.brew_date="" self.brew_type="" self.hydro_init='1040' self.hydro_final='1000' self.starter="" self.amt_start="" def alcohol(self): return ((string.atoi(self.hydro_init)-string.atoi(self.hydro_final))*0.00036251)*10 0 ... I assign data from a file so the data that goes into the alcohol method needs to be converted from string. The problem is that when I try to reference an instantiation of the Brew() class, i.e; current_brew=Brew() I can get all the other data items but a call to; current_brew.alcohol returns So. I know that the calculation of alcohol content is not true but I am just fiddling and will put in the correct formula when I get round to it. But, what am I doing wrong in relation to my definition or calling of the Brew.alcohol method? Trivial but nonetheless I have to start learning somewhere. Your help is much appreciated. Alistair Campbell Brisbane, Qld From fredrik at pythonware.com Wed Jul 24 13:32:09 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 24 Jul 2002 17:32:09 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: Alex Martelli wrote: > BTW, GvR claimed (less than a month ago on the python-dev list) > that having an integer argument to readlines was a design error. except that he was talking about "readline", not "readlines". (does anyone here even know that readline takes an optional integer argument, and what it does? ;-) From boud at valdyas.org Mon Jul 29 17:48:33 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Mon, 29 Jul 2002 23:48:33 +0200 Subject: default setting of unicode set References: <3D45000F.5040300@gmx.net> <3d454bc8$0$94895$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <3d45bcef$0$12305$e4fe514c@dreader4.news.xs4all.nl> Martin v. L?wis wrote: > Boudewijn Rempt writes: > >> This question comes up so often that I'm more and more convinced that >> the argument for deleting sys.setdefaultencoding() is flawed. Calling >> sys.setdefaultencoding("utf-8"), _is_ rather explicit, and beats having >> to add .encode()'s to all string handling. > > The attempt to do so is flawed. It is not *all* string handling that > should use .encode, but just the output handling. In many cases, using > codecs.open instead of the builtin open will remove the need for many > explicit .encode calls. That sounds very fine -- but the problem is, it's so counter-intuitive, that every newcomer will stumble over this. I just noticed another posting on this topic... Having to use codects.open instead of the builtin is just as bad. People will start using plain open, waste a few days trying to find out why it doesn't work, and then perhaps discover the codecs module. -- Boudewijn Rempt | http://www.valdyas.org From jb at cascade-sys.com Fri Jul 26 20:08:40 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 26 Jul 2002 17:08:40 -0700 Subject: calendar lameness! References: <3D3C0A21.1EB8A671@anansispaceworks.com> <1027715640.10236.200.camel@vaio2> Message-ID: <3D41E488.5C6E6D6A@cascade-sys.com> Andreas Kostyrka wrote: > Am Mon, 2002-07-22 um 15.35 schrieb Terry Hancock: > > "calendar" is pretty neat -- except it has pretty > > annoying arbitrary limits on the date: > > > > 1900-1/1 to 2038-1/18 > Well, this is not that arbitrary. Considering the fact that the > "calendar" wasn't standardized completly the beginning of the 20th > century. An earlier error in the calendar (IIRC, absence of leap century days) caused the calendar to precess until it was noticeably out of whack. The Gregorian Reformation is considered by most (but not all!) countries to have happened on 3 September 1752, whcn 10 days were axed out of the official calendar. Thus an accurate, "universal" calendar for the US would show that month as: [cascade jb]$ cal 9 1752 September 1752 Su Mo Tu We Th Fr Sa 1 2 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 And don't get me started on when Easter is. --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From dig.list at telkel.net Wed Jul 24 00:35:18 2002 From: dig.list at telkel.net (DIG) Date: Tue, 23 Jul 2002 23:35:18 -0500 Subject: Mastering Regular Expressions 2nd Ed. In-Reply-To: ; from "Tom Harris" on Wed, Jul 24, 2002 at 11:24:36AM References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> <7xn0si9o2o.fsf@ruckus.brouhaha.com> <3D3E0CEE.E3B3B4A0@engcorp.com> Message-ID: <20020723233518.B20383@lifebook> Hi, Peter Hansen ! On Tue, Jul 23, 2002 at 10:11:58PM -0400, Peter Hansen wrote: > Neil Schemenauer wrote: > > > > Regular expressions work much better if you use them for lexical > > analysis rather than for parsing. > > Would you please expand on that for those of us who are not computer > scientists and/or who do not understand the implications of your > statement? I am not Neil Schemenauer . And I am not a computer scientist (sorry ! :-)), but in my opinion, Tom Harris (tomh at optiscan.com, Software Engineer) already (Wed, Jul 24, 2002 at 11:24:36AM +1000) answered you (by asking right questions): * On Wed, Jul 24, 2002 at 11:24:36AM +1000, Tom Harris wrote: * * [...] Lexical analysis is tokenisation, parsing is making sense of the * tokens, is that correct? Is the moral to leave logic to the programming * language, not try to use regexes to di it? [...] Yes, it is. Regards, -- DIG (Dmitri I GOULIAEV) From guy at lightwork.co.uk Mon Jul 8 08:25:28 2002 From: guy at lightwork.co.uk (Guy) Date: 8 Jul 2002 05:25:28 -0700 Subject: mac sit files. Message-ID: Hi Quick question, I've been looking at the zip module, I was wondering if there is some code of some sort, anywhere that could do the same but in a mac sit file. From aleax at aleax.it Tue Jul 16 05:02:38 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 16 Jul 2002 09:02:38 GMT Subject: uniform interface for MySQL & MSSQL References: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> Message-ID: Johann wrote: > On Mon, 15 Jul 2002 19:38:28 GMT, Alex Martelli > wrote: > >>Have you tried: >>http://www.object-craft.com.au/projects/mssql/ > > It does not work. I tried to compile it under Cygwin but some files > (*.h) are missing :-( > > In file included from mssqldb.c:25: > mssqldb.h:37: sybfront.h: No such file or directory > mssqldb.h:38: sybdb.h: No such file or directory > error: command 'gcc' failed with exit status 1 Looks like you need freetds (or a Sybase installation, of course) -- http://www.freetds.org/ > I found this module have no cursor.seek(nr) method. :( Method seek is not part of the DBAPI standard, so it's hardly surprising that DBAPI compliant modules may lack it:-). (To be honest, I didn't even know mysqldb supplied that...). I hear a rumor that the DB SIG may be discussing a new version of the standard: maybe you should have a look at their mlist and lobby a bit for a seek method to be introduced in that new version. Of course this doesn't help you today. For a shorter-term fix, you might try win32api and ADO as a way to interface to Microsoft SQL -- not too hard to put a thin DBAPI compatible interface on top of that. I did that for think3, back when I worked there (but the code stayed with them and we never got around to discussing opensourcing some of the various pieces of code I wrote for them over the years -- don't hold your breath for THAT, sigh). As I recall, it's a week's work, tops. Alex From tdelaney at avaya.com Mon Jul 8 22:15:20 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 9 Jul 2002 12:15:20 +1000 Subject: Using Python for processing of large datasets (convincing man agment) Message-ID: > From: Thomas Jensen [mailto:spam at ob_scure.dk] > > 25-50% but thats not a realistic measure, since the client > makes a huge > amount of small selects, which probably makes network latency > play some > role. One method to reduce latency is to return multiple result sets with a single call. This is one thing stored procs are very useful for: create procedure ABC as begin select a from T_A; select b from T_B; select c from T_C; end or you can actually do it in your sql call - IIRC correctly as a "batch" call, or just simply as: "select a from T_A;select b from T_B;select c from T_C;" Doing this should reduce your network latency massively. Tim Delaney From sorry at no.mail.address Thu Jul 4 17:04:15 2002 From: sorry at no.mail.address (Tom Seddon) Date: Thu, 04 Jul 2002 21:04:15 GMT Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: In article , dreed at capital.edu says... > > From: Peter Hansen > > X-Accept-Language: en > > Newsgroups: comp.lang.python > > Xref: news.baymountain.net comp.lang.python:170296 > > Sender: python-list-admin at python.org > > Date: Sat, 29 Jun 2002 12:32:50 -0400 > > > > Rhymes wrote: > > > > > > Is there any possibility to build up a _real_ private attribute? > > > > Please define what "_real_" means to you. It's not apparent. > > > > > Such as C++ private data members... > > > > You realize that it's quite possible to get at private data members > > in C++, don't you? > > Kind of off-topic, but this got me curious. The only way I could think > of is to assume (which I think is always true) that the private data > members are in order from the starting address so based on the offset > from the address of the object you could access each one. > > Is there another way? > > Dave You need a class with a member template function. You then specialize this outside the class declaration. #include //tried with intel C++ 5.0 struct K { public: K():j(1) {} template void f(T r) { j=5; } int r() { return j; } private: int j; }; template<> void K::f(void *p) { j=6; } int main(int argc,char *argv[]) { K test; std::cout<(0)); std::cout< Message-ID: Charles Mantha wrote: : I am trying to run a small toy program which I modified from a tutorial. : : [...] : menu_choice = int(raw_input("Choose one of the options: ")), : while menu_choice != 3: : if menu_choice == 1: : run_test(get_questions()) Remove the comma from the end of the line that sets menu_choice. With the comma, when the user types "1", menu_choice gets the tuple "(1,)" instead of the int "1". This is making your while loop run forever without doing anything. dz From barry at zope.com Tue Jul 23 14:44:43 2002 From: barry at zope.com (Barry A. Warsaw) Date: Tue, 23 Jul 2002 14:44:43 -0400 Subject: mail.python.python scheduled maintenance Message-ID: <15677.42011.756642.192378@anthem.wooz.org> BayMountain, the ISP that manages mail.python.org as well as several zope.org machines, has scheduled some network maintenance for 24-Jul0-2002 between 23:00 and 24:00 EDT. This will include a change of IP addresses to all affected machines, although Zope Corp's IT manager will have proxies in place to handle forwarding of traffic until DNS catches up. He doesn't expect the affects of the outage to last more than an hour. For the Python community, this will affect all python.org email. Note that www.python.org is /not/ affected, since that is hosted by XS4ALL in the Netherlands. Cheers, -Barry From anoop79 at myrealbox.com Mon Jul 1 02:43:39 2002 From: anoop79 at myrealbox.com (Anoop P B) Date: Mon, 01 Jul 2002 12:13:39 +0530 Subject: calling a java app from python References: Message-ID: <3D1FFA1B.6000008@myrealbox.com> is there no way of doing this cross-platform? (i have changed the subject of this post since this subject may draw better attention and hold greater interest to others as well. please read my original post below....) Matt Gerrans wrote: > If you are not averse to using the Win32 extensions on the Windows platform, > then win32api.WinExec() or win32api.ShellExecute() will do the job quite > nicely. > > My original post: _____________________ Hi, I am trying to call a java application through my python script on windows. After consulting the documentation, i quickly learnt that the os.spawn*p versions are not available on windows. so, i tried the following: os.spawnle(os.P_NOWAIT, "java.exe", "java", "testProg", "testParam", os.environ) As I understand, this should work by picking up the path system variable from os.environ for setting up the environment for the new process (or am I missing something here?). But what I get is.... Traceback (most recent call last): File "server.py", line 48, in ? ct.run() File "server.py", line 25, in run os.spawnle(os.P_NOWAIT, "java.exe", "java", "testProg", "testParam", os.environ) File "c:\python22\lib\os.py", line 541, in spawnle return spawnve(mode, file, args[:-1], env) OSError: [Errno 2] No such file or directory Can someone please throw some light on possible solutions to this problem. My ultimate aim is only to run the java program through my python script. However, I cannot use os.system() since my python program gets blocked which is not acceptable. I need my python script to call the java program and continue executing. Thanks in advance, Anoop note: the java class is in the same directory in which my python script lies From donn at u.washington.edu Wed Jul 3 14:27:18 2002 From: donn at u.washington.edu (Donn Cave) Date: 3 Jul 2002 18:27:18 GMT Subject: GoTo considered missing References: <3D233D8C.2030104@onsitetech.com> Message-ID: Quoth Robb Shecter : | David LeBlanc wrote: |>...if you're writing python |> code that uses nested loops like that, it's possible you're not taking good |> advantage of Python's features. Care to share what you're working on?... | | I'd like to know too. I can't really think of an example where I'd need | a goto statement. Come on, guys - think outside of the block! Donn Cave, donn at u.washington.edu From gerhard.haering at gmx.de Wed Jul 3 10:41:07 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 3 Jul 2002 14:41:07 GMT Subject: "my brain hurts" or is isinstance broken? References: Message-ID: Jonathan Hogg wrote: >Robert Kuzelj wrote: >> [...] the real reason why i want to do this is something i realy dare >> not to say in this forum ;-) > > Oh, you can tell us. No matter what crimes your contemplating, you can > take comfort in the fact that they can probably be made more horrifying > with metaclasses ;-) I guess the reason why Robert feels better /protected/ when he doesn't say it in /public/ is that he's used to languages like Java. At least I heard so in /private/ ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From aahz at pythoncraft.com Sat Jul 20 11:21:00 2002 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2002 11:21:00 -0400 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: In article , Rhymes wrote: >On Fri, 19 Jul 2002 14:53:28 -0700 (PDT), "Sean 'Shaleh' Perry" > wrote: >> >>from __future__ import generators > >I know...but it's not a built-in feature :) Yes, it is, unless you're using some strange meaning for "built-in" far removed from its normal meaning. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From shalehperry at attbi.com Wed Jul 3 20:31:39 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 03 Jul 2002 17:31:39 -0700 (PDT) Subject: Parsing In-Reply-To: Message-ID: > > but, that's not really working out. I was just wondering if there was > some kind of standard parsing library for python to help me get rid of > those nasty html tags. Any pointers would me much appreciated. > > Have a nice day, and thanks. > import htmllib From mis6 at pitt.edu Wed Jul 24 17:36:40 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 24 Jul 2002 14:36:40 -0700 Subject: A better self (again) Message-ID: <2259b0e2.0207241336.498c5dd3@posting.google.com> That thread started as a request to have a better self implemented in the language. Since the usage of self seems so eradicated that probably will never be modified (which can be a good or a bad thing depending on your personal taste) I suggest a simple recipe to avoid typing self and having a preprocessor inserting automatically self in the right positions. IMHO this recipe is better than having a metaclass doing the job (as suggested by Alex Martelli) because: 1. It is simpler. 2. It is fast: on an old Pentium II 366MHz it takes only one second to process 100.000 lines of code ! 2. In the metaclass approach the pseudocode has to be entered as a python docstring: this means that it will not be correctly highlighted by the editor, which is a nuisance. 3. It is quite simple to configure Emacs in such a way to invoke automatically the preprocessor (I guess in idle too), therefore one can write and check the pseudocode directly. Notice that if an error occurs, Emacs automagically goes to the correct line in the pseudocode ! 4. When the program works, one can save it as standard code and reuse it as a module or distribute it. People will not get fool in trying to understand your metaclass hacking. Of course a simpler alternative is to learn to appreciate self :-) Personally, self does not bother me very much. I have chosen the example of self as an appliication of the general idea of a Python preprocessor. It could be handy for saving typings in various situations. One could even define abbreviations for ' reserved words and tokens of the language, even if I would not recommend that. For people working in Unix-like OS and using Emacs, this is the recipe, simple as the ABC: A. Save the preprocessor code in an executable file called pp: ---begin pp--- #!/usr/bin/python from os import popen import sys def process(pseudocode): from re import compile comma=compile(r'\(\s*,') dot=compile(r'[^\w_\)\]]\.[a-zA-Z_]+') code=comma.sub('(self,',pseudocode) end=0; newcode='' for found in dot.finditer(code): start=found.start() newcode+=code[end:start+1]+'self' end=found.end() newcode+=code[start+1:end] return newcode+code[end:] nargs=len(sys.argv)-1 if nargs==0: #execute the pseudoprogram out=process(sys.stdin.read()) popen('python2','w').write(out) elif nargs==1: #print to file print >>file(sys.argv[1],'w'),process(sys.stdin.read()) else: print """Too many arguments. Usage: pp < pseudo.py pp normal.py < pseudo.py""" ---end pp--- this preprocessor convert "(," --> "(self," and ".something" --> "self.something" B. Write your pseudopython program, for instance this one, which avoids self: ---begin pseudo.py--- from math import sin,sqrt import sys class Example: y,z,t=1.0,1.0,1.0 def f(,x): return sin(.t)*x**.y+sqrt(.z) example=Example() print example.f(1.0) ---end pseudo.py The preprocessor reads from the standard input and the pseudopython program can be executed as follows: $ pp < pseudo.py It can be converted to normal code as follows: $ pp normal.py < pseudo.py One can also write code on the fly, for instance $ pp print 1+1 CTRL-D 2 C. If you want to write and execute pseudopython programs from Emacs, add the line (setq py-python-command "pp") in the .emacs file. Emacs will highlight the pseudocode and in case of errors will jump to the correct line ! Maybe somebody want to try it. Obviously the preprocessor can be extended and improved to recognize any kind of new sintax you like. You can design your personal Python without bothering the official designers ! :-) --- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From bokr at oz.net Tue Jul 16 23:12:21 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2002 03:12:21 GMT Subject: map del efficiency python2.2 and 2.1 References: Message-ID: On Tue, 16 Jul 2002 15:53:43 GMT, Alex Martelli wrote: >John Hunter wrote: > ... >> def pairs(l): >> return [(l[i], l[i+1]) for i in range(0, len(l), 2)] ^^^^^ > >In 2.2, with "from __future__ import generators" at the start >of your module, you can probably use this almost as fast as >the other, less-elegant solution, by recoding it as a generator: > >def pairs(L): > for i in xrange(0, len(L), 2): ^^^^^^ ^ > yield L[i], L[i+1] > >but that's a minor issue, I guess. > >Another likely performance boost in 2.2 would be: > >m = dict(pairs(seq)) > >with pairs coded as here shown. In case John didn't notice, that little 'x' your finger likely typed automatically probably made some difference too ;-) > >Regarding del time, you could measure that directly by >doing a "del m" and seeing times before and after; also, >just in case (shouldn't matter, but...), you could try >gc.disable() and see if that makes a difference. > The range(0, len(l), 2) would have been part of the garbage to collect too, unless gc had already hit (in which case gc.disable() might change timing in two places). BTW, I wonder what the speed difference is in collecting deleted numbers in the magic shared range(-1,100) vs others is, given that it would just be decrementing refs until the end. Regards, Bengt Richter From aleax at aleax.it Sat Jul 13 03:19:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 09:19:10 +0200 Subject: switch recipe? In-Reply-To: References: Message-ID: <02071309191001.10164@arthur> On Saturday 13 July 2002 00:11, Mark McEahern wrote: ... > In general, this recipe, if it's worthy to be called such, is useful when > you want to weave together a finite set of values of a given length (n) > with a different set of values of a different length (m) and for the i-th > element of n, you want it to be weaved with the len(m) modulo i-th > element of m. Right. So what about a direct implementation of what you just said? def weave(setn, setm): n = len(setn) m = len(setm) if not n or not m: raise ValueError, "Weaved sets cannot be empty" yield setn[0], setm[0] i = 1 while i%n or i%m: yield setn[i%n], setm[i%m] i += 1 Your approach is more clever (and may have other uses), but this plain and direct implementation appeals to me. So the function that uses it might become something like: def colorize(value, *colors): return ''.join([ "<%s>%s" % (color, item, color) for item, color in weave(value, colors) ]) Alex From ianb at colorstudy.com Tue Jul 16 17:53:50 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 16 Jul 2002 16:53:50 -0500 Subject: Writing a secure web client? In-Reply-To: <3D34944F.DE1F2C5C@coryadams.com> References: <3D34944F.DE1F2C5C@coryadams.com> Message-ID: <1026856431.2095.7.camel@lothlorien.colorstudy.net> WebUnit contains HTTPSession, which does just what you want. On Tue, 2002-07-16 at 16:46, CA wrote: > I am trying to write a web client in python that first authenticates to > a secure url, then posts to a form using the secure session cookie. The > problem that I am having is follows: > > I can post to the secure form and get the session cookie back into a > Cookie.SmartCookie. How do I use this cookie to subsequently post to a > form using that session id? > > For example: > > http://domain.com/restricted/login.cgi > > Post here, get cookie > > http://domain.com/restricted/stuff/dosomething.cgi > > Now post to this form, or others below /restricted > > Any help would be greatly appreciated. > > Thanks, > > CA > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From christophe.delord at free.fr Wed Jul 10 16:40:14 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Wed, 10 Jul 2002 22:40:14 +0200 Subject: Behaviour of print in functions References: Message-ID: <20020710224014.27499085.christophe.delord@free.fr> You must use the global statement to assign global variables : http://www.python.org/doc/current/ref/global.html ----- The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. While using global names is automatic if they are not defined in the local scope, assigning to global names would be impossible without global. ----- Try this : def foo(): global X print X X = 100 print X Christophe. On Wed, 10 Jul 2002 20:11:33 GMT "Craig McLean" wrote: > I'm learning Python and I have run into something I can't explain. I have > the following code > > X = 99 > def foo(): > print X > X = 100 > print X > > foo() > > When I call foo it complains that local variable X is referenced before been > assigned. However X is a global and I was under the impression that it > should realize that and resolve it automatically. > > I know that if you add a "global X" as the first line of function foo then > this all works properly. > > I also know that > > X=99 > def qux(): > print X > > qux() > > prints 99 as I would expect. > > I'm assuming what is happening is that name resolutions use the LGB rule, > but assignments always create a new entry in the local namespace, without > checking to see if it is covering up a global object of the same name. I'm > also assuming that this happens before any of the code in the function is > executed. > > Am I correct? Or is something else happening here. > > > -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From aleax at aleax.it Fri Jul 26 02:48:52 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 08:48:52 +0200 Subject: how to count lines in a file ? In-Reply-To: <200207260746.00524.rjones@ekit-inc.com> References: <7aU%8.139472$vm5.4528856@news2.tin.it> <200207260746.00524.rjones@ekit-inc.com> Message-ID: On Thursday 25 July 2002 11:46 pm, Richard Jones wrote: ... > I think the major problem that we're running into here is that before there > was GC, the refcounting-based cleanup of objects was clear, > straight-forward and reliable. Now it's not clear when objects are cleared > up. That's a fairly major problem for some of us old-timers (and, quite Yes, I've witnessed this panic reaction at other times, most widely in the migration (still going on right now) from Microsoft's COM to their .NET. COM is defined with reference count semantics (a bit stricter than Python's in that counts are per-interface rather than per-object, but that's a minor difference in this context). .NET is defined with generic GC semantics, and if you consider the likely possibility of _distributed_ systems, it's even more important in their case. Distributed variants of COM never scaled up decently because of the synchronization implications of RC -- and the distributed semantics was often subtly different from the local case, too, at least in terms of timing. In other words, RC was truly hellish (over and above the reference loops and so on) and moving to generic GC a *huge* win in the COM to .NET transition, rather than just a neat one for Python. And for all that -- "some of them old-timers" (not me, as one of my very first job tasks had been to consider how to design hardware help for GC, and that was back when GC basically meant "mark and sweep" to most guys [at least for sure most _hardware_ guys]) are STILL bitching and moaning to this day. > possibly, a lot of newbies) to come to terms with. I hadn't realised that Don't worry about newbies -- they're likely to come from Java, these days, thus with full exposure to general GC. If they've had no previous programming exposure, they don't particularly expect "the computer" to clean up after them anyway -- they're used to, e.g., explicitly closing applications and documents, the idea of explicitly calling .close() on some object that needs to be closed is perfectly natural. C (if there are any more newbies coming from C) also requires explicit cleanup, much more fussily so than Python too. No, the problem is with reasonably experienced programmers -- not experienced enough to have worked extensively in, say, Java, or Lisp, or Smalltalk, but with experience in languages and systems that do rely on reference counts (or in some cases stack allocation, like C++). > GC threw such a big, ugly spanner in the works :( It's not as bad as it looks. I wish there was some slightly handier way to express try/finally, yes -- say the equivalent of atexit but applied to exiting the current function, to avoid the deep nesting and open/close separation that try/finally may require: a = open('a') try: b = open('b') try: c = open('c') try: process(a,b,c) finally: c.close() finally: b.close() finally: a.close() Since flat is better than nested, I *DO* dream of being able to express this very common structure without all the indents. Say that 'onclose' was a new keyword, this would become: a = open('a') onclose: a.close() b = open('b') onclose: b.close() c = open('c') onclose: c.close() process(a,b,c) Now THAT is something I would find vastly superior, both to the deep obscuring nesting that try/finally requires, and to CPython's (and C++'s) idea of relying on destructors executing implicitly "at the right time". Admittedly "onclose" is a wretched choice for a keyword. "finally:" without an accompanying "try" would be neat but perhaps might mask some syntax errors. But, the semantics' the thing. Oh well. Alex From chris.gonnerman at newcenturycomputers.net Thu Jul 11 08:00:58 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 11 Jul 2002 07:00:58 -0500 Subject: Win32 Registry Manipulation w/PythonWin? References: <3D2CDB4F.4357F810@cascade-sys.com> <005b01c2288a$f3bad1e0$0101010a@local> <3D2D0D8C.8F8B2121@cascade-sys.com> Message-ID: <005101c228d2$a31068c0$0101010a@local> ----- Original Message ----- From: "James J. Besemer" > > http://www.oreilly.com/catalog/pythonwin32/ > > My email filters back-fired and filed most of this thread (with a > tundraware.com to or from) into a folder for a different list, wherein the > lazy allusion should have sufficed. > > Also this explains they otherwise confusing "why isn't this in c-l.py?" I *was* kidding. I did know who Whatzizname referred to... but it is a quite (Monty) Pythonic joke to actually *name* someone Whatzizname. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From zbortolo at vt.edu Fri Jul 19 13:36:26 2002 From: zbortolo at vt.edu (Zachary Bortolot) Date: 19 Jul 2002 10:36:26 -0700 Subject: Newbie Word & Text file access? References: <3D381EB2.1030506@mcw.net> Message-ID: <25c15ddd.0207190936.38deb917@posting.google.com> Hi David, I had this problem as well when I was first learning Python. The solution for me was to replace the backslashes with forward slashes, so the line would read: open("C:/DownLoad/test1.txt", "r") Good luck! Zack Bortolot David Wilson wrote in message news:<3D381EB2.1030506 at mcw.net>... > Newbie question after checking about 500 messages on comp.lang.python : > Using W2K on Intel, Python 2.2.1, and IDLE 0.8 > > Unsuccessful open() of MS Word (.doc) , Abiword (.abw) and text (.txt) > files after successfully opening and reading HTML (.html) and LOG files. > > Sample IDLE output: > > >>> open("C:\DownLoad\test1.txt","r") > Traceback (most recent call last): > File "", line 1, in ? > open("C:\DownLoad\test1.txt","r") > IOError: [Errno 2] No such file or directory: 'C:\\DownLoad\test1.txt' > > > 1) What else is necessary to open these types of files? > > 2) Please advise where I can find documentation on IDLE and/or Python > errors such as "[Errno 2]" above? > > 3) Is there a parser utility which can massage these formatted document > files for faster/easier subsequent manipulation? > > Thanks in advance. > > ddw From jdhunter at nitace.bsd.uchicago.edu Thu Jul 18 20:48:03 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 18 Jul 2002 19:48:03 -0500 Subject: Percent sign in format string? References: Message-ID: >>>>> "Ron" == Ron Levine writes: Ron> How can I put a "%" sign in a format string? % quotes itself: >>> print '%d%%' % 5 5% From mgilfix at eecs.tufts.edu Tue Jul 23 19:09:08 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Tue, 23 Jul 2002 19:09:08 -0400 Subject: list to string In-Reply-To: <200207232243.g6NMh8G04597@localhost.localdomain>; from dreed@capital.edu on Tue, Jul 23, 2002 at 06:43:08PM -0400 References: <20020723174006.B3170@eecs.tufts.edu> <200207232243.g6NMh8G04597@localhost.localdomain> Message-ID: <20020723190908.D3170@eecs.tufts.edu> Yeah, but the topic said "list to string" so I figured that it might apply to another context than what was just given in the post.. -- Mike On Tue, Jul 23 @ 18:43, Dave Reed wrote: > > Wouldn't > > all_text = file.read() > > do what you want instead of reading the lines and then joining them? > > Dave -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From sholden at holdenweb.com Tue Jul 2 08:08:25 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 2 Jul 2002 08:08:25 -0400 Subject: [NEWBIE]-Object referencing?? References: Message-ID: "Alistair Campbell" wrote in message news:z8bU8.1944$yY2.74422 at ozemail.com.au... > Hi, > > I have class defined as below > > > ... > class Brew: > > def __init__(self): > self.brew_id="" > self.brew_date="" > self.brew_type="" > self.hydro_init='1040' > self.hydro_final='1000' > self.starter="" > self.amt_start="" > > def alcohol(self): > return > ((string.atoi(self.hydro_init)-string.atoi(self.hydro_final))*0.00036251)*10 > > ... > > > I assign data from a file so the data that goes into the alcohol method > needs to be converted from string. > The problem is that when I try to reference an instantiation of the Brew() > class, i.e; > > current_brew=Brew() > > I can get all the other data items but a call to; > > current_brew.alcohol > > returns > > > > So. I know that the calculation of alcohol content is not true but I am just > fiddling and will put in the correct formula when I get round to it. > > But, what am I doing wrong in relation to my definition or calling of the > Brew.alcohol method? > > Trivial but nonetheless I have to start learning somewhere. Your help is > much appreciated. > Alistair: Now this is my kind of application - forget all that wimpy networking and GUI stuff, let's get some alcohol brewing! You've already been told that you have to actually *call* the alcohol() method to get it to do the computation. I just though I'd ask if there was a particular reason why the hydro_init and hydro_final attributes are stored as strings? If you converted them into numbers (presumably integers will do) when you input them then you could simplify your alcohol method to def alcohol(self): return (self.hydro_init-self.hydro_final)*0.00036251*10 Also note that there's an int() built-in (actually it's a type in 2.2 and on) that will convert a string into an integer for you. By the way, it seems a little weird to not just multiply the difference by 0.0036251 -- is there some reason for the separate multiplication by 10? Anyway, good luck with the program. And remember, beer is *not* just a good breakfast. a-balanced-meal-is-a-pint-in-each-hand-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From zopestoller at thomas-guettler.de Wed Jul 3 07:58:54 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 03 Jul 2002 13:58:54 +0200 Subject: Syntax Error at end of file References: Message-ID: <3D22E6FE.9070705@thomas-guettler.de> Opus wrote: > I find it helpful to use an editor that does color coding. Many will color > code with strings as well. Would have helped you in this case. I do. I use emacs, but this time highlighting did not work. But it would be very nice if the python parser would tell what input token it was searching for, and where the start token is. thomas From sam at webslingerz.com Mon Jul 1 09:08:26 2002 From: sam at webslingerz.com (Sam Brauer) Date: Mon, 01 Jul 2002 09:08:26 -0400 Subject: xslt on windows References: <3d204ef7.15906605@usenet.plus.net> Message-ID: <3D20544A.7010106@webslingerz.com> If you're using 4Suite-0.12.0, there is no xml.xslt to import. Instead, you should import Ft.Xml.Xslt. This is mentioned at http://4suite.org/docs/howto/UNIX.xml in the section "Important for Application Developers". This is the case regardless of OS. Here's a really basic example of usage: import Ft.Xml.Xslt.Processor, Ft.Xml.InputSource import sys if(len(sys.argv) < 3): sys.stderr.write("usage: %s style.xsl doc.xml\n" % sys.argv[0]) sys.exit(1) processor = Ft.Xml.Xslt.Processor.Processor() f = open(sys.argv[1]) xsl_data = f.read() f.close() f = open(sys.argv[2]) xml_data = f.read() f.close() processor.appendStylesheet(Ft.Xml.InputSource.DefaultFactory.fromString(xsl_data, "uri")) result = processor.run(Ft.Xml.InputSource.DefaultFactory.fromString(xml_data, "uri")) processor.reset() print xml_data (Some of the long lines at the end of the script may have unintended linebreaks.) By the way, it would probably be best to ask about this sort of thing on 4suite's mailing list... http://lists.fourthought.com/mailman/listinfo/4suite Tim Rowe wrote: > I suspect that's the same problem I'm having with 4suite under Windows > ME, but nobody has come back to me, either. I don't really know where > to go next except maybe to report it as a bug (at least in the > installation script if not in 4suite itself) > > On Fri, 28 Jun 2002 17:26:01 +0200, "Marko Faldix" > wrote: > > >>Hello, >> >>I tried installing 4suite's xslt on Win 2000, but I really don't know how to >>deal with pathes. >> >>I used >> >> Python-2.2.1.exe >> win32all-146.exe >> 4Suite-0.12.0a2.win32-py2.2.exe >> >>All scripts, wether if command-line or through web server, doesn't know >>module xml.xslt. >> >>Unfortunately, you can't import a module *.site-packages.*, where * is >>anything, because "-" is forbidden as part of module names. >> >>Also, you can't copy directories from site-packages to c:\python22, they >>don't work properly then. >> >>Is there anybody using xslt with python? Maybe better with linux in place of >>windows? >> >>Best wishes, >>-- >>Marko Faldix >>M+R Infosysteme >>Hubert-Wienen-Str. 24 52070 Aachen >>Tel.: 0241-93878-16 Fax.:0241-875095 >>E-Mail: marko.faldix at mplusr.de >> >> > > From gerhard.haering at gmx.de Wed Jul 24 13:44:59 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 24 Jul 2002 17:44:59 GMT Subject: Geek-Ware in Germany References: Message-ID: Thomas Guettler wrote: > Hi! > > Does some know where I can get python geek ware (t-shirts, hats) > in germany? Alas, I don't know the answer :-( Maybe somebody who has the graphics files for the Python T-Shirts of a previous Python conference or so can publish them? You could also ask on the python-de mailing list, I think Christian Tismer, might know more, for example. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mf at mrinfo.de Mon Jul 1 10:47:41 2002 From: mf at mrinfo.de (Marko Faldix) Date: Mon, 1 Jul 2002 16:47:41 +0200 Subject: xslt on windows References: <3d204ef7.15906605@usenet.plus.net> Message-ID: Hello, "Sam Brauer" schrieb im Newsbeitrag news:mailman.1025529003.27827.python-list at python.org... > If you're using 4Suite-0.12.0, there is no xml.xslt to import. > Instead, you should import Ft.Xml.Xslt. this was my problem it is now solved. -- Marko Faldix M+R Infosysteme Hubert-Wienen-Str. 24 52070 Aachen Tel.: 0241-93878-16 Fax.:0241-875095 E-Mail: marko.faldix at mplusr.de [snip] From pecora at anvil.nrl.navy.mil Wed Jul 10 10:19:11 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 10 Jul 2002 10:19:11 -0400 Subject: Why self? References: Message-ID: <100720021019119427%pecora@anvil.nrl.navy.mil> In article , Delaney, Timothy wrote: > x, t, z, a, tseries = self.x, self.t, self.z, self.a, self.tseries > > self.y = x**2 * t/z + a * FFT(tseries) Not bad. I might be able to live with that one extra line. Thanks. (my therapist thanks you, too). -- Lou Pecora - My views are my own. From jdhunter at nitace.bsd.uchicago.edu Tue Jul 16 15:07:02 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 16 Jul 2002 14:07:02 -0500 Subject: map del efficiency python2.2 and 2.1 References: Message-ID: >>>>> "Alex" == Alex Martelli writes: Alex> Another likely performance boost in 2.2 would be: Alex> m = dict(pairs(seq)) Yes, very nice. This is the fastest yet. Using the generator pairs func in the loop for (key, val) in pairs(seq): m[key] = int(val) is indeed a good bit faster than the list comp approach, but slower than the xrange stride 2 ugly thingie. But dict(pairs(seq)) is faster and cleaner than either. Thanks. Alex> Regarding del time, you could measure that directly by doing Alex> a "del m" and seeing times before and after; also, just in Alex> case (shouldn't matter, but...), you could try gc.disable() Alex> and see if that makes a difference. The reported time required for the 'del m' is miniscule, 0.2s. Interestingly, though, if I do the 'del m', the extra wait at the end of the python 2.2 run is dramatically reduced and comparable to that in 2.1. gc.disable() did not have an appreciable effect, but after I read your post I did a google groups search on garbage collection and found that others have talked about an exponential increase in gc times: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&threadm=mailman.1021733430.3746.python-list%40python.org&rnum=1&prev=/groups%3Fq%3Ddisable%2Bgarbage%2Bcollection%2Bpython%26ie%3DISO-8859-1%26hl%3Den%26btnG%3DGoogle%2BSearch I'm still experimenting with this and if I figure anything more out, I'll post. John Hunter From smouttebolleke at hotmail.com Sun Jul 7 17:46:40 2002 From: smouttebolleke at hotmail.com (MontrezVosSeins) Date: 7 Jul 2002 14:46:40 -0700 Subject: Why is it crashing? (newbie) References: Message-ID: smouttebolleke at hotmail.com (MontrezVosSeins) wrote in message news: Oeps, sorry about my 2 posts, didn't know it took 3h to 9h > maybe this should do it, > > menu() > menu_choice = input("Choose one of the options: ") > if menu_choice == 1: > run_test(get_questions()) > elif menu_choice == 2: > ... > elif menu_choice == 3: > print "Byee" > else: > print "Whoops, illegal choice, try again." From yduppen at xs4all.nl Tue Jul 23 09:44:34 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Tue, 23 Jul 2002 15:44:34 +0200 Subject: No subject References: <3d3d53f4.356458609@news.skynet.be> Message-ID: <3d3d5dc4$0$94901$e4fe514c@dreader3.news.xs4all.nl> >> What datatypes can one use as key in a dictionary? > anything immutable. thats numbers, strings, tumples And of course any object that implements the __hash__(self) method. (Note: it is usually a good idea only to implement __hash__ for immutable objects; hashing mutable objects can give very... interesting results) YDD -- .sigmentation Fault From mark at mceahern.com Fri Jul 12 16:37:23 2002 From: mark at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 15:37:23 -0500 Subject: switch recipe? In-Reply-To: <1026505435.3406.46.camel@software1.logiplex.internal> Message-ID: > or possibly: > > def make_switch(*args): > """Return a generator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") > def switch(): > while True: > for a in args: > yield a > return switch Holy cow, that's much nicer! Thanks, // mark - From mgilfix at eecs.tufts.edu Tue Jul 23 17:40:06 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Tue, 23 Jul 2002 17:40:06 -0400 Subject: list to string In-Reply-To: ; from whisper@oz.net on Tue, Jul 23, 2002 at 01:08:59PM -0700 References: Message-ID: <20020723174006.B3170@eecs.tufts.edu> It sounds like you want to do something like this: list = [ 'this', ' ', 'is', ' a', ' test' ] string = ''.join (list) Or if you want a space and you just have a list of strings: string = ' '.join (list) The character in the source string is used to join the elements in the list of the join() call. So in the context of what you're written here, you could do: file = open ('foo.txt', 'r') lines = file.readlines () all_text = ''.join (lines) -- Mike On Tue, Jul 23 @ 13:08, David LeBlanc wrote: > I have this code: > > fn = file('foo.txt') > > txt = fn.readlines() > > str = ?something?(txt) # or txt.?something?()... > > What's the something? This is probably so obvious, i'm going to feel dumb, > but I havn't been able to find anything in any doc I've looked at. > > David LeBlanc > Seattle, WA USA > > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (whisper) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From oren-py-l at hishome.net Wed Jul 3 09:58:51 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 3 Jul 2002 09:58:51 -0400 Subject: Thread safetyness in Python In-Reply-To: References: Message-ID: <20020703135851.GA73351@hishome.net> On Wed, Jul 03, 2002 at 12:52:32PM +0000, John Goerzen wrote: > Hi, > > I have some questions about what is thread-safe in Python. Can someone tell > me whether each of the following are thread-safe: > > 1. a = a + 1 > 2. a = a + 2 > 3. list.append(x) > 4. list.remove(x) > 5. del(list[0]) >From www.python.org/doc/current/api/threads.html : Therefore, the rule exists that only the thread that has acquired the global interpreter lock may operate on Python objects or call Python/C API functions. In order to support multi-threaded Python programs, the interpreter regularly releases and reacquires the lock -- by default, every ten bytecode instructions (this can be changed with sys.setcheckinterval()). The lock is also released and reacquired around potentially blocking I/O operations like reading or writing a file, so that other threads can run while the thread that requests the I/O is waiting for the I/O operation to complete. The resolution is one bytecode operation so a+=1 is atomic but not a=a+1. The list operations above are atomic. Oren From b.maryniuk at forbis.lt Tue Jul 9 11:07:48 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 17:07:48 +0200 Subject: j2ee and python and evil competitors In-Reply-To: <96c7f32.0207090659.b5b9a27@posting.google.com> References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: <200207091707.48899.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 16:59, curt finch wrote: > ftp://ftp.jump.net/pub/journyx/other/PythonWhtPaper0_1.doc Right people will not download this. M$ Word DOC is *evil* format. Please do PDF, DVI or HTML instead. -- Sincerely yours, Bogdan M. Maryniuck "Absolutely nothing should be concluded from these figures except that no conclusion can be drawn from them." (By Joseph L. Brothers, Linux/PowerPC Project) From aahz at pythoncraft.com Tue Jul 23 13:47:25 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2002 13:47:25 -0400 Subject: Queue.Queue examples? References: Message-ID: In article , David Garamond wrote: > >despite having read the manual, i'm still totally ignorant on the basic >concept of Queue and how can it be used to safely pass objects between >two (or more) threads. could someone enlighten me? See the thread tutorial on my web page for some examples. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From fperez528 at yahoo.com Tue Jul 23 12:02:49 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 23 Jul 2002 10:02:49 -0600 Subject: Make me beautiful (code needs help) References: Message-ID: Mark wrote: > Ok, I have the following data: > > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] > > That is, I want to get the successive differences into their proper place. > I don't care what is in the question mark spot.??I'll?figure?that?out?later. Use Numeric: In [9]: from Numeric import * In [10]: data ={} In [11]: data["A"] = array([1,2,4,10,50]) In [12]: data["new"] = data['A'][1:] - data['A'][:-1] In [13]: data['new'] Out[13]: array([ 1, 2, 6, 40]) > Now, the other problem, is that in general, I want to fill data["new"] with > an arbitary function of the values in data["A"].??As?a?dumb?example,?I > might want to fill data["new"] with copies of the mean (average) of > data["A"].??So,?in?some?cases,?the?new?values?are?relative?to?the?current > location (ie i and i-1) and in other they are absolute (ie all of them). > > I can certainly hack through this, but I'm looking for something pretty.??I > know python is up to it. For this kind of thing, look at Numeric. It has a ton of functions ready-made for numerical processing, very convenient slicing syntax (better than python lists) and as a bonus it's fast. Explicit loops in python over large lists for numerical processing take an eternity and a half. That's what Numeric is for. cheers, f. From fredrik at pythonware.com Sun Jul 21 16:41:11 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Jul 2002 20:41:11 GMT Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? References: <8d3e714e.0207210836.7f8a51c8@posting.google.com> <0BC_8.112265$vm5.3832285@news2.tin.it> Message-ID: Alex wrote: > I do hope Ascher and Lundh find the time to update "Learning" to > 2.2 very soon, of course.' Ascher and Lutz. Lundh is busy updating and expanding "Library" for 2.2/2.3. From asokanp at virtusa.com Sat Jul 20 09:46:37 2002 From: asokanp at virtusa.com (Pichai Asokan) Date: 20 Jul 2002 06:46:37 -0700 Subject: Lists & two dimensions Message-ID: I am a trainer and in a training session a participant came up with a problem that stumped me: Here is the code snippet that isolates what I want: -------------------- board = [[-1] * 3 ]*3 print board board[1][2] = 'x' print board -------------------- Output ----------------------- [ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ] [ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ] ----------------------- I thought board = [[-1] * 3 ]*3 should give me a list of 9 elements; but ... What is going on? Where can we read more to understand what is goingg on? P Asokan From donn at u.washington.edu Tue Jul 30 13:18:21 2002 From: donn at u.washington.edu (Donn Cave) Date: 30 Jul 2002 17:18:21 GMT Subject: How to execute an external binary reading from standard in References: <3D46A6FC.AA068BC8@iki.fi> Message-ID: Quoth Markus O Kaukonen : | I tried | os.popen('/home/mok/my_prog.bin < my_input.txt ') | with no success That works for me. A couple of followups have suggested other things that also should work, but since we don't know what went wrong here, it's hard to say why any of those will work better. If none of them actually works for you, or if you actually want to understand what's going wrong, a simple example program would help explain what you expected, and what actually happened. Donn Cave, donn at u.washington.edu From zopestoller at thomas-guettler.de Thu Jul 4 03:13:17 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 04 Jul 2002 09:13:17 +0200 Subject: Syntax Error at end of file References: <3D22E6FE.9070705@thomas-guettler.de> Message-ID: <3D23F58D.8080705@thomas-guettler.de> Skip Montanaro wrote: > Thomas> But it would be very nice if the python parser would tell what > Thomas> input token it was searching for, and where the start token is. > > In a similar thread which occurred just a few days ago it was observed (by > Tim Peters, I think) that the set of acceptable characters at any particular > point in the parse is big, so enumerating them in the error message would be > counterproductive and would just serve to confuse the issue in most cases. Yes, listing all acceptable characters would be difficult. But it would be easy if the parser is inside a '''-string and reaches the end of file, that it tells me where the string started. I added it to my list of possible python inhancements. One day I want to see how you can add this to the parser thomas From kristian.ovaska at helsinki.fi Tue Jul 30 04:08:04 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Tue, 30 Jul 2002 11:08:04 +0300 Subject: lexing nested parenthesis References: Message-ID: Dave Cinege : >Primarily I want to do search, evaluate, modify, and replace >on a line by line basis. The diffculty comes with matching >arbitrary nested constructs, IE nested parenthesis. You can't parse those with regular languages - that's a mathematical fact. Maybe you can play some tricks with nonregular extension, or maybe not, but I don't think it's worth trying. You need a stronger parsing method that handles nested constructs. The language cathegory you're dealing with is called context-free grammars. It's more expressive than regular languages, and it can parse any programming language. Yacc is a classic C tool for this. PLY is a Lex+Yacc implementation in pure Python. SPARK is another Python tool, and there are some others. -- Kristian Ovaska From aleax at aleax.it Wed Jul 10 05:05:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 09:05:17 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: Tim Daneliuk wrote: > Does some kind soul out there happen to have a pointer to a > tutorial/examples on fiddling with the Win32 registry from PythonWin? There are a lot in the online cookbook, http://aspn.activestate.com/ASPN/Cookbook/Python -- looking for registry there gives 7 hits, each a relevant recipe. Alex From matt_gerrans at hp.com Wed Jul 10 14:58:20 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Wed, 10 Jul 2002 11:58:20 -0700 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: > ... I take doc extensions to mean "This document is intended > for Microsoft customers only". Or "Open this to install the latest VBScript virus on your machine" (Yes, I know that macros can ostensibly be disabled in Word and Excel, but I don't necessarily trust that checking the "High Security Level" radio button really blocks all macros -- it is a black box, after all) From squelart at hotmail.nospam.com Wed Jul 24 22:02:19 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Thu, 25 Jul 2002 12:02:19 +1000 Subject: Float class with infinity and stuff, interval computations Message-ID: <3d3f5c2b$1@duster.adelaide.on.net> Hi all, Before I start coding away, I'd like to know if there's a module that implements a float-like class that includes +/-infinity, NaN and possibly +/-overflow. I had a quick look at the Vault, but didn't see anything like that. If it effectively does not exist, is anybody be interested? (i.e. should I publish it?) Looking at the bigger picture (wow, sounds serious ;-), I'm working on an interval computations class. Same questions as above... Cheers, Gerald. From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 10 11:33:33 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 10 Jul 2002 15:33:33 +0000 Subject: Fwd: Re: askopenfilename????? Message-ID: <200207101437.g6AEbR720459@helios.gatwick.geco-prakla.slb.com> Whoops I sent to OP only (AGAIN!) ---------- Forwarded Message ---------- Subject: Re: askopenfilename????? Date: Wed, 10 Jul 2002 14:53:16 +0000 From: Martin Franklin To: jubafre at zipmail.com.br On Wednesday 10 Jul 2002 1:49 pm, jubafre at zipmail.com.br wrote: > i don?t know how to use a filetypes option of askopenfilename, somebody > can help? > > > askopenfilename(filetypes=???) From the module comments:- $ more /usr/local/lib/python2.2/lib-tk/tkFileDialog.py # # Instant Python # $Id: tkFileDialog.py,v 1.4 2001/11/08 17:51:33 loewis Exp $ # # tk common file dialogues # # this module provides interfaces to the native file dialogues # available in Tk 4.2 and newer, and the directory dialogue available # in Tk 8.3 and newer. # # written by Fredrik Lundh, May 1997. # # # options (all have default values): # # - defaultextension: added to filename if not explicitly given # # - filetypes: sequence of (label, pattern) tuples. the same pattern # may occur with several patterns. use "*" as pattern to indicate # all files. # so for python file types.. filetypes=(('python source', '*.py'), ('compiled python', '*.pyc')) interactive example..... [bpse at m-franklin dev]$ python Python 2.2.1 (#3, May 29 2002, 20:32:44) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import * >>> import tkFileDialog >>> fil=tkFileDialog.askopenfilename(filetypes=(('python source', '*.py'), ('compiled python', '*.pyc'))) Cheers Martin ------------------------------------------------------- -- Martin Franklin Initial Software Solutions (44) (0)1293 556629 / (44) (0)1234 888960 mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 10 15:33:16 2002 From lellinghaus at yahoo.com Mon Jul 8 05:35:12 2002 From: lellinghaus at yahoo.com (Lance Ellinghaus) Date: Mon, 8 Jul 2002 02:35:12 -0700 (PDT) Subject: shadow password module Message-ID: <20020708093512.50722.qmail@web20909.mail.yahoo.com> Does anyone have a module to handle shadow passwords like the pwdmodule handles the /etc/passwd file? This needs to run on Solaris 2.8. I don't want to have to reinvent the wheel if I can keep from doing it. Thanks, Lance Ellinghaus ===== -- Lance Ellinghaus __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com From bdesth at nospam.free.fr Mon Jul 8 22:56:05 2002 From: bdesth at nospam.free.fr (laotseu) Date: Mon, 08 Jul 2002 22:56:05 -0400 Subject: Making computer into server for free References: Message-ID: <3D2A50C5.9050508@nospam.free.fr> Ali K wrote: > I would like to know how to make my computer into a web site host with which > I can use python for making my website. Please Reply. Thank You. > > What was your question about Python ? Use a web server (Apache may be a good choice) laotseu From whisper at oz.net Tue Jul 9 19:44:51 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 9 Jul 2002 16:44:51 -0700 Subject: openprojects python room is ruled by dangerous people In-Reply-To: Message-ID: efbot detector? David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Fredrik Lundh > Sent: Tuesday, July 09, 2002 16:04 > To: python-list at python.org > Subject: Re: openprojects python room is ruled by dangerous people > > > Martijn wrote: > > > They do kick you out a bit readily, I agree. I got somewhat annoyed > > when I got kicked out while apologizing for spamming with a misfired > > copy & paste buffer. > > the first time I visited, I was kicked out (and banned, iirc) > within a couple of seconds... > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From aahz at pythoncraft.com Mon Jul 1 00:46:29 2002 From: aahz at pythoncraft.com (Aahz) Date: 1 Jul 2002 00:46:29 -0400 Subject: Is this a __slot__ bug? References: Message-ID: In article , Ian McMeans wrote: > >I wasn't able to find a good documentation of slots on the python website. >Do you have a link handy? I guess I'm just bad at searching, I couldn't find >a description in the first few pages of google either. Remembering the key word "descrintro" helps to Google: http://www.python.org/2.2.1/descrintro.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From hancock at anansispaceworks.com Tue Jul 2 09:42:41 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 02 Jul 2002 06:42:41 -0700 Subject: GoTo considered missing References: <20020703010101.4372.99712.Mailman@mail.python.org> Message-ID: <3D21ADD1.54775D25@anansispaceworks.com> From: "Harvey Frey" > OK. I'm a spaghetti-coder from way back, new to Python. > I didn't even realize there was no "goto" till I tried to rewrite a big C > program in Python. > > Breaks and Continues are fine for single loops, but: > What is the approved Python method for getting from the bottom of a set of > nested loops to the top? > > Maybe I could rewrite the big loop with function calls, but I'd be > knee-deep in recursion. You should probably try to use an exception in this case. class ImDone(Exception): # ... I don't remember this bit because I remember # the now-deprecated exceptions-are-strings syntax pass try: loop ... loop ... loop ... loop ... if special-reason-I-need-to-bail-out-like-Im-finished-early: raise ImDone except ImDone: # stuff I need to do after finishing This is pretty similar to the rare cases in C when "goto" is considered sound programming style. Exceptions are good for more than error-handling! Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From donnal at donnal.net Wed Jul 31 12:57:06 2002 From: donnal at donnal.net (Donnal Walter) Date: 31 Jul 2002 09:57:06 -0700 Subject: wxPython printing help References: Message-ID: <918bc22f.0207310857.2f9f1a06@posting.google.com> CJ wrote: > iIs this even possible or am I wasting my time? As far as I can tell, printing from PDF is NOT easily accomplished with the wxPython printing framework. It certainly is not as easy as opening a .pdf file and asking it to print. If you have the capability of generating HTML instead, you would be much better off using wxHtmlPrintout, which *IS* almost that easy. Donnal Walter From Chris.Barker at noaa.gov Thu Jul 18 12:56:16 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 18 Jul 2002 09:56:16 -0700 Subject: Hurray for new division!!! Message-ID: <3D36F32F.338551E8@noaa.gov> Hi all, After all the contentiousness about new division, I thought I'd post this little anecdote. I just spent quite a few hours debugging an error caused by using integer division when I didn't expect it (Python 2.1, with "old" division). It was caused by a piece of test code I wrote to compare the results of two different algorithms used in a C extension. The results should have been the same, and they weren't. The bug turns out to have been caused by integer division of two numbers, one of which should have been a Float, but in my test code I just just quickly hard coded in an easy constant that happened to be an integer, and got wrong results. It took me forever to find the problem! With new division there would have been no problem. This just reinforced the idea that the behavior of the division operator (or any operator) should not be a function of the type of operator (when the types are so similar) in a dynamic language. I am not a Newbie. I have been using various programming languages for over 20 years (if you count Basic on an 8k Commodore PET). I have been using Python pretty regularly for over 3 years. I am very much looking forward to new division being standard. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From dfeustel at mindspring.com Thu Jul 4 09:32:57 2002 From: dfeustel at mindspring.com (Dave Feustel) Date: Thu, 4 Jul 2002 08:32:57 -0500 Subject: Quaternion Arithmetic Module Message-ID: Is there a python module for doing quaternion arithmetic? Thanks, -- ------------------------------------------------------------ Dave Feustel http://www.mindspring.com/~dfeustel 260-483-1857 ------------------------------------------------------------ From whisper at oz.net Wed Jul 3 18:56:49 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 3 Jul 2002 15:56:49 -0700 Subject: python decimal infection? In-Reply-To: Message-ID: > I wonder where this puts the old Librascope RPC-9000 (ca 1960) which > used BCD coded in binary excess 3 (that is, 0 == 0011, 1 == 0100,etc, > with three non-digits at each end). > In a museum? :-) > --John Dave LeBlanc Seattle, WA USA From mwh at python.net Wed Jul 10 06:46:42 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 10 Jul 2002 10:46:42 GMT Subject: expect module and/or functionality? Or SSH wrapper module? References: Message-ID: claird at starbase.neosoft.com (Cameron Laird) writes: > If not, no, you can't Expect with pure Python; there's no > practical way to get the pseudoterminal munging right without > calls into the C run-time library that Python itself can't > access. Huh? You have openpty, forkpty, ioctl, setsid, setpgrp, ... what more do you need? > I'm working on techniques to use standard distribution instal- > lations of (Tcl-based) Expect and (pure) Python to achieve > general results. The idea is that many hosts--essentially > all Linuxes, for example--are already equipped with these > executables, so all you'd need to install are your pure-Python > scripts. I don't have these ready yet, though. Not to say that this isn't a worthy goal... Cheers, M. -- 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, 16 Sep 93 From gugabbe at hotmail.com Tue Jul 23 15:58:36 2002 From: gugabbe at hotmail.com (Mack) Date: Tue, 23 Jul 2002 21:58:36 +0200 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: In <3D3DB42D.3080404 at earthlink.net>, Hans Nowak wrote: > Mack wrote: > >>>>>[elem*2 for elem in li] >>>> >> File "", line 1 >> [elem*2 for elem in li] >> ^ >> is what i'm getting. Is my python too old? Is something else wrong? >> I've just cut and pasted from the tutorial into python ide. > > That's a list comprehension, which wasn't available in 1.5.2. I think it > first appeared in 2.0. Upgrading to a more recent Python version should > fix this. Thanks. I just checked out the doc Whats new in 2.0 and found it. I didn't think my redhat 7.1 was that old. I'll just upgrade then. From anton.wilson at camotion.com Fri Jul 26 18:10:49 2002 From: anton.wilson at camotion.com (anton wilson) Date: Fri, 26 Jul 2002 18:10:49 -0400 Subject: thread wierdness In-Reply-To: References: Message-ID: <200207262210.SAA23975@test-area.com> On Friday 26 July 2002 03:51 pm, Tim Peters wrote: > [anton wilson] > > > Ok, I see that python creates an init thread when the first > > thread is being created that sits there and does nothing but loop. > > That seems very pointless although I'm sure there is a reason for this. > > Try writing an equivalent C program and see what happens. This is almost > certainly something being done by your C runtime library, and/or OS. Yes, strangely enough it is . . . Anton From a.schapira at worldnet.att.net Thu Jul 18 09:18:38 2002 From: a.schapira at worldnet.att.net (Al Schapira) Date: Thu, 18 Jul 2002 13:18:38 GMT Subject: Adding a "PRINT" button Message-ID: <3D36C0CE.7080500@worldnet.att.net> I haven't seen this discussed anywhere. What is the proper way (or any good way) to add a "PRINT" button or "PRINT" submenu to a Python application? For example, how can a PRINT button be added to the IDLE GUI so that the current source or program output can be printed? Hopefully this can be done in an OS independent way, but I'll settle for something that works in W98. How can the print functionality make use of the underlying W98 print spooler? Thanks. -Al Schapira a.schapira at worldnet.att.net From deda at mypad.com Fri Jul 12 10:37:20 2002 From: deda at mypad.com (DeDa) Date: Fri, 12 Jul 2002 16:37:20 +0200 Subject: Converting 2 bytes string into INT Message-ID: Hi to all, I'm a newbie of Python and I already have a big problem. I read 2 bytes from files and I like to convert them into an integer. How can I do it? Thanks a lot. Bye, DeDa. From Gabe.Newcomb at noetix.com Mon Jul 22 22:19:08 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Mon, 22 Jul 2002 19:19:08 -0700 Subject: Is there a Tkinter mailing list? Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6114@NOXMAIL.noetixad.com> -----Original Message----- From: Tim Peters [mailto:tim.one at comcast.net] Sent: Monday, July 22, 2002 7:17 PM To: python-list at python.org Subject: RE: calendar lameness! [Terry Hancock] > ... > "calendar" is pretty neat -- except it has pretty > annoying arbitrary limits on the date: > > 1900-1/1 to 2038-1/18 > > I can see that this is adequate for a business > planner, but for historical or astronomical uses, > it's really inadequate. > ... Get Marc-Andre Lemburg's mxDateTime. Python 2.3 will have some sort of standard more-powerful datetime gimmick, but Guido is anti-interested in arguing with datetime weenies <0.9 wink>. > ... > This is Python 2.1. Anyway -- any chance these got > fixed in a later release? None. > Why the range? > ... > Actually, it looks like maybe it's "mktime" that > is the limiter here (?). Bingo! > ... > It seems like Python longs would make it unnecessary to > have such arbitrary limits. See Demo/classes/Dates.py in the Python source distribution. -- http://mail.python.org/mailman/listinfo/python-list From phr-n2002b at NOSPAMnightsong.com Tue Jul 9 02:12:01 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 08 Jul 2002 23:12:01 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2A078A.7040502@ob_scure.dk> <06F2E275AA053281.30FCDA468DD949D2.9ED8D7E798995448@lp.airnews.net> <3D2A2586.5070302@ob_scure.dk> <4QuW8.46343$Jj7.1305133@news1.tin.it> Message-ID: <7xd6txwhu6.fsf@ruckus.brouhaha.com> Alex Martelli writes: > > I'm a little scared though about using SQL too extensivly. > > Joe Celko's "SQL for Smarties" might be just what you need to move you > to the next level of SQL usage (or, to turn you off it for life, > depending:-). Philip Greenspun's SQL for Web Nerds http://philip.greenspun.com/sql/index.html is pretty good (at least for non-SQL-whizzes like me) and has a reasonable amount of info on performance tuning and optimization. One thing I remember about Oracle is that prepared queries really help. I don't know about other database. But if you're not using them, you probably should give them a try. From tchur at optushome.com.au Tue Jul 9 15:55:38 2002 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 10 Jul 2002 05:55:38 +1000 Subject: Multi-threading on Multi-CPU machines References: <3D29FC43.C239BD5F@earthlink.net> Message-ID: <3D2B3FBA.2054F616@optushome.com.au> Garry Taylor wrote: > > Joseph A Knapka wrote in message news:<3D29FC43.C239BD5F at earthlink.net>... > > Garry Taylor wrote: > > > > > > Hello, > > > I am attempting to make a multi-threading function in one of my > > > programs in an effort to gain a speed increase, but I'm getting quite > > > the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten > > > me as to why, > > > > Yes. CPython threads cannot utilize multiple CPUs, due to the > > Global Interpreter Lock, which may only be acquired by one > > thread at a time. Apparently Jython threads do not have > > this limitation, as the GIL doesn't exist in Jython, or so > > I'm told. So if you simply ran your program under Jython > > you might see an improvement. > > > > Cheers, > > > > -- Joe > > Thank you both for your anwsers, unfortunatly running under Jython is > not an option, as the whole program which I am writing runs to about > 5,000 lines and use lots of Python modules which I don't really fancy > trying to get to work under Jython. > > So, am I correct in thinking that there is nothing I can do about > this, and still use standard Python? I understand that Solaris has a > very good threading library, but from the comments above, I assume > that this would make no difference? Do you have any tips/ideas how I > could make use of multiple processors in a Python program? As someone else suggested, consider using MPI, which can be used to parallelise code on shared memory SMP machines as well as networked clusters. Installing user-mode LAM/MPI is very easy, although other forms of MPI such as MPICH may be a bit more difficult. However, once you have MPI installed, there are a number of Python MPI modules around which make using it a cinch. May I recommend PyPar, by Ole Nielsen at the Austrlian National University, as being particularly easy to use? See http://datamining.anu.edu.au/~ole/pypar/ I am pretty sure Ole has been using MPI and Pypar on multi-CPU Solaris machines as well as Linux Beowulf clusters and the hybrid shared/distributed memory APAC supercomputer at ANU. Tim C > > Thanks again > > Garry > -- > http://mail.python.org/mailman/listinfo/python-list From newfroups at jerf.org Fri Jul 12 11:53:45 2002 From: newfroups at jerf.org (Jeremy Bowers) Date: Fri, 12 Jul 2002 15:53:45 GMT Subject: Python to XML to Python conversion References: <3D2E1793.8030600@jerf.org> <3D2EBECF.4060907@jerf.org> Message-ID: <3D2ECC89.5080402@jerf.org> Jeremy Bowers wrote: > Alex Martelli wrote: >> I think this assertion, as it stands, is untenable. There just about >> IS *some* other way -- e.g., inventing your own little language for >> data description and writing from scratch the needed parsers in all >> languages and environments of interest. > > > That's order N effort rather then constant effort, thus that's not easy > parsing in other environments, that's the virtually impossible job we > were faced with 10 years ago. (SGML wasn't all that easy either, from > what I gather.) Though it occurs to me to point out a bit later that parsing somebody else's XML format can feel about as hard as parsing a new little language; XML libraries take care of the tokenizing and parsing step but you still get to do the semantic analysis yourself. If you're good with writing parsers (which usually implies tokenizing is a non-issue to that person), this can be a bad tradeoff if you could write a much simpler special-purpose language that would tokenize and parse into something more closely appropriate to the task at hand. Sometimes straight into the desired format; I, and others, have used Python source code files directly as configuration files before. Parsing an XML-version of those files is a pain, relative to the eas of 'parsing' the Python configuration file: from configuration import * or import configuration Complete with robust error detection. Part of the reason XML is useful is that programmers who have not dedicated their lives to writing compilers find it easier to muddle through the semantic analysis then to write a good tokenizer and parser, as the latter largely *can't* be muddled through for any non-trivial language. (Parsers are powerful but do like to bite hard.) Of course, other reasons include the fact that this tokenizer/parser is available in multiple languages, reasonably human readable, etc. This message is an observation and food for though, not the whole of my XML views. I may not even agree with this observation tommorow. ;-) From johnboik at sbcglobal.net Wed Jul 3 01:39:21 2002 From: johnboik at sbcglobal.net (John Boik) Date: Wed, 03 Jul 2002 05:39:21 GMT Subject: newbie problem with canvas create_image Message-ID: Hi: Im having a problem that I just cant figure out. I am trying to create a simple program that has a gif in a canvas on a frame. I imported Tkinter and Image, created the frame for the widget and then have: photo=Image.open("name.gif") photo2=photo.rotate(10) photo2.show() cnv= Canvas(pane.pane("right")) cnv.create_image(5,50,anchor=SW, image=photo) cnv.pack() For this code I get the following message: Traceback (most recent call last): File "C:\Python22\digitizer.py", line 33, in ? cnv.create_image(5,50,anchor=SW, image=photo) File "C:\Python22\lib\lib-tk\Tkinter.py", line 1949, in create_image return self._create('image', args, kw) File "C:\Python22\lib\lib-tk\Tkinter.py", line 1939, in _create (self._w, 'create', itemType) TclError: image "" doesn't exist I would think that Image is imported OK because I do get the rotated image shown in a frame. But for some reason, create_image does not work. It did work, however, when I used it with: photo= PhotoImage("name.gif") but I would rather use Image.open because I want to use the rotate and resize commands. Any idea why create_image would not work? Thanks. John From glingl at aon.at Sat Jul 13 04:25:49 2002 From: glingl at aon.at (Gregor Lingl) Date: Sat, 13 Jul 2002 10:25:49 +0200 Subject: dir() shows strange behaviour with VPython Message-ID: <3d2fe41e$0$25552$91cee783@newsreader02.highway.telekom.at> I thought to understand the dir() function, but... ... when playing around with VPython I encountered the following: >>> from visual import * Visual-2002-06-14 >>> s=sphere() # beautiful white sphere displayed immediately >>> s >>> dir(s) ['__class__', 'axis', 'blue', 'color', 'constr', 'display', 'frame', 'green', 'name', 'pos', 'radius', 'red', 'rotate', 'up', 'visible', 'x', 'y', 'z'] >>> s.__methods__ ['rotate'] >>> s.__dict__ {'__class__': } >>> s.__members__ ['axis', 'blue', 'color', 'display', 'frame', 'green', 'pos', 'radius', 'red', 'up', 'visible', 'x', 'y', 'z'] >>> s.name Traceback (most recent call last): File "", line 1, in ? s.name AttributeError: name >>> So, what are 'name' and 'constr', which both do not appear neither in s.__members__ nor in s.__dict__ nor in s.__methods__, but in the list returned by dir(s)? (Or: what is generally returned by dir() ?) Perhaps there is somebody who can explain this. Thanks, Gregor In other words: what happens in the following example, should not happen in my understanding: >>> from visual import * Visual-2002-06-14 >>> s = sphere() >>> for att in dir(s): print att, ':', print type(eval('s.'+att)) __class__ : axis : blue : color : constr : Traceback (most recent call last): File "", line 3, in ? print type(eval('y.'+att)) File "", line 0, in ? AttributeError: constr >>> From guido at python.org Wed Jul 31 10:55:52 2002 From: guido at python.org (Guido van Rossum) Date: Wed, 31 Jul 2002 10:55:52 -0400 Subject: ANN: Python Spread Module 1.3 Released Message-ID: <200207311455.g6VEtqQ00460@odiug.zope.com> I've released version 1.3 of the Spread Module for Python: http://www.python.org/other/spread/ About the Spread Module ----------------------- This package contains a simple Python wrapper module for the Spread toolkit (see below). The wrapper is compatible with Python 2.1 and 2.2. It wraps Spread mailboxes and messages in Python objects with appropriate methods and attributes, and turns Spread errors into Python exceptions. Virtually all Spread features are accessible from Python. About Spread ------------ >From the Spread website (http://www.spread.org): Spread is a toolkit that provides a high performance messaging service that is resilient to faults across external or internal networks. Spread functions as a unified message bus for distributed applications, and provides highly tuned application-level multicast and group communication support. Spread services range from reliable message passing to fully ordered messages with delivery guarantees, even in case of computer failures and network partitions. Spread is designed to encapsulate the challenging aspects of asynchronous networks and enable the construction of scalable distributed applications, allowing application builders to focus on the differentiating components of their application. Changes since release 1.2 ------------------------- - Critical bugfix: We didn't realize that the service_type argument to Spread's SP_receive() is an input parameter as well as an output parameter, and consequently didn't initialize it. Depending on what trash happened to be sitting on the stack, this could cause Spread to deliberately drop data (a backward compatibility feature in Spread triggered by passing the DROP_RECV flag in service_type on input). Enjoy! --Guido van Rossum (home page: http://www.python.org/~guido/) From kristian.ovaska at helsinki.fi Thu Jul 25 04:46:29 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Thu, 25 Jul 2002 11:46:29 +0300 Subject: crc32 with wintel files References: <7cgrjukbcu3piev8mn1uuc94g104pu9d9n@4ax.com> Message-ID: <2nevju0oav8sqrjfii9cj0q6eemjkr3a2b@4ax.com> Chris Hartemink : >I'm trying to create crc32 checksums for files, not strings. When you call file.read(), it returns a string which you can feed to the crc32 funtion. Remember to open the file in binary 'rb' mode. If the files get large, you might want to read the file in chunks of limited size using file.read(CHUNKSIZE). In this case, you pass the so-far-computed checksum to crc32 as the second argument. -- Kristian Ovaska From donn at u.washington.edu Fri Jul 5 12:48:05 2002 From: donn at u.washington.edu (Donn Cave) Date: 5 Jul 2002 16:48:05 GMT Subject: sending a file through sockets References: <3D253AA6.1090806@nowhere.org> Message-ID: Quoth Bryan Olson : | brueckd at tbye.com wrote: ... |> but to send the length of the file first so the receiving end |> knows if and when it got the whole thing. | | That's not really needed. Just call shutdown(1) when finished writing. | The receiver can detect the end when recv() returns zero bytes without | error, which only happens on clean shutdown. The socket will also | select() as readable just before the zero-byte recv(). Fine if the file is all you're sending, but it's like "who needs an on-off switch on this appliance, when you can just cut the power cord with a pair of insulated wire cutters." A byte count prefix usually is needed, and in the rare case when it isn't, it doesn't cost much to do it anyway. | The only snag is if a local error causes the sender to close the socket | before sending all the data. Note that in the code, you don't actually | check that you've received as much data as expected. The code uses the | size to know when to stop reading, and the "if not data: break" will do | that anyway. Yes, the actual application would certainly want to verify that it received the complete file. |> Anyway, here's some sample code, but if |> you're not already familiar with sockets then you should spend a little |> time experimenting with them. | | Did you test this? The Python library uses the empty string for | INADDR_ANY, which is fine for bind(), but I don't think it's legal for | connect(). So, did you test it? I did! According to my results, he's right, you're wrong. | I understand it's a basic demo, but I'll note that any real application | requires some time-out discipline to avoid very long hangs. Also on | most Unix systems we'd need to watch out for signals that force system | calls to return. We would? I never have, and I don't notice the standard library modules doing that. It might something to think about, but hardly the given it would be in C. Does any real application need a timeout discipline? Some applications probably need one, but "real" or not doesn't sound like a very useful way to think about it. Donn Cave, donn at u.washington.edu From mhammond at skippinet.com.au Mon Jul 1 21:40:24 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 02 Jul 2002 01:40:24 GMT Subject: Python COM installation and NT Administrative rights. References: <3281a460.0206290652.51b800c9@posting.google.com> <3D1EB9C7.70901@skippinet.com.au> <3281a460.0207011507.2cd668c5@posting.google.com> Message-ID: <3D210547.10908@skippinet.com.au> P Adhia wrote: > Mark Hammond wrote in message > > >>Installing Python 2.2 + the latest win32all *should* work here - but I >>am sure there will be some problems. > > > I downloaded > > http://starship.python.net/crew/mhammond/downloads/win32all-148.exe > > Installation program just quits immediately after the first welcome > screen. The last dialog box that comes up recommends that I rerun the > program with administrative privileges - something that I don't > control. Damn :( I will check it out and see what the problem is for the next win32all build. Mark. From uwe.schmitt at procoders.net Mon Jul 29 04:39:41 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 29 Jul 2002 08:39:41 GMT Subject: announcement References: Message-ID: Gerhard H?ring wrote: | Uwe Schmitt wrote in comp.lang.python: | One correction for rnetgui.py: | try: | from win32api import RegOpenKeyEx, RegQueryValueEx, error | from win32con import HKEY_LOCAL_MACHINE, KEY_READ | key = RegOpenKeyEx(HKEY_LOCAL_MACHINE,r'SOFTWARE\Ziarc',0,KEY_READ) | homepath=RegQueryValueEx(key,'Path')[0] | #except error: | except Exception, reason: | homepath=os.path.abspath(".") | I replaced the "except error:" line to get it running on Linux. Thanks, I missed to check if the lates version runs on linux. The code after try makes only sense for the soon following ziarc windows installer. | You might want to do a | try: | from win32api import ... | except ImportError: | # ... | to check wether the win32 extensions are available, which on | non-Windows system, they usually aren't ;-) the import statemente is not the only statement which might rise an exception, the line begining with "homepath=" might cause an exception too. Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt python, php, c++, codes, tips, tutorials at uwe.schmitt at procoders.net http://www.procoders.net From aleax at aleax.it Sat Jul 20 04:56:49 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 08:56:49 GMT Subject: file ops on the fly ? References: <21TZ8.101254$vm5.3505549@news2.tin.it> Message-ID: Shagshag13 wrote: > > "Alex Martelli" a ?crit dans le message de news: > 21TZ8.101254$vm5.3505549 at news2.tin.it... >> Shagshag13 wrote: >> >> > hello, >> > >> > is it possible (and how) to do "on the fly" reading and updating on >> > file ? >> >> You can open a file for 'r+b' and then call both read and write on it, >> moving around with seek and possibly tell. This is hardly ever useful >> on a text file, though. But I guess much depends on what you mean by >> "on the fly" in this context -- maybe the simulation of inplace edits >> for text files offered by standard module fileinput is all you need? > > thanks, i'm going to look at fileinput... > > ans yes i'm working on big file (>1go). From a sequential reading (line by > line) i need to do line insertion and/or line deletion in my file. And i > don't wish to create a new (wasting place) file. fileinput's _simulation_ of inplace edits actually creates a new file. If you can afford it -- i.e. if you have enough free space on disk for the new-file creation -- it's no waste at all: the old file will disappear as soon as the sequential pass is done and the new one will take the old one's name. It's an *investment* of temporary disk use to gain huge speed and simplicity. Think of a file as an array of bytes on disk. What does it imply to "insert a line" somewhere in the middle, actually operating on that disk space rather than using auxiliary space elsewhere on the disk (given that your file does not fit in memory)? Think about it. It implies inserting an arbitrary number of bytes without damaging the following ones. How do you do that? Answer: you MOVE all the following bytes forward by just enough. So you're reading on average half a gigabyte (the part of your file that follows the insertion point) and writing half a gigabyte back to disk. For ANY insertion, be it even seven bytes or whatever. How many insertions are you going to do? A dozen? That's about 12 gigabytes of data you're moving. *shudder*. If you do a sequential pass and writing to a new file you're reading 1gig, writing 1gig -- total 2 gigabytes data moved rather than 12. If you do 100 insertions, still 2 gigabytes rather than 50. And so on. You could speed your program up by 100, 1000, or ten thousand times, dependiong on the number of insertions. Are you STILL inclined to call it a "waste" ... ?-) Deletions are much the same. Coding the insertions and the deletions is tricky and bug-prone (while doing them while sequentially copying is trivial), but THAT might perhaps be finessed by a refined implementation in a library... but there's no way to finesse the ENORMOUS slow-down you'd incur. Some INCREDIBLY clever buffering algorithm might perhaps be able to DOUBLE the speed of your desired in-place-editing approach depending on your patterns of deletions and insertions, by using (not wasting:-) memory most cleverly. So you'd only slow down by say 500 times insted of by 1000. Do you think it would be worth the huge coding effort? Buy a new disk. They're cheap, VERY cheap. Or, change your data's structure. A flat text file does not really make much sense when dealing with gigabytes, particularly for data that needs to be updated in-place (conceptually) such as yours. *INVEST* (not a waste!-) some disk space into structuring your data in a way that is a closer match for your application's needs...! Alex From sholden at holdenweb.com Tue Jul 30 06:19:41 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 30 Jul 2002 06:19:41 -0400 Subject: wxTextCtrl + wxGrid References: Message-ID: "Thorsten Gawantka" wrote ... > Hi Group, > how can I get the Value of wxTextCtrl into a Cell of wxGrid? > my actual code is > > -- > ## Copy the textCtrl.Value into gridCell > self.grid.SetCellValue(i, 0, self.edit_p1.GetValue) > ## > -- > > this is not functional, because the python interpreter > want to have a string. > How can I get this solved? > You probably want to *call* the GetValue method of the wxTextCtrl rather than referring to it. It's a mistake most have made ... try self.grid.SetCellValue(i, 0, self.edit_p1.GetValue()) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From marklists at mceahern.com Fri Jul 12 18:45:27 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 17:45:27 -0500 Subject: switch recipe? In-Reply-To: Message-ID: [Tim Peters] > The top one generates an unbounded sequence, due to the "while True". The > Icon language calls this "repeated alternation", and actually has a prefix > operator for it (the vertical bar). > > What I'm unclear about is why we're writing a function to return > a generator function: why not write a generator function directly? Well dang, my original motivation was so I could pass around the generator without specifying the args. As you point out, that's completely unnecessary. Thanks! > So my candidate for simplification is: > > def make_switch(*args): > """Generate the elements in args repeatedly.""" > if not args: > raise TypeError("at least one argument required") > while True: > for a in args: > yield a > > I'd lose the "if not args:" block, though; if the arglist is > empty, it will > simply terminate without yielding anything, and that's what I expect the > empty case to do. If you leave the while True, then it won't raise StopIteration when you call it without arguments. The simple fix is to replace that with while args. Here's the result of my latest tinkering. For what it's worth, I think I prefer raising the error in the generator when args is not specified rather than waiting until next() is called the first time--on the principle that raising the error earlier is better. Still, this version shows the delayed raise.... #! /usr/bin/env python from __future__ import generators import unittest def repeat(*args): """Return an unbounded iterator that repeatedly iterates over args.""" while args: for a in args: yield a def weave(values, repeat, weaver): for item in values: yield weaver(item, repeat.next()) def color_item(item, color): template = "<%(color)s>%(item)s" return template % locals() class test(unittest.TestCase): def test(self): values = range(10) colors = ("red", "organge", "yellow", "green", "blue", "indigo", "violet") repeat_colors = repeat(*colors) expected = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] generated = [x for x in weave(values, repeat_colors, color_item)] self.assertEquals(expected, generated) def test_empty(self): r = repeat() self.assertRaises(StopIteration, r.next) if __name__ == "__main__": unittest.main() - From and-google at doxdesk.com Fri Jul 12 05:47:57 2002 From: and-google at doxdesk.com (Andrew Clover) Date: 12 Jul 2002 02:47:57 -0700 Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <3D2487CB.9000102@gmx.de> <3D24FAC5.3050406@something.invalid> Message-ID: <2c60a528.0207120147.498bc1f3@posting.google.com> Thomas Bellman wrote: > I *would* have liked that to be > > repeat: > part_1() > while test_1(): > part_2() > while test_2(): > part_3() > in Python, but that is unfortunately not compatible with the > current Python syntax. :-( I like that kind of syntax. I'd like to propose an alternative keyword: while cond1: dofoo() andwhile cond2: dobar() with an analogous structure: if cond1: dofoo() andif cond2: dobar() else: doqux() where foo is done if cond1, bar is done if (cond1 and cond2) and qux is done if not (cond1 and cond2). For consistency with elif it could be called anif instead? -- Andrew Clover mailto:and at doxdesk.com http://and.doxdesk.com/ From chris.gonnerman at newcenturycomputers.net Fri Jul 5 11:57:07 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 05 Jul 2002 10:57:07 CDT Subject: Getting Process List On *nix In-Reply-To: <1025880972.1933.28.camel@lestat.howden.press.net> Message-ID: <200207051717.MAA09035@paris.k12.mo.us> On 05 Jul 2002 15:56:12 +0100, John Abel wrote: > I am trying to write a script, capable of running on Win32, and *nix, > which looks for certain processes. However, I can't seem to find any > details of how to access of list of running processes under *nix, > without shelling out, something I'm loathe to do. Use os.popen(). I know you don't want to shell out, but trust me, it's easier this way. The process listing on proprietary Unix systems is sometimes in the kernel memory image (only) and sometimes exposed by the /proc filesystem interface (if you have that on your Unix). Further AFAIK there is no reliably implemented standard for how this data is to be retrieved. On the other hand, adapting to the output format of different versions of the ps command is pretty simple. > I'd be grateful for any pointers. > > John From whisper at oz.net Sun Jul 7 02:49:28 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 6 Jul 2002 23:49:28 -0700 Subject: Chinese language support of Python? In-Reply-To: Message-ID: This may not be of much help, but Tk, the library behind Tkinter, is quite popular for displaying Asian languages and there was a substantial body of work done. Some changes where made to standard Tk to accomodate Asian language display. You might find it necessary to build a custom version of Tk for Tkinter to link with and possibly also modify some of the Tkinter wrapper. You should be able to get more information about Asian language support in Tk by asking on the comp.lang.tcl newsgroup. You can also find some good information on Tk at http://www.tcl.tk/. You can also find a pointer to a "traditional Chinese" page from http://tcl.sourceforge.net/faqs/tcl/ Then, of course, there's Chinese Python at http://chinesepython.cosoft.org.cn/cgi-bin/cgb/home.html (in chinese - also has a Sourceforge page at http://sourceforge.net/projects/chinesepython/ in english). There are other links about tkinter and chinese at yahoo - I just entered tkinter and chinese (without the word "and"). Note: while Tcl is a nice language, I do not suggest you abandon Python for Tcl, especially if more then basic MS-Windows support is important to you. I personally think Python might have a speed edge too. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Leon Wang > Sent: Saturday, July 06, 2002 22:55 > To: python-list at python.org > Subject: Re: Chinese language support of Python? > > > Hi, I got the Chinese displayed correctly in window title without > change the default encoding in site.py by: > > root.title(u'\u4e2d\u6587') > > But still can not put Chinese directly as string in source, I can not > live with so much \u... for a whole Chinese sensence/paragraph, it's > impossible to read and edit them :( > However, I can print Chinese string (normal string, without u prefix > and \u codes) in console with command line python.exe. How can I let > Tkinter accept that? > > martin at v.loewis.de (Martin v. Loewis) wrote in message > news:... > > Boudewijn Rempt writes: > > > > > > root.title('中文') # this is Chinese > > [...] > > > If you use _real_ unicode -- for instance > > > root.title(u'\u028A\u0288') # no chinese, because of lacking > fonts, but IPA > > > then everything works fine -- at least, with my window > manager, on my OS. > > > > It's more likely that the OP meant > > > > root.title(u'\u4e2d\u6587') > > > > Regards, > > Martin > -- > http://mail.python.org/mailman/listinfo/python-list From jslowery at hotmail.com Fri Jul 5 23:41:24 2002 From: jslowery at hotmail.com (Jeremy S Lowery) Date: Fri, 5 Jul 2002 22:41:24 -0500 Subject: problems with a for loop (noobie) References: <1IsV8.42194$Fc1.850199@wagner.videotron.net> Message-ID: <%BtV8.46202$wj4.3665644@e3500-atl2.usenetserver.com> "Charles Mantha" wrote in message news:1IsV8.42194$Fc1.850199 at wagner.videotron.net... > Reading the Python Tutorial by Guido van Russom and there's an example that > I don't get, and seems to not be explained (at least not enought for me). > The line < ... if n % x == 0: >, what does the % do? % is the mod operator. It retrieves the remainder of the operands, from dividing them. >>> 4 % 2 0 4 / 2 = 2 r 0 >>> 20 % 8 4 20 / 8 = 2 r 4 Just remember 3rd grade, when you did remainders and not decimals :) > Also I just seem to not get the logic of this program. Would be nice if > someone would explain it to me. if n % m == 0 then n is equally divisible by m (i.e. no remainder). like 4 % 2, 27 % 3, 121 % 11, 32 % 8 If you're into prime numbers: http://www.utm.edu/research/primes/prove/index.html Jeremy S Lowery From skip at pobox.com Sat Jul 20 08:48:54 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Jul 2002 07:48:54 -0500 Subject: Funny behaviour of MySQLdb In-Reply-To: References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> Message-ID: <15673.23606.257022.388489@localhost.localdomain> >> I just tried the single-threaded way, and that works... Hmm... Nothing >> apparently different, except that I took out the base class >> SocketServer.ThreadingMixIn from the definition of the server class... Alex> Rule of thumb: always ensure a single thread interacts with any Alex> given external entity, be it a file, a database, the user, or even Alex> a global shared variable subject to updates. Hmmm... I'm not discounting your rule of thumb, but I use MySQL from a multi-threaded application with no problems (at least no problems of which I am aware). I maintain a pool of (currently five) connection objects in a Queue. Each thread which needs to chat with the database calls .get(), creates a cursor, chats, then returns the connection to the Queue. Guess I'll have to go back and reread the MySQL docs and refine my stress tests. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From pecora at anvil.nrl.navy.mil Sun Jul 21 09:56:18 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Sun, 21 Jul 2002 09:56:18 -0400 Subject: A better self References: Message-ID: <210720020956188669%pecora@anvil.nrl.navy.mil> In article , wrote: > Just an idea - since Python is so dynamic, instead of writing the > function you write a string describing the function and have another > function read it and generate a method that does all the 'self.' stuff. > Obviously you'd have to think it through some, but this is definitely > possible. > > In the above example, I assume MyCoolUnboundMethodMaker would read > the string, and use it to generate a string like this: > > '''def NewMethod(self, arg): > self.x = self.y * self.z + self.t * arg > ''' > > after which it would exec the string and then do a 'return NewMethod', and > bingo, your class now has a method that performs that operation. It'd take > some work to get it right the first time, but from then on you could reuse > it for all your numeric work. I gotta think about that one. Thanks. -- Lou Pecora - My views are my own. From aleax at aleax.it Fri Jul 26 06:36:56 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 10:36:56 GMT Subject: how to count lines in a file ? References: <1027656130.63094@yasure> <%I809.493664$o66.1339193@news-server.bigpond.net.au> Message-ID: Neil Hodgson wrote: > Alex Martelli: > >> One thought I've toyed with, at times, is to have the optional >> ability to mark a few objects as _requiring_ stricter finalization >> semantics than the run-of-the-mill kinds of objects. E.g., files >> could be marked that way. > > Some of the history behind .NET not having deterministic finalization > even for a subset of objects: > http://www.managedworld.com/articles/0003/article.aspx VERY good reference, and an excellent article too -- thanks! If nothing else, I can rub it in somebody's face next time said somebody says some absurdity about the abilities of MS's techies (some of them ARE really good, as this article shows:-). Note that .NET does make slightly stronger promises for finalizers than Java and other GC systems, even though, as the article's author notes, .NET's docs are rather cautious (one could say wishy-washy) about it, given (I surmise) the difficulty of defining what a "well behaved" program is in a distributed, networked environment. __del__ in Python (at least in general, i.e., considering Jython too) is far weaker than in .NET, *and* has the further trouble of impeding GC when it occurs in cycles. Thus, it might well be preferable to avoid a __del__ in Python where in an equivalent .NET case you would decide to write a finalizer "just in case". It's interesting to notice that the reason they gave up (prematurely) on deterministically-finalizing just SOME objects was a (doomed) attempt to preserve VB6's semantics. Eventually VB6 semantics went by the wayside anyway, but in the meantile deterministic finalization for just SOME objects had been abandoned. The author IS hinting that they're thinking about it again for the future:-). It also seems to me they haven't considered the specific approach that seems most feasible to me: do it per-object, not per-class, AND have an "object wrapped in a single-owner" only hand out WEAK references (proxies). Maybe too explicit for their tastes:-). However, their proposed "using" statement IS exactly what I've also been dreaming about to collapse deuced trees of try/finally statements (except for syntax sugar differences between C# and Python, of course:-). I wonder whether that's good or bad:-). Alex From loewis at informatik.hu-berlin.de Mon Jul 29 04:47:25 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 29 Jul 2002 10:47:25 +0200 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> <3D4263E7.3000107@ims.u-tokyo.ac.jp> <3D42D972.2060607@ims.u-tokyo.ac.jp> <3D438546.6010403@ims.u-tokyo.ac.jp> Message-ID: Michiel Jan Laurens de Hoon writes: > Well my real problem is how to get distutils to use gcc on unix systems. > As far as I know, I can only use --compiler='unix' on unix systems, > and for some reason my distutils ignores the environment variable > CC. So I always end up with the cc compiler, even if I set CC=gcc. Perhaps you didn't set the variable correctly? Regards, Martin From b.maryniuk at forbis.lt Tue Jul 23 04:19:20 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 23 Jul 2002 10:19:20 +0200 Subject: setting the screen resolution In-Reply-To: <6edeb2ff.0207220845.86b6ebd@posting.google.com> References: <6edeb2ff.0207220845.86b6ebd@posting.google.com> Message-ID: <200207231019.20814.b.maryniuk@forbis.lt> On Monday 22 July 2002 18:45, Chad Haynes wrote: > i am currently working on a program using wxPython which requires the > screen resolution to be 1024x768. Bad program, IMHO... -- Sincerely yours, Bogdan M. Maryniuck Be warned that typing \fBkillall \fIname\fP may not have the desired effect on non-Linux systems, especially when done by a privileged user. (From the killall manual page) From aleax at aleax.it Wed Jul 17 03:32:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 17 Jul 2002 07:32:16 GMT Subject: map del efficiency python2.2 and 2.1 References: Message-ID: <449Z8.89567$vm5.3207139@news2.tin.it> Bengt Richter wrote: > On Tue, 16 Jul 2002 15:53:43 GMT, Alex Martelli wrote: > >>John Hunter wrote: >> ... >>> def pairs(l): >>> return [(l[i], l[i+1]) for i in range(0, len(l), 2)] > ^^^^^ ... >>def pairs(L): >> for i in xrange(0, len(L), 2): > ^^^^^^ > ^ >> yield L[i], L[i+1] >> >>but that's a minor issue, I guess. >> >>Another likely performance boost in 2.2 would be: >> >>m = dict(pairs(seq)) >> >>with pairs coded as here shown. > > In case John didn't notice, that little 'x' your finger likely > typed automatically probably made some difference too ;-) Yep, but John had used xrange in other spots of his code, so I didn't think I needed to explain better. Still, that may have been an error on my part. So, the better explanation: range and list comprehensions build lists and thus may have to allocate lots of memory. xrange and generators don't build any list but rather return one item at a time as needed. But the importance of using xrange vs range is minor -- yes it does make SOME difference, but it's small. See: from __future__ import generators import time, gc L = range(300 * 1000) def timit(f): start = time.clock() m = dict(f(L)) stend = time.clock() print f.__name__, stend-start def pairs_lc_ra(L): return [ (L[i],L[i+1]) for i in range(0, len(L), 2) ] def pairs_lc_xr(L): return [ (L[i],L[i+1]) for i in xrange(0, len(L), 2) ] def pairs_ge_ra(L): for i in range(0, len(L), 2): yield L[i], L[i+1] def pairs_ge_xr(L): for i in range(0, len(L), 2): yield L[i], L[i+1] gc.disable() for i in range(3): for f in pairs_lc_ra, pairs_lc_xr, pairs_ge_ra, pairs_ge_xr: timit(f) [alex at lancelot MyDocuments]$ python pa.py pairs_lc_ra 0.53 pairs_lc_xr 0.52 pairs_ge_ra 0.29 pairs_ge_xr 0.28 pairs_lc_ra 0.52 pairs_lc_xr 0.52 pairs_ge_ra 0.28 pairs_ge_xr 0.28 pairs_lc_ra 0.52 pairs_lc_xr 0.52 pairs_ge_ra 0.28 pairs_ge_xr 0.28 This is with 2.2.1. 2.3 built from CVS lowers generator's advantage: [alex at lancelot src]$ ./python pa.py pairs_lc_ra 0.44 pairs_lc_xr 0.4 pairs_ge_ra 0.29 pairs_ge_xr 0.28 pairs_lc_ra 0.43 pairs_lc_xr 0.4 pairs_ge_ra 0.29 pairs_ge_xr 0.29 pairs_lc_ra 0.43 pairs_lc_xr 0.39 pairs_ge_ra 0.29 pairs_ge_xr 0.29 but even here, using generators rather than list comprehensions seems still much more important than using xrange rather than range. Alex From peter at engcorp.com Tue Jul 23 22:20:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Jul 2002 22:20:56 -0400 Subject: Multikey dictionary References: <3d3d596e.357860250@news.skynet.be> Message-ID: <3D3E0F08.A32FE51E@engcorp.com> henk_derudder at hotmail.com wrote: > > Sory for reposting this, I forgot to mention a subject in my first > post :-) > > What datatypes can one use as key in a dictionary? > > Can I use for example two longs as key (kind of a double key)? > > If not, are there examples on how to achieve this? To experiment with this kind of thing the interactive prompt can be highly effective. You'll learn much more than if you just ask the group (not to say that you won't learn a lot from asking, too). >>> d = {} >>> d[5] = 5 >>> d[5L] = 6 >>> d {5: 6} >>> d[5, 6] = 7 >>> d {(5, 6): 7, 5: 6} >>> d[5L, 6L] = 88 >>> d {(5, 6): 88, 5: 6} Hmmm... looks like using "longs" (if you mean Python longs) is no different from using regular ints of the same value, and you can use two longs but they are obviously treated as though you'd explicitly used a tuple even though the parentheses were left out. -Peter From observer at NOSPAM.space.pl Tue Jul 16 03:31:42 2002 From: observer at NOSPAM.space.pl (Johann) Date: Tue, 16 Jul 2002 09:31:42 +0200 Subject: uniform interface for MySQL & MSSQL References: Message-ID: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> On Mon, 15 Jul 2002 19:38:28 GMT, Alex Martelli wrote: >Have you tried: >http://www.object-craft.com.au/projects/mssql/ It does not work. I tried to compile it under Cygwin but some files (*.h) are missing :-( In file included from mssqldb.c:25: mssqldb.h:37: sybfront.h: No such file or directory mssqldb.h:38: sybdb.h: No such file or directory error: command 'gcc' failed with exit status 1 I found this module have no cursor.seek(nr) method. :( -- Johann From bokr at oz.net Sat Jul 13 00:57:03 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2002 04:57:03 GMT Subject: List assignment, unexpected result References: Message-ID: On Wed, 10 Jul 2002 22:33:02 +0100, "Steve Coates" wrote: >Thanks for the help. I think my favourite solution was > >grid = [['.' * 4] for i in range(4)] > I think you should take Dave Reed's advice and use grid = [['.',] * 4 for i in range(4)] though you can leave out the the comma, since ['.',] is a list, not a one-element tuple >but I'll need to read up on the syntax. I haven't seen this >use of a for loop before. > As someone pointed out, it's a list comprehension, not a for loop. Your "favorite solution" is a little different from Dave's suggestion (as you've probably found out by now): >>> grid = [['.' * 4] for i in range(4)] >>> grid [['....'], ['....'], ['....'], ['....']] >>> grid [0][0] = '0' >>> grid [['0'], ['....'], ['....'], ['....']] IOW, even trivial things are worth testing ;-) vs. moving a right bracket to get Dave's version (w/o comma): >>> grid = [['.' * 4] for i in range(4)] : v ,-<-' v >>> grid = [['.'] * 4 for i in range(4)] >>> grid [['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']] >>> grid [0][0] = '0' >>> grid [['0', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']] or to finish, >>> for i in range(4): grid[i][i] = i ... >>> grid [[0, '.', '.', '.'], ['.', 1, '.', '.'], ['.', '.', 2, '.'], ['.', '.', '.', 3]] Regards, Bengt Richter From aleax at aleax.it Wed Jul 10 06:05:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 10:05:37 GMT Subject: 8 Queens Problem References: Message-ID: One way to think about the problem: you want all permutations of range(0,8) that satisfy certain constraints. The "permutations of range(0,8)" part is about having 8 queens on the board, never two on the same row or column; the "certain constraints" are about never having two queens in the same diagonal either. Omitting the "certain constraints" would clearly solve the "8 rooks problems", for example. The advantage of this approach is that it neatly break down the problem into two separately reusable parts: (a) generate all permutations, (b) filter a stream to yield only items that satisfy certain conditions. Permutations can be easily adapted e.g. from Danny Yoo's recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962 -- my favourite version being (needs 2.2 and from __future__ import generators, of course): def permute(sequence): if not sequence: yield sequence for i in range(len(sequence)): head = sequence[i:i+1] for tail in permute(sequence[:i]+sequence[i+1:]): yield head + tail permute(range(8)) will of course yield 8 factorial, 40320 permutations -- not too bad, so clearly we CAN afford this specific approach. The '8 rooks' solutions that we want to reject as '8 queens' solutions are clearly those where two queens are "in the same diagonal". Given the way we represent the board placements, the two diagonals on which the i-th queen lies are clearly identified by i+x[i] and i-x[i] where x is one of our permutations -- what we want is for each of these values to be unique for i in range(8), for x to be considered OK. The validation function is therefore not hard to program: def valid(board): for sign in (-1, 1): diagonals = {} for i in range(len(board)): diagonal = i + sign*board[i] if diagonal in diagonals: return False diagonals[diagonal] = True return True Now, we can plug together these two elements in any old way, e.g.: n = 0 m = 0 for board in permute(range(8)): n += 1 if valid(board): m += 1 print board print 'total: %d out of %d permutations' % (m, n) Or, we can choose to be more systematic, depending also on what ancillary information we require -- supposing we only want an iterator on all valid solutions, for example: def filter_iterator(iterator, filter_function): for item in iterator: if filter_function(item): yield item and for board in filter_iterator(permute(range(8)), valid): print board In this case, we don't know, at the top level, the total number of permutations considered, but then that wasn't a specification of the original problem, so that's OK. Alex From aahz at pythoncraft.com Mon Jul 1 17:26:44 2002 From: aahz at pythoncraft.com (Aahz) Date: 1 Jul 2002 17:26:44 -0400 Subject: New style classes as exceptions (Was: exception handing) References: <7V%T8.69851$F16.33443@atlpnn01.usenetserver.com> Message-ID: In article , Jonathan Hogg wrote: >On 1/7/2002 18:02, in article >7V%T8.69851$F16.33443 at atlpnn01.usenetserver.com, "Steve Holden" > wrote: >> >> I think it's currently a feature, but it will doubtless become a bug if this >> situation continues for too long... > >... as you say, if new-style classes are the future, and certainly the >present now, then it doesn't make much sense to not be able to raise them. Upgrading Python is complex dance between moving forward and maintaining backward compatibility. There have been long threads on python-dev about this if you want to look for them. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From raims at dot.com Mon Jul 29 11:24:43 2002 From: raims at dot.com (Rhymes) Date: Mon, 29 Jul 2002 17:24:43 +0200 Subject: [ZOPE] Zope, Python, Win2k and Mysql References: <4a4akukkfg92po76t3svc7flen29s3stui@4ax.com> Message-ID: On Mon, 29 Jul 2002 12:27:37 +0200, "Gillou" wrote: >You should... > >1/ Install Python 2.1.3 from www.python.org (even if you lalready got the >one provided with Zope) > >2/ Install mysqdb from sourceforge on top of this new python installation > >3/ change the "start.bat" file to run zope from that python.exe (tipycally >c:\python2.1\python.exe) > >This does the job for me. I don't want another Python distribution... I have the 2.2.1 one Could I follow only your third tip? -- Rhymes (rhymes at myself.com) http://www26.brinkster.com/rhymes " ride or die " From eugene1977 at hotmail.com Wed Jul 17 09:21:04 2002 From: eugene1977 at hotmail.com (Eugene Kim) Date: Wed, 17 Jul 2002 09:21:04 -0400 Subject: any comment on my first program plz.. References: Message-ID: hi.. i finally managed to parse history.xml file and feed them into postgresql i got some questions.. i'm using pyxml, postgresql-python.rpm 1.when i prepare queryString for db.query(queryString) it's really pain to take care of "'", ",".. is there any elegant solution? 2.queryString can't contain special characters such as + '...and more error message ------------ UnicodeError: ASCII encoding error: ordinal not in range(128) ------------ any solution for this? i'd like to store exactly same string in db 3. well.. i'm just upset that many documentations are outdated and it's really hard to find good documentation about python I'm trying to crawl all websites that i visit in db and query through cgi.. size of db is going to be several hundred gigs.. python has any advantage over other languages for my purpose? i'm fairly comfortable with java but not python.. can i go with java? thx for any comment... #!/usr/bin/python import string import xml.sax.handler import _pg user=_pg.set_defuser('postgres') db=_pg.connect('test','localhost') class HistoryHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inItem =0 self.mapping={} self.count=0 def startElement(self, name, attributes): if name=="item": self.url=string.replace(attributes["url"], "'", '"') # needs to handle more special characters... self.title=string.replace(attributes["title"], "'", '"') self.firsttime=attributes["first_time"] self.lasttime=attributes["last_time"] self.visits=attributes["visits"] tmp = "\'" sqlselect = 'SELECT url, visits FROM history WHERE url = \'' + self.url + "';" result = db.query(sqlselect).getresult() if(result): existUrl = str(result[0][0]) newVisits=str(result[0][1]+ int(self.visits)) sqlclause = 'UPDATE history SET visits =' + newVisits + ' WHERE url = \'' + existUrl + '\'' else: sqlclause = 'INSERT INTO history VALUES (' + tmp + self.title + tmp +","+ tmp + self.url + tmp + "," + self.firsttime + "," + self.lasttime + "," + self.visits + " )" db.query(sqlclause) # import pprint parser = xml.sax.make_parser( ) handler = HistoryHandler( ) parser.setContentHandler(handler) parser.parse("smallhistory.xml") # pprint.pprint(handler.mapping) From donnal at donnal.net Sat Jul 20 08:41:15 2002 From: donnal at donnal.net (Donnal Walter) Date: 20 Jul 2002 05:41:15 -0700 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> Message-ID: <918bc22f.0207200441.7a5a130d@posting.google.com> Peter Hansen wrote: > Roy Smith wrote: > > Peter Hansen wrote: > > > Rename the runTest() > > > method to start with the text "test", and then change the __main__ > > > content to be simply 'unittest.main()' instead of the dictEntries.run > > > that you have. > > > > OK, that seemed to work, even though I'm still not sure I understand all > > the subtleties of what's going on, and what role all the various classes > > (TestCase, TestSuite, TestResult, TestLoader, etc) play. > > I don't really either, but I've never needed to. Basically just subclass > TestCase and do the above and you may never need to either. :) Yes, it's all very confusing to me. I love unit tests, but I've been unable to grok the API for TestSuites. Let's say I have a module named "cell.py" and a corresponding test module "unit.cell_unit.py" with the following code: import unittest from cell import Cell class Test(unittest.TestCase): def test1(self): x = Cell() self.failUnless(isinstance(x, Cell)) def test2(self): assert_(1 != 2) if __name__ == '__main__': unittest.main() This is just as Peter suggested above, and I can run this unit test from the command line just fine. But, now let's say that I want to make it part of a test suite by adding the following code to cell.py: if __name__ == '__main__': import unittest import unit.cell_unit ts = unittest.TestSuite() ts.addTest(unit.cell_unit.Test()) unittest.TextTestRunner().run(ts) Now I get the following error: ValueError: no such test method in unit.cell_unit.Test: runTest unless I add a runTest definition to cell_unit.Test: def runTest(self): self.test1() self.test2() . . . Somehow I don't think this is how it was intended to be used, but so far it is the only way I can figure out to make it work. Can anyone tell me what am I doing wrong? From aleax at aleax.it Mon Jul 8 05:57:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 09:57:58 GMT Subject: Memory ? References: Message-ID: Shagshag13 wrote: > > Great thanks for the reply ! It helps a lot to understand ! > >> I'm not sure what you mean by "boxed" in this context. > > That i can' t guess the size of my arrays (range from 0 to ???) Both the array.array type, and the vastly more powerful Numeric.array type from the Numeric extension package, are arrays that can grow and shrink. >> But if you don't need such alterations and >> insertions, a mapping from the compact set [0..N) to any multiset of >> N values is indeed faster and less memory-hungry as a sequence, typically >> a list, than as a dictionary > > Sorry to ask but what do you call a "mapping" ? Python containers are divided into "mappings" and "sequences". Typical examples of sequences are lists, tuples, strings, instances of array.array. Typical examples of mappings are dictionaries. The lines between them are a bit blurry, particularly now that you can iterate directly on a dictionary (and presumably other mappings). In some fields of maths (abstract algebra) a mapping, or map, also called a function, is a relation M between sets D and R such that for each and every element d1 of D one, and only one pair (d1,r) is in M. The terminology about this is all over the map (:-) but it's still a useful concept to keep in mind -- it hints at underlying commonalities between (pure) functions, sequences, and mappings in the Python sense of the word, and implicitly suggests attempting interchanges between these implementation-separate approaches at the same (or, very similar) abstract functionality. In my paragraph that you quote above, they key issue is the clause *if you don't need such alterations and insertions*. Often, you do. Consider a FIFO queue implemented in the way that comes immediately to mind: class Fifo1(list): def get(self): return self.pop(0) def put(self, value): self.append(value) Now this is fine and dandy, BUT -- self.pop(0) removes the first element and thus is O(N) where N is the number of items in the queue at that time. If that is unacceptable, and you need O(1) behavior (or thereabouts), you can, instead, try: class Fifo2(list): def get(self): return self.pop(-1) def put(self, value): self.insert(0, value) but this just moves the O(N) behavior to put instead of get. The simplest way to get O(1) (roughly) on both operations is: class Fifo3(dict): def __init__(self): self.start = self.end = 0 def get(self): result = self[self.start] del self[self.start] self.start += 1 return result def put(self, value): self[self.end] = value self.end += 1 In Python 2.3 I might code the get method a bit differently: def get(self): try: return self.pop(self.start) finally: self.start += 1 but that doesn't change the essential characteristics at all, it just lets get and put have a more similar structure and thus arguably enhances clarity. Alex From mgerrans at mindspring.com Mon Jul 8 03:36:40 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 8 Jul 2002 00:36:40 -0700 Subject: Properties - when and why References: Message-ID: > def V_homogenous(self): > V = self.V > return array((V.x,V.y,V.z,1.)) > > Seriously, what COULD be simpler -- or, less special-case...?! Exactly what I was thinking! Alex, are you psychic, or was this obvious? ;-) > > Is the when and why of using properties something that can be > > explained in few enough words? > > Use properties when you want the syntax of attribute access > and the semantics of a method call. That has nothing to do > with the fact that if you need "common subexpression elimination" > you need to write that out explicitly -- Python never eliminates > common subexpressions by itself. Additionally, properties are of great value in creating read-only members and are great for controlling a valid state of objects, since they can do range-checking on the input. Sure, you can do all this without properties (as for instance, in Java, where the properties effect in JavaBeans is achieved by an agreed-upon standard), but they make it much more clean and standard. Having been weaned (from MFC!) on Delphi and C++ Builder (and more recently C#), I think properties are a great thing, especially for Python. Since it doesn't have strong typing, properties can go a long way in ensuring an object's state remains valid or that an exception is raised close to the actual cause of the problem (that being the bad assignment; without the property, you might not discover the problem until much later, when the member variable is used). Properties also add flexibility: for instance, with assignment, you could assign either a 3-item list or tuple to your W property and it could be designed to work just fine either way. Hmm, I hope that wasn't too many words. - mfg From daniel.dittmar at sap.com Thu Jul 4 12:44:27 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 4 Jul 2002 18:44:27 +0200 Subject: testing a sequence for 'identicalness' References: Message-ID: > does anybody knwo how I can check a sequence for 'identical ness', > ie given a sequence: > > [1,1,1,1,1,1,1,1,1,1] > > it would be classified as 100% identical > > and > > [1,1,1,1,1,1,1,1,1,2] > > would be classified as 90% identical. Assuming [2,1,1,1,1,1,1,1,1,1] is also 90% identical: - create a dictionary where you count the occurrences (a Bag in Smalltalk speak) - counters = bag.values () - identicalness = sum (counters) / max (counters) Daniel From mwh at python.net Mon Jul 8 07:05:55 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 8 Jul 2002 11:05:55 GMT Subject: Given PID, make sure a process is running on Unix? References: <3D2761CD.1090503@lindbergs.org> Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > [VanL] > > > I am trying to get write a python script that on Unix reads a PID from > > a file and, if that process is still running, exits. If the process is > > not running, the process would be started. [...] Any help? > > You could work along the lines of: > > try: > os.kill(PID, 0) > except OSError: > print PID, 'is not running' > else: > print PID, 'is running' > > Killing a process with signal 0 never kills it. :-) You might want to check why the kill failed -- if the process exists but is owned by another user (and you're not root), then you get an OSError, but with a different errno. try: os.kill(PID, 0) except OSError, err: if err.err == errno.EPERM: print PID, 'is running' else: print PID, 'is not running' else: print PID, 'is running' Whether this distinction matters is something I can't predict from here. Cheers, M. -- Structure is _nothing_ if it is all you got. Skeletons _spook_ people if they try to walk around on their own. I really wonder why XML does not. -- Erik Naggum, comp.lang.lisp From bergeston at yahoo.fr Wed Jul 31 11:58:15 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Wed, 31 Jul 2002 17:58:15 +0200 Subject: Use python without install it. Message-ID: Hi, Does somebody know if it is possible to use python on a computer under Linux on that it's not allowed to install it for security reasons (server in production) ? The purpose is to have some shell scripts written in Python to make some maintenance tasks. Those scripts are launched manually. Run it from a CD rom ? How ? Special user ? is it really secure ? Other idea ? TIA. B. From jknapka at earthlink.net Mon Jul 8 21:46:34 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 09 Jul 2002 01:46:34 GMT Subject: Generic vector aggregates References: Message-ID: <3D2A3FF5.FB9DA0A7@earthlink.net> Ingo Blank wrote: > > Hi, > > I want to implement a generic vector aggregate function for dyadic operators > like this: I believe the built-in reduce() function does exactly what you want (that is, it performs your aggregate() task). As for naming arithmetic operators, have a look at the "operator" module :-) Cheers, -- Joe > ## -- dyadic operators (primitives) > > def add(a,b): > return a + b > > def mul(a,b): > return a * b > > def inc(a,b): > return a + 1 > > ## -- generic aggregate > > def aggregate(f,v,start=0): > a = start > for x in v: > a = apply(f,(a,x)) > return a > > ## -- 2nd order callers > > def sum(v): > return aggregate(add,v,0) > > def prod(v): > return aggregate(mul,v,1) > > def count(v): > return aggregate(inc,v,0) > > ... and so on... > > Q: How can I refer to the built in arithmetic operators "+","*" etc. > This would save the additional dispatching step, without the need to > call > "add","mul" etc. > > Thanks > > --ingo > voy NG arktb QBG qr [ rot13 ] > > PGP PublicKey > http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x18B44974 -- "Thanks to Microsoft, I am now blind in both eyes. They have rolled back in my head so many times this week that they are apparently stuck there now." - Jonathan Rickman, regarding M$ anti-open-source PR. From barry at zope.com Mon Jul 29 14:38:06 2002 From: barry at zope.com (Barry A. Warsaw) Date: Mon, 29 Jul 2002 14:38:06 -0400 Subject: PEP 1, PEP Purpose and Guidelines Message-ID: <15685.35726.678832.241665@anthem.wooz.org> It has been a while since I posted a copy of PEP 1 to the mailing lists and newsgroups. I've recently done some updating of a few sections, so in the interest of gaining wider community participation in the Python development process, I'm posting the latest revision of PEP 1 here. A version of the PEP is always available on-line at http://www.python.org/peps/pep-0001.html Enjoy, -Barry -------------------- snip snip -------------------- PEP: 1 Title: PEP Purpose and Guidelines Version: $Revision: 1.36 $ Last-Modified: $Date: 2002/07/29 18:34:59 $ Author: Barry A. Warsaw, Jeremy Hylton Status: Active Type: Informational Created: 13-Jun-2000 Post-History: 21-Mar-2001, 29-Jul-2002 What is a PEP? PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python. The PEP should provide a concise technical specification of the feature and a rationale for the feature. We intend PEPs to be the primary mechanisms for proposing new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions. Because the PEPs are maintained as plain text files under CVS control, their revision history is the historical record of the feature proposal[1]. Kinds of PEPs There are two kinds of PEPs. A standards track PEP describes a new feature or implementation for Python. An informational PEP describes a Python design issue, or provides general guidelines or information to the Python community, but does not propose a new feature. Informational PEPs do not necessarily represent a Python community consensus or recommendation, so users and implementors are free to ignore informational PEPs or follow their advice. PEP Work Flow The PEP editor, Barry Warsaw , assigns numbers for each PEP and changes its status. The PEP process begins with a new idea for Python. It is highly recommended that a single PEP contain a single key proposal or new idea. The more focussed the PEP, the more successfully it tends to be. The PEP editor reserves the right to reject PEP proposals if they appear too unfocussed or too broad. If in doubt, split your PEP into several well-focussed ones. Each PEP must have a champion -- someone who writes the PEP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The PEP champion (a.k.a. Author) should first attempt to ascertain whether the idea is PEP-able. Small enhancements or patches often don't need a PEP and can be injected into the Python development work flow with a patch submission to the SourceForge patch manager[2] or feature request tracker[3]. The PEP champion then emails the PEP editor with a proposed title and a rough, but fleshed out, draft of the PEP. This draft must be written in PEP style as described below. If the PEP editor approves, he will assign the PEP a number, label it as standards track or informational, give it status 'draft', and create and check-in the initial draft of the PEP. The PEP editor will not unreasonably deny a PEP. Reasons for denying PEP status include duplication of effort, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Python philosophy. The BDFL (Benevolent Dictator for Life, Guido van Rossum) can be consulted during the approval phase, and is the final arbitrator of the draft's PEP-ability. If a pre-PEP is rejected, the author may elect to take the pre-PEP to the comp.lang.python newsgroup (a.k.a. python-list at python.org mailing list) to help flesh it out, gain feedback and consensus from the community at large, and improve the PEP for re-submission. The author of the PEP is then responsible for posting the PEP to the community forums, and marshaling community support for it. As updates are necessary, the PEP author can check in new versions if they have CVS commit permissions, or can email new PEP versions to the PEP editor for committing. Standards track PEPs consists of two parts, a design document and a reference implementation. The PEP should be reviewed and accepted before a reference implementation is begun, unless a reference implementation will aid people in studying the PEP. Standards Track PEPs must include an implementation - in the form of code, patch, or URL to same - before it can be considered Final. PEP authors are responsible for collecting community feedback on a PEP before submitting it for review. A PEP that has not been discussed on python-list at python.org and/or python-dev at python.org will not be accepted. However, wherever possible, long open-ended discussions on public mailing lists should be avoided. Strategies to keep the discussions efficient include, setting up a separate SIG mailing list for the topic, having the PEP author accept private comments in the early design phases, etc. PEP authors should use their discretion here. Once the authors have completed a PEP, they must inform the PEP editor that it is ready for review. PEPs are reviewed by the BDFL and his chosen consultants, who may accept or reject a PEP or send it back to the author(s) for revision. Once a PEP has been accepted, the reference implementation must be completed. When the reference implementation is complete and accepted by the BDFL, the status will be changed to `Final.' A PEP can also be assigned status `Deferred.' The PEP author or editor can assign the PEP this status when no progress is being made on the PEP. Once a PEP is deferred, the PEP editor can re-assign it to draft status. A PEP can also be `Rejected'. Perhaps after all is said and done it was not a good idea. It is still important to have a record of this fact. PEPs can also be replaced by a different PEP, rendering the original obsolete. This is intended for Informational PEPs, where version 2 of an API can replace version 1. PEP work flow is as follows: Draft -> Accepted -> Final -> Replaced ^ +----> Rejected v Deferred Some informational PEPs may also have a status of `Active' if they are never meant to be completed. E.g. PEP 1. What belongs in a successful PEP? Each PEP should have the following parts: 1. Preamble -- RFC822 style headers containing meta-data about the PEP, including the PEP number, a short descriptive title (limited to a maximum of 44 characters), the names, and optionally the contact info for each author, etc. 2. Abstract -- a short (~200 word) description of the technical issue being addressed. 3. Copyright/public domain -- Each PEP must either be explicitly labelled as placed in the public domain (see this PEP as an example) or licensed under the Open Publication License[4]. 4. Specification -- The technical specification should describe the syntax and semantics of any new language feature. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Python platforms (CPython, JPython, Python .NET). 5. Motivation -- The motivation is critical for PEPs that want to change the Python language. It should clearly explain why the existing language specification is inadequate to address the problem that the PEP solves. PEP submissions without sufficient motivation may be rejected outright. 6. Rationale -- The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages. The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion. 7. Backwards Compatibility -- All PEPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The PEP must explain how the author proposes to deal with these incompatibilities. PEP submissions without a sufficient backwards compatibility treatise may be rejected outright. 8. Reference Implementation -- The reference implementation must be completed before any PEP is given status 'Final,' but it need not be completed before the PEP is accepted. It is better to finish the specification and rationale first and reach consensus on it before writing code. The final implementation must include test code and documentation appropriate for either the Python language reference or the standard library reference. PEP Template PEPs are written in plain ASCII text, and should adhere to a rigid style. There is a Python script that parses this style and converts the plain text PEP to HTML for viewing on the web[5]. PEP 9 contains a boilerplate[7] template you can use to get started writing your PEP. Each PEP must begin with an RFC822 style header preamble. The headers must appear in the following order. Headers marked with `*' are optional and are described below. All other headers are required. PEP: Title: Version: Last-Modified: Author: * Discussions-To: Status: Type: * Requires: Created: * Python-Version: Post-History: * Replaces: * Replaced-By: The Author: header lists the names and optionally, the email addresses of all the authors/owners of the PEP. The format of the author entry should be address at dom.ain (Random J. User) if the email address is included, and just Random J. User if the address is not given. If there are multiple authors, each should be on a separate line following RFC 822 continuation line conventions. Note that personal email addresses in PEPs will be obscured as a defense against spam harvesters. Standards track PEPs must have a Python-Version: header which indicates the version of Python that the feature will be released with. Informational PEPs do not need a Python-Version: header. While a PEP is in private discussions (usually during the initial Draft phase), a Discussions-To: header will indicate the mailing list or URL where the PEP is being discussed. No Discussions-To: header is necessary if the PEP is being discussed privately with the author, or on the python-list or python-dev email mailing lists. Note that email addresses in the Discussions-To: header will not be obscured. Created: records the date that the PEP was assigned a number, while Post-History: is used to record the dates of when new versions of the PEP are posted to python-list and/or python-dev. Both headers should be in dd-mmm-yyyy format, e.g. 14-Aug-2001. PEPs may have a Requires: header, indicating the PEP numbers that this PEP depends on. PEPs may also have a Replaced-By: header indicating that a PEP has been rendered obsolete by a later document; the value is the number of the PEP that replaces the current document. The newer PEP must have a Replaces: header containing the number of the PEP that it rendered obsolete. PEP Formatting Requirements PEP headings must begin in column zero and the initial letter of each word must be capitalized as in book titles. Acronyms should be in all capitals. The body of each section must be indented 4 spaces. Code samples inside body sections should be indented a further 4 spaces, and other indentation can be used as required to make the text readable. You must use two blank lines between the last line of a section's body and the next section heading. You must adhere to the Emacs convention of adding two spaces at the end of every sentence. You should fill your paragraphs to column 70, but under no circumstances should your lines extend past column 79. If your code samples spill over column 79, you should rewrite them. Tab characters must never appear in the document at all. A PEP should include the standard Emacs stanza included by example at the bottom of this PEP. A PEP must contain a Copyright section, and it is strongly recommended to put the PEP in the public domain. When referencing an external web page in the body of a PEP, you should include the title of the page in the text, with a footnote reference to the URL. Do not include the URL in the body text of the PEP. E.g. Refer to the Python Language web site [1] for more details. ... [1] http://www.python.org When referring to another PEP, include the PEP number in the body text, such as "PEP 1". The title may optionally appear. Add a footnote reference that includes the PEP's title and author. It may optionally include the explicit URL on a separate line, but only in the References section. Note that the pep2html.py script will calculate URLs automatically, e.g.: ... Refer to PEP 1 [7] for more information about PEP style ... References [7] PEP 1, PEP Purpose and Guidelines, Warsaw, Hylton http://www.python.org/peps/pep-0001.html If you decide to provide an explicit URL for a PEP, please use this as the URL template: http://www.python.org/peps/pep-xxxx.html PEP numbers in URLs must be padded with zeros from the left, so as to be exactly 4 characters wide, however PEP numbers in text are never padded. Reporting PEP Bugs, or Submitting PEP Updates How you report a bug, or submit a PEP update depends on several factors, such as the maturity of the PEP, the preferences of the PEP author, and the nature of your comments. For the early draft stages of the PEP, it's probably best to send your comments and changes directly to the PEP author. For more mature, or finished PEPs you may want to submit corrections to the SourceForge bug manager[6] or better yet, the SourceForge patch manager[2] so that your changes don't get lost. If the PEP author is a SF developer, assign the bug/patch to him, otherwise assign it to the PEP editor. When in doubt about where to send your changes, please check first with the PEP author and/or PEP editor. PEP authors who are also SF committers, can update the PEPs themselves by using "cvs commit" to commit their changes. Remember to also push the formatted PEP text out to the web by doing the following: % python pep2html.py -i NUM where NUM is the number of the PEP you want to push out. See % python pep2html.py --help for details. Transferring PEP Ownership It occasionally becomes necessary to transfer ownership of PEPs to a new champion. In general, we'd like to retain the original author as a co-author of the transferred PEP, but that's really up to the original author. A good reason to transfer ownership is because the original author no longer has the time or interest in updating it or following through with the PEP process, or has fallen off the face of the 'net (i.e. is unreachable or not responding to email). A bad reason to transfer ownership is because you don't agree with the direction of the PEP. We try to build consensus around a PEP, but if that's not possible, you can always submit a competing PEP. If you are interested assuming ownership of a PEP, send a message asking to take over, addressed to both the original author and the PEP editor . If the original author doesn't respond to email in a timely manner, the PEP editor will make a unilateral decision (it's not like such decisions can be reversed. :). References and Footnotes [1] This historical record is available by the normal CVS commands for retrieving older revisions. For those without direct access to the CVS tree, you can browse the current and past PEP revisions via the SourceForge web site at http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/python/nondist/peps/?cvsroot=python [2] http://sourceforge.net/tracker/?group_id=5470&atid=305470 [3] http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse [4] http://www.opencontent.org/openpub/ [5] The script referred to here is pep2html.py, which lives in the same directory in the CVS tree as the PEPs themselves. Try "pep2html.py --help" for details. The URL for viewing PEPs on the web is http://www.python.org/peps/ [6] http://sourceforge.net/tracker/?group_id=5470&atid=305470 [7] PEP 9, Sample PEP Template http://www.python.org/peps/pep-0009.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From gerhard.haering at gmx.de Sun Jul 14 10:28:20 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 14 Jul 2002 16:28:20 +0200 Subject: Making code 2.1 compatible In-Reply-To: <3D2EF1F3.4B18FAEB@tds.net> References: <3D2EED98.BD59D615@tds.net> <3D2EF1F3.4B18FAEB@tds.net> Message-ID: <20020714142820.GA1176@lilith.my-fqdn.de> * Edward K. Ream [2002-07-12 15:12 +0000]: > >Is there a way to ask Python not to allow 2.2 constructs? > >Having Python complain when producing .pyc files would be good enough. > > Perhaps I should add, using Python 2.2 itself. One way would be to > install Python 2.1, but I'd rather not do that :-) But testing with a Python 2.1 installed alongside the Python 2.2 is the only sensible way if you're trying to stay Python 2.1 compatible. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 19.5 ?C Wind: 1.7 m/s From imbosol at vt.edu Mon Jul 15 18:41:11 2002 From: imbosol at vt.edu (Carl Banks) Date: Mon, 15 Jul 2002 18:41:11 -0400 Subject: Python's Lisp heritage References: Message-ID: <72jvga.eb.ln@grey.aerojockey.localdomain> Christopher Browne wrote: > From a paper on Emacs: Incidentally, I'd like a reference to this paper. I hope it's not something that appeared in a scholarly journal, because it's flatly wrong. (I think it more likely to be someone at Perl conference in 1992 trying to justify the local statement. :) -- CARL BANKS http://www.aerojockey.com From shalehperry at attbi.com Wed Jul 3 10:56:37 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 03 Jul 2002 07:56:37 -0700 (PDT) Subject: Patterns and all that new fangled stuff ... In-Reply-To: <3D22EC27.4040805@mxm.dk> Message-ID: On 03-Jul-2002 Max M wrote: > For the fun and education of it I have recently tried to refactor one of > my projects using patterns. > > I did expect the code to be longer and more verbose, but was a little > surprised when I found out that it got exactly twice as long ... > > But I know the code too well and cannot be objective about it, so I > thought I would like to get a second opinion. Which code would you guys > prefer to maintain down the line. The short "linear" version or the > object oriented "pattern" version. Which one is the easiest to read? > > It as an .asp project. I have chosen not to include the html part of it > as it just inserts html generated from the Python code. > if your new facade class is only used once, in one place there is little benefit. However if this type of thing occurs in several places you have no limited your changes to one class rather than every call. A programmer must learn when to use a tool. Just because you have a toolbox brimming with solutions does not mean you should use all of them on a single project. From johnroth at ameritech.net Tue Jul 30 19:18:42 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 30 Jul 2002 19:18:42 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> <3d46c6a2$1_1@hpb10302.boi.hp.com> Message-ID: "Daniel Fackrell" wrote in message news:3d46c6a2$1_1 at hpb10302.boi.hp.com... > "John Roth" wrote in message > news:ukddqtelmp6eda at news.supernews.com... > > > > "Daniel Fackrell" wrote in > > message news:3d46964b$1_2 at hpb10302.boi.hp.com... > > > "John Roth" wrote in message > > > news:ukb31ell2rh643 at news.supernews.com... > > > > > > > > > > > > > for word in 'fee fie fo fum'.split(): > > > > Button(frame, command = def (): > > > > print word > > > > ) > > > > > > > > This isn't really the world's best example, because IMO, the > > > > lambda form is easier to read for something this small. However, > > > > it does give the guts of the idea: > > > > > > > > > > > > > 2. The remainder of the syntax exactly models def, including > > > > statement indentation within the expression. Notice that the > > > > first statement in the anonamous function has to be indented > > > > two from the preceeding line, because the continuation of > > > > the expression has to still be indented from the line with the > > > > 'def', and dedented from the statements. > > > > > > IIRC, there's no such ting as "indenting two" in Python as the size of > > an > > > indentation is automatically detected as you go along, making the > > following > > > indentation style valid (although no one would ever want to do it): > > > > > > toplevel > > > secondlevel > > > thirdlevel > > > secondlevel > > > thirdlevel > > > fourthlevel > > > secondlevel > > > toplevel > > > > The reason I say "indenting 2" is that you need two > > dedents to make it work: one to close the def, which does > > not have it's own indent, and one to finish off the expression > > in which the def is imbedded. > > > > Does this make it clearer? > > > > John Roth > > Again, the problem is that Python must assume that when it sees code > indented further than the previous line, a single indent is intended. It > has no way of knowing how many indents you mean unless something is actually > indented to each level along the way. This is quite true, however what I meant to convey (and don't seem to have done a very good job of it) is that since you need two dedents to close the figure (one to end the def (or class) and one to end the enclosing expression) for symetry you need two indents. The compiler, in fact, wouldn't (and shouldn't) be able to tell the difference, but I presume that syntax aware editors might be able to. I said two indents not because of compiler concerns, but because of syntax aware editor concerns. > In addition to that, indentation is currently ignored inside (), {}, [], > strings, and on lines following an escaped newline. Some of that could > change, perhaps, but it seems to me that it might break existing code. I don't see how it would break anything. The presence of 'def' or 'class' would cause a shift into 'statement' mode. Those two reserved words are not currently allowed within statements, only at the statement level. > I do see merit in this discussion, though, because I see class and def > statements as really being a shorthand for doing two things at once, namely > creating a function and then binding it to a name. That's exactly the point. > Admittedly, there are probably cases where the second part does not apply > all that well. Perhaps a case where you want a list or dict of functions > would be one such case. Binding to the name simply adds a step along the > way. Passing a callable object as a parameter to another callable object > would probably be another such case. Well, that's what's significant about anonymous functions. The inline definition results in the function object, which then has to be consumed by something that takes a function object and uses it. The statement version binds the function or class object to a name as part of it's execution. > The issue quickly becomes readability, though. Would you want to be able to > do a complex multi-line def or class statement inside an assignment creating > a list, for example? And how would you do that without indentation? I suppose you could. Again, if the list is supposed to contain references to function objects, I don't see why not. > > funcList = [ Insert idea here ] # notice that the indentation isn't very obvious - problems with OE funcList = [ def (a, b): print a # indented 20 spaces print b # indented 20 spaces , def (a, b): # indented 16 spaces globalA = a # indented 20 spaces globalB = b # indented 20 spaces ] # indented 12 spaces Does this make sense? > > lambda in its current form does okay in cases like this. As an expression > it does not require indentation for anything, but it is also not allowed to > execute statements. Well, yes. And lambda generally does quite well for short functions. The idea that inline functions should be short has a great number of adherents. John Roth > > -- > Daniel Fackrell (unlearned at learn2think.org) > When we attempt the impossible, we can experience true growth. > > From tim at zope.com Tue Jul 2 16:46:44 2002 From: tim at zope.com (Tim Peters) Date: Tue, 2 Jul 2002 16:46:44 -0400 Subject: python decimal infection? In-Reply-To: Message-ID: [Thinkit] > How much has the cancer known as decimal infected python? > Decimal is evil. Indeed, Python uses base-3 arithmetic exclusively, in honor of the Holy Trinity. no-evil-here-ly y'rs - tim From skip at pobox.com Fri Jul 26 17:48:24 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Jul 2002 16:48:24 -0500 Subject: ?Module re documentation bug, error, or misunderstanding? In-Reply-To: <3D41BF1B.905CA623@email.sps.mot.com> References: <3D41B265.AD56FF90@email.sps.mot.com> <15681.47874.446657.686812@12-248-11-90.client.attbi.com> <3D41BF1B.905CA623@email.sps.mot.com> Message-ID: <15681.50088.994371.777110@12-248-11-90.client.attbi.com> Norman> This solution leads to another question, probably a Norman> documentation issue. I do not need "r" or double backslashes Norman> when I use \d, \s, \S, ... all the special sequences that Norman> \number is included with in the documentation. What indication Norman> is there in the documentation that \number must be handled Norman> differently than say, \d ? You're fighting two battles at once when you don't use raw strings. Python's lexical analyzer recognizes a wide array of escape sequences. For example, "\t" is a one-character string containing an ASCII TAB character, not a two-character string containing a backslash followed by a "t". Since lexical analysis is complete before the regular expression compiler sees the strings, many escape sequences will have disappeared by that stage of the game. Using raw strings ("r" prefix) tells the lexical analyzer to not interpret escape sequences in that string. Thus r"\t" is a two-character sequence consisting of a backslash followed by a "t". Raw strings were created specifically to avoid this conflict between the lexical analyzer and the regular expression compiler. You can think of it as the usually boorish lexical analyzer showing some manners by not eating all the shrimp at the buffet. ;-) For a discussion of string literals, check this section of the language reference manual: http://www.python.org/doc/current/ref/strings.html For a discussion of regular expression syntax, check this section of the library manual: http://www.python.org/doc/current/lib/re-syntax.html I'm sure there are other documentation bits that may help as well, but these two pages list the escape sequences the two parts of the system understand. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From ods at fep.ru Tue Jul 23 08:06:59 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Tue, 23 Jul 2002 16:06:59 +0400 (MSD) Subject: format strings or page tempaltes In-Reply-To: Message-ID: On Tue, 23 Jul 2002, Jeff Davis wrote: JD> I am trying to make use of an organized templating system JD> for web JD> development. I really just need something simple, so I was JD> considering JD> using format strings (just doing "open('mytemplate').read() JD> % mydict"). JD> The only thing that seems to be lacking for me is the JD> ability to call a JD> function with arguments from the template file. For example, JD> here's what JD> I'd like to be able to do: JD> JD> JD> .... JD> %(myfunction("foo"))s JD> ..... JD> import sys class EvalDict: def __init__(self, globals=None, locals=None): if globals is None: globals = sys._getframe(1).f_globals self.globals = globals if locals is None: locals = sys._getframe(1).f_locals self.locals = locals def __getitem__(self, key): key = key % self return eval(key, self.globals, self.locals) >>> def myFunc(arg): ... return '!%s!' % arg ... >>> print 'Template with %(myFunc("My argument"))s call' % EvalDict() Template with !My argument! call -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From op73418 at mail.telepac.pt Sat Jul 20 10:12:00 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sat, 20 Jul 2002 15:12:00 +0100 Subject: Using pointers References: <4210d7a2.0207200538.44a91c0f@posting.google.com> Message-ID: On 20 Jul 2002 06:38:49 -0700, jkrahn at nc.rr.com (Joe Krahn) wrote: >Can I make a pointer to an object in Python? I know that all >objects/variables are references, but not in the same sense as in C. >How do I get multiple pointers to reference and modify one variable? There are no explicit pointers/references in Python and dereferencing is automatic. But why do you need pinters? If you tell us why maybe we can be a little more helpful. With my best regards, Gon?alo Rodrigues From lhudson at geminidataloggers.com Mon Jul 8 12:27:59 2002 From: lhudson at geminidataloggers.com (Lawrence Hudson) Date: Mon, 08 Jul 2002 17:27:59 +0100 Subject: freeze path problem (on nt) References: <9a6d7d9d.0207080658.3d8181d8@posting.google.com> Message-ID: <3D29BD8F.3060207@geminidataloggers.com> Hi Aaron, Which version of Python are you using? Lots of import-at-runtime-from-frozen-binary problems were fixed in Python 221 and I think that this is one of them. 221 added a couple of options to freeze; from the docstring: -X module Like -x, except the module can never be imported by the frozen binary. -E: Freeze will fail if any modules can't be found (that were not excluded using -x or -X). I believe that if -E is not specified then the default behaviour is unchanged, ie: modules which can not be found by freeze will not be included in the frozen program and the normal sys.path import mechanism will be used at runtime. Turning on -E will require you to add -X for a few modules that the standard library will try to import but may not be available on your machine, eg TERMIOS, java.lang, Tkinter etc). We always use the -E switch to be confident of avoiding weird import problems at runtime. If you are using an earlier version then it would be worth trying 221. If you still have problems then try setting the PYTHONVERBOSE environment variable before running the frozen program to see exactly what is being imported from where. Is rlextra a reportlab module? I don't have reportlab but it is possible that it performs some sys.path tricks in which case freezing will be tricky. Hope this helps! Thanks, Lawrence Aaron Watters wrote: > Hi guys. I have the following problem. > > I use tools/freeze to build a frozen exe (X.exe) for windows using vc++ 6. > > If I run it on a machine without a python installation it runs fine. > But if I run it on a machine with python and a package called > > rlextra.rml2pdf > > then the import > > from rlextra.rml2pdf import rml2pdf > > imports the python module from the file system in preference to the > frozen pyc that is compiled into X.exe. This is a problem, of course > if the version of rml2pdf on the file system differs from the one in X.exe. > > It must have something to do with sys.path and/or those goofy *.pth files > right? > > Anyway, how do I prevent X.exe from trying to import stuff from the > file system first before looking internally... anybody got a clue? > > thx in advance > > =- Aaron Watters > > === > JUVENILE COURT TO TRY SHOOTING SUSPECT > -- from "real headlines" (that should work...) From stever at gate.net Mon Jul 1 01:02:19 2002 From: stever at gate.net (Steve Reeves) Date: 1 Jul 2002 05:02:19 GMT Subject: telnetlib option negotiation callback should be a method In-Reply-To: References: Message-ID: I wrote: > I have an application using telnet that requires option subnegotiation > (specifically, it needs to set a terminal type in the manner of RFC > 1091). The standard telnetlib doesn't currently support this. I > would like to extend it to do so, but the current design of the option > negotiation callback makes this difficult. > > Currently, the callback is a function taking a socket as an argument. > This is adequate for sending data to the server, but not for > receiving. It bypasses the Telnet object's internal queue, which may > already contain the data you're waiting for. It also requires you to > reimplement the special processing the protocol requires (undoubling > IAC characters), and the default negotiation behavior. > > The callback really needs to be a method of the Telnet object, with > access to the internal queue. It can implement the default DONT/WONT > negotiation. Subclasses can override it to handle the specific > options they want and forward the rest to the base class. The > set_option_negotiation_callback() method would no longer be needed. > > (This question of function vs. method was briefly raised when the > telnetlib patch was first submitted, , > but it was left as a function.) > > Opinions? Ok, I figured out that if you read the suboption parameter data in the Telnet object's process_rawq method and pass it to the callback function, you don't necessarily need the callback to be a Telnet method. However, it still seems more Pythonic to me to subclass Telnet than to call set_option_negotiation_callback. Is anybody out there using the callback as it is currently implemented? Would anyone care if it were changed to a method? -- Steve Reeves stever at gate.net From jepler at unpythonic.net Wed Jul 31 10:58:49 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 31 Jul 2002 09:58:49 -0500 Subject: global interpreter lock not working as it should In-Reply-To: <200207311359.JAA15020@test-area.com> References: <200207302247.SAA21093@test-area.com> <20020730202014.A3224@unpythonic.net> <200207311359.JAA15020@test-area.com> Message-ID: <20020731145848.GC1800@unpythonic.net> On Wed, Jul 31, 2002 at 10:00:41AM -0400, anton wilson wrote: > On Tuesday 30 July 2002 09:20 pm, jepler at unpythonic.net wrote: > > > On Tuesday 30 July 2002 07:18 pm, brueckd at tbye.com wrote: > > > > Quick tangential question: if there's no blocking of any kind, why are > > > > you using threads, anyway? Off the cuff thinking says this seems like a > > > > misuse of them. > > > > On Tue, Jul 30, 2002 at 06:48:40PM -0400, anton wilson wrote: > > > For a real-time system. ;) It will work. It would just be nice if they > > > switched exactly every 10 byte codes becuase that means they only use > > > about 10 to 20 milliseconds each. > > > > Realtime? Really? So can you tell me the upper-bound on the runtime > > of > > > > >>> x = 3 > > > > on the hardware you're targeting? > > > > Jeff > > > Good question. You have any reasons why we should not use python? It's a trick question. >>> x = 3 will do a decref on the old value of x, if it had one. This could invoke the __del__ of an arbitrary object, which could call any C function. Or, deallocating x could make the reference count of arbitrarily many objects fall to 0, for instance if the old value of x was >>> x = [uniqueobject() for x in range(1000 * 1000)] then ultimately around 1 million objects would be deallocated as a result of a single statement. (these deallocations are done with the GIL held, yet the bytecode loop will not be entered unless uniqueobject has a __del__ method written in Python) I won't even mention garbage collection or other worse issues. A realtime system places an upper bound on all operations, but the very nature of Python makes this impractical if not impossible. An interaction between Python's handling of the GIL and the platform's pthread library is going to be the least of your problems if you actually intend to deliver a system which gives realtime guarantees on Python programs. Jeff From StRanGy at dijana.vest.hr Mon Jul 8 05:13:17 2002 From: StRanGy at dijana.vest.hr (Ivica) Date: 8 Jul 2002 09:13:17 GMT Subject: Pyrex Message-ID: Can any one send me a copy of pyrexc.py for windows because the pyrexc that ships with pyrex does not work on windows, and I'm a newbie to pyrex and python. -- --------------------------------- # RealName: Ivica Munitic # E-Mail: imunitic at vest.hr --------------------------------- From ykingma at accessforall.nl Tue Jul 2 16:04:35 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Tue, 02 Jul 2002 21:04:35 +0100 Subject: python threads and the linuxthread pthread library References: <3D210EFB.51E375EA@earthlink.net> Message-ID: <3D220748.34FAC7F9@accessforall.nl> Joseph A Knapka wrote: > > Tim Peters wrote: > > > > [anton wilson] > > > ... > > > Is the Python Virtual Machine it's own thread? > > > > No. All threads run in the PVM, but the GIL serializes their PVM time. > > Does Jython lift this limitation, by any chance? Or is > the GIL a universal and unchangable Python artifact? Jython does not have this limitation. Jython threads are Java threads. Some basic types of the jython interpreter are java-synchronized, eg. the dictionary type used for namespaces and threading.Lock. For synchronisation you can use the standard python things, and also others, eg util.concurrent by Doug Lea. Finally, it's easy to manipulate the java thread priority from jython. Have fun, Ype From gcordova at hebmex.com Mon Jul 8 11:56:23 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 8 Jul 2002 10:56:23 -0500 Subject: Python 2.1 == Jython 2.1 != Python 2.2? Message-ID: > > > If so, is there an ETA on Jython 2.2? > > What is an ETA? > > Regards, > Martin > ETA == "Environmental Turnover Announcement" Typo prolly. ;-) -gus From jdavis at empires.org Thu Jul 25 01:53:05 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 25 Jul 2002 05:53:05 GMT Subject: random 64-bit int Message-ID: <5nM%8.30598$4T2.8891354@twister.socal.rr.com> I need to get a random 64-bit integer (positve or negative). Here is my current algorithm: -------- from struct import pack,unpack from random import randint max = 2**16-1 r12 = pack('H',randint(0,max)) r34 = pack('H',randint(0,max)) r56 = pack('H',randint(0,max)) r78 = pack('H',randint(0,max)) unpack('q',r12+r34+r56+r78)[0] --------- It seems like the above works, but I'd like to know whether I am losing randomness, or whether there is a more efficient or faster way to accomplish that. Would it be a good idea to include a call to random.seed()? Also, it would be *really* nice if there was a good way to do that in python2.1, which does not seem to allow the "q" type for unpack(). Thanks, Jeff From maxm at mxm.dk Wed Jul 24 08:21:35 2002 From: maxm at mxm.dk (Max M) Date: Wed, 24 Jul 2002 14:21:35 +0200 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: <3D3E9BCF.90806@mxm.dk> Alex Martelli wrote: > A respectable opinion. Mine is just the reverse -- were it not > for backwards compatibility, I wouldn't mind losing __call__ in > instances. A bound method can do it, and we could have a > _convention_ about how a "primary" method (if any) should be > named, just as we have for the 'self' argument. It's all > theoretical anyway, __call__'s never going to go away in fact. I believe you mean something like: class WithPrimary: def WithPrimary_primary(self): # primary method due to naming conventions pass Why is this better than having an explicit __call__ method? Is it because of a dislike of the "__*__" methods in general? I must admit that I rarely use the __call__ method, but I have found it very convenient in some cases. The funny thing though is that I have found it most usefull when I need to set up a function in somehing like map(), sort(), filter() etc. where I need additional data passed to the visitor function, which these functions does not allow. So a "shortcomming" in Python is worked around by a strength, if you can say it like that. regards Max M From woodsplitter at rocketmail.com Mon Jul 22 15:38:48 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: 22 Jul 2002 12:38:48 -0700 Subject: Python to Excell References: <3d3bb483.250106359@news.skynet.be> Message-ID: <7876a8ea.0207221138.66a3a5b@posting.google.com> pixie888 at hotmail.com wrote > ... > I do not know the interface which is exposed by Excell. Can anybody help me > further on this one? Here's a post that I made some time ago on this subject: http://groups.google.com/groups?selm=7876a8ea.0112061746.145c1e76%40posting.google.com&output=gplain **Pay special attention to the URLs listed in that post; they link to documentation of Excel's exposed object model.** > ...writing a script which updates an Excell sheet... The linked post explicitly demonstrates how to update an Excel worksheet on a range-by-range (which could mean cell-by-cell) basis. > ...and which prints it out then... To print a WorkBook, use the PrintOut() method. --- Also, Stefan's suggestion that you "use the macro recorder of excel and translate it to python code" is good advice. Perhaps you don't know this, but you can record a macro that does a small part of your ultimate task, then look at the Visual Basic for Applications code that the macro recorder generated and model your hand-written code on it. That's the easiest way to learn the Excel object model incrementally, though you should definitely still use the MSDN documentation. From gerhard at bigfoot.de Sat Jul 13 20:53:07 2002 From: gerhard at bigfoot.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Sun, 14 Jul 2002 02:53:07 +0200 Subject: Pros/cons of various PostGres modules In-Reply-To: <545cb8c2.0207130852.74d88a5@posting.google.com> References: <545cb8c2.0207130852.74d88a5@posting.google.com> Message-ID: <20020714005307.GA4849@gargamel.hqd-internal> * Jim Hefferon [2002-07-13 09:52 -0700]: > Hello, > > I'm starting on a project that will have Python interfacing with > PostGres. I see that there are now four modules listed on the Python web > site. I'd be very interested in any suggestions as to which ones are > best. > > I've used PyPgSQL with good luck in the recent past. But there are two > that are newer Newer? AFAIK pyPgSQL and psycopg are the youngest projects of the four DB-API adapters (pyPgSQL, psycopg, PoPy, PyGreSQL). And the latest pyPgSQL release was on 2002-06-04, so I don't quite understand what you mean here :) > that are thread safe. pyPgSQL has a threadsafety of 1, which means you can't safely share connections among threads, but you can use the module in a multithreaded application. I'd never do otherwise, anyway. psycopg, however, is /designed/ for heavily multithreaded apps, and has threadsafety=2 (can share connections among threads), IIRC. > Will I notice on a moderately-loaded application? In my experience, the only solution to get a sensible answer is to fire use the time, hotshot or profile profile modules yourself to find out. > Are they debugged? AFAIK pyPgSQL and psycopg are both relatively bugfree and well maintained. I can't speak for PoPy, except that they haven't got around to republish at their new website for over a year now. PyGreSQL is IMO very badly maintained: there was a serious bug with cursor.fetchone() always returning the first row of the resultset, which made cursors basically unusable. It was known for over a year until somebody (me) got annoyed enough to take the half-an hour to look into the Python and C code, write a patch and submit it to the PostgreSQL developers. > Is one faster than the others? psycopg is faster than pyPgSQL in my benchmarks. The bottlenecks in my apps, however, were never the overhead of the database interface. I'd suggest to profile the usage of the modules you consider in a real app. You can use code like this to do so: from pyPgSQL import PgSQL as mydbmodule #import psycopg as mydbmodule conn = mydbmodule.connect("") # ... > Any other experiences? They all look good to me! As one of the pyPgSQL developers, I'm not unbiased, but I'd stay with pyPgSQL and only consider psycopg as an alternative :-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From nospam at bigfoot.com Tue Jul 2 08:29:05 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 2 Jul 2002 14:29:05 +0200 Subject: python + simple graphics (lines, circles etc.) References: Message-ID: You did'nt mention what's the graphics backend. GIF/Jpeg file, PDF file, on screen (whith what GUI toolkit)... There are tons of solutions... --Gilles glenfant AT bigfoot DOT com "Andreas Daskalopoulos" a ?crit dans le message news: m37kkfpjsc.fsf at linux.local... > > What modules are avalaible for drawing simple things like lines, > circles etc.? I searched the documentation for a module but i didnt > find something. > > Thank you for reading my article. From chrisc894 at hotmail.com Mon Jul 29 21:17:18 2002 From: chrisc894 at hotmail.com (Chris) Date: Tue, 30 Jul 2002 01:17:18 GMT Subject: Instant Messenger Message-ID: OK, first of all I've done this so far: Set up a username registraion page and linked it to a MySQL database running on my computer. Everything there works well. What I'm having trouble with: Mostly (well, alright, completely) the design of how to implement it. What I want to do: I want to run the "server" on my computer that will accept connections, validate the username and password sent by the "client" by checking for them in the MySQL database. Alright, simple enough. Questions: Once the server has validated the username and password, I want to store the socket that I used to recv() the username and password so that I can send messages to it later (i.e. when another user logs on). Also, I want to be able to keep a list of all the users logged in, which I guess is one in the same with the last sentence. Is any of this possible without threading? My biggest problem is storing the sockets that recv() the username and password, for now. If anyone has any resources for me, would you please send me the links, or if you have any ideas or suggestions, could you please post them. Any help is appreciated. thanks, chris Post-Script: I do have network programming experience (i.e. sockets, et cetera). From tim.one at comcast.net Mon Jul 8 16:18:16 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 08 Jul 2002 16:18:16 -0400 Subject: subclassing int and accessing the value In-Reply-To: <200207081936.g68JaSe25466@localhost.localdomain> Message-ID: [Dave Reed] > Let's say I want to subclass int to write my own class for handling > monetary values (i.e., represent them in cents, but print them in > dollars and cents, but otherwise allow normal addition, subtraction of > ints to work). For example, store 150, but print $1.50. > ... > The following works so it appears to be possible. > > class myint(int): > def __init__(self, v): > int.__init__(self, ) > > i = myint(5) > print i # prints 5 Because ints are immutable, it's too late to affect what's stored in them by the time __init__ is called (the "int part" of the memory has already been initialized by the time __init__ is called, and can't be changed). So the __init__ method there has no effect. This works just as well as the above: class myint(int): pass If you do want to affect what's stored in "the int part", you need to use the __new__ method instead. > Now my question is, how do I access the actual value 5 internally so I > can write my own __repr__ method that returns '$0.05'. I'm guessing it's > using __getattribute__, but what attribute do I want to access? It's simpler than that: use self! For example, """ class myint(int): def __str__(self): return "$%.2f" % (self / 1e2) print myint(513) """ prints $5.13. > I haven't found any examples for subclassing numeric types, only > dicts and lists at > http://www.python.org/2.2.1/descrintro.html#subclassing. The standard test Lib/test/test_descr.py has many examples of obscure things. Its inherits() function tests examples of subclassing from, e.g., long and complex. Note that subclassing of builtin types is intended to be used to add new behaviors and/or attributes; trying to override standard behaviors is something of a crapshoot. From pinard at iro.umontreal.ca Thu Jul 18 07:11:40 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 18 Jul 2002 07:11:40 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: [James Kew] > Should I feel guilty for not learning lex/yacc? No. These are for C programmers, and you should not have to program C to be happy! However, if you live in a Python world, it is not bad that you put a similar Pytonish tool in your pocket, one of these days! > Or should I rejoice in my batteries-included (or at least, > batteries-downloaded-from-SourceForge) pragmatism? If you feel comfortable and happy with XML, then XML is quite OK. As long as you resist turning into an XML frantic fanatic, you know, those recognisable by the foam at the mouth, you're safe! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From gerhard.haering at gmx.de Wed Jul 3 10:15:50 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 3 Jul 2002 14:15:50 GMT Subject: Forward Declaring Py_complex References: Message-ID: In article , Mark Charsley wrote: > Is there any way to forward declare Py_complex in C++ headers? #include "complexobject.h" should do the trick. > I'm trying to create a C++ function that returns a Py_complex, and would > really prefer not to have to pull in all of Python.h in the header file. Any reason why? I can't think of any good reason. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From claird at starbase.neosoft.com Mon Jul 15 08:37:52 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 15 Jul 2002 07:37:52 -0500 Subject: SNMP module in python References: <3d329ac0.330042218@news.skynet.be> Message-ID: In article <3d329ac0.330042218 at news.skynet.be>, wrote: >Hi, > >I am looking for a module written in Python to perform SNMP >communication. Can anyone tell me where I can find one? . . . By way of . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From tjreedy at udel.edu Thu Jul 4 10:30:16 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Jul 2002 14:30:16 GMT Subject: Meta Line information in Python? References: Message-ID: "Tan Woon Kiong" wrote in message news:f735e100.0207040009.62d21938 at posting.google.com... > Hi, > > Is there a way to specify meta line information in Python? > > For instance, in C language, this can be done by writing the statement > #line "" There are internal __file__ and __lineno__ (spelling?) vars which are used to print tracebacks. I do not know if they are writable from Python (as opposed to C code compiled into the interpreter). You might investigate Terry J. Reedy From jbreen at nospam.com Wed Jul 31 18:43:21 2002 From: jbreen at nospam.com (John J Breen) Date: Wed, 31 Jul 2002 18:43:21 -0400 Subject: Python and Sockets, Message-ID: <3D486809.6F2DC882@nospam.com> Hey all, I am writing a program in Pygtk that also has a Python/TK component. I need these two components to be able to communicate with one another through a third component written in python. I would like to use sockets to send information back and forth, but am running into some trouble. The components may be sending information at any time so I need to the sockets to be able to listen/send at any time. I cant have a loop for listening because that would keep the user from sending events to either the gtk or TK interface. Someone suggested _createfilehandler but Im not sure what that is... Does anyone have any suggestions for such a problem? J From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 23:27:45 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 23:27:45 -0400 Subject: python threads and the linuxthread pthread library References: <3D210EFB.51E375EA@earthlink.net> Message-ID: <3D211DB1.70309@removethisandallhyphens-o-n-e.net> > > Does Jython lift this limitation, by any chance? Or is > the GIL a universal and unchangable Python artifact? I don't know about jython, but _nothing_ is unchangeable (well, almost nothing) - the GIL is whats used right now... Theres no reason to believe that a non-GIL solution couldn't be found if people put thier minds to it - it would be *hard*, and might break compatability (ACK!), but it is possible. How about a read-lock on global data? - all threads could maintain thier own locals-state, and just lock on trying to read/write a global... of course, first, all code in the current implementation would need to be rentrant for true (OS) threads... -c From spam at ob_scure.dk Mon Jul 8 17:51:30 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Mon, 08 Jul 2002 23:51:30 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> Message-ID: <3D2A0962.5030303@ob_scure.dk> Neil Schemenauer wrote: > What's wrong with fork()? Available on Win32? In our current situation that's a requirement. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From aahz at pythoncraft.com Mon Jul 1 12:32:50 2002 From: aahz at pythoncraft.com (Aahz) Date: 1 Jul 2002 12:32:50 -0400 Subject: New style classes as exceptions (Was: exception handing) References: Message-ID: In article , Denis S. Otkidach wrote: > >New style classes don't work when used as exceptions. I guess it >should be considered as a bug. Nope, that's just the way it currently works. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From shalehperry at attbi.com Tue Jul 23 15:56:07 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 12:56:07 -0700 (PDT) Subject: NEWBIE: for statement in "dive into python" gives syntax err In-Reply-To: Message-ID: On 23-Jul-2002 Mack wrote: > Hi > > I need some pointers. I've been reading the "Dive into python" tutorial > and tried some statements on my machine. Redhat 7.1 with python 1.5.2 > >>>> li = [1, 9, 8, 4] >>>> li > [1, 9, 8, 4] >>>> [elem*2 for elem in li] > File "", line 1 > [elem*2 for elem in li] > ^ > is what i'm getting. Is my python too old? Is something else wrong? > I've just cut and pasted from the tutorial into python ide. > yep. "Dive Into Python" has a lot of code which only works under 2.1.x and up. The syntax you pasted is called a 'list comprehension' and was added in the 2.x series. The 1.5 idiom for the above would have been: output = map(lambda elem: elem * 2, li) or def double(item): return item * 2 output = map(double, li) or even output = [] for elem in li: output.append(elem * 2) From mgerrans at mindspring.com Fri Jul 5 04:06:30 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Fri, 5 Jul 2002 01:06:30 -0700 Subject: Full-screen display in Tkinter References: <21298535.0207040554.6caeed01@posting.google.com> <3D245F10.FDFE02DF@ipm.fhg.de> Message-ID: By the way, unless this is a turnkey application, I think most people find this sort of behavior by a program (even installers) to be very annoying. From brian at sweetapp.com Fri Jul 19 04:01:09 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 19 Jul 2002 01:01:09 -0700 Subject: C-API question: Memory returned by PyString_AsString In-Reply-To: <2379a09f.0207182349.58a98350@posting.google.com> Message-ID: <007201c22efa$713fe630$bd5d4540@Dell2> > functions like PyString_AsString return a pointer to a character > vector. Is this memory specially allocated when I call this function > (which implies I have to take care of it in my program) or is this > merely a pointer to a character vector stored by the Python > interpreter (implying that I should not free the memory). I assume > that the later is correct, but would like to have a definitive answer. According to the docs (which you should read :-): char* PyString_AsString (PyObject *string) Returns a null-terminated representation of the contents of string. The pointer refers to the internal buffer of string, not a copy. The data must not be modified in any way. It must not be de-allocated. Cheers, Brian From roy at panix.com Sun Jul 14 10:03:15 2002 From: roy at panix.com (Roy Smith) Date: Sun, 14 Jul 2002 10:03:15 -0400 Subject: isA function? References: Message-ID: I wrote: >> We're writing some unit tests, and one of the tests is "foo() returns >> something which isA (bar)". "Afonso Fernandez Nogueira" wrote: > "isinstance() considered harmful": > http://www.mail-archive.com/kragen-tol at canonical.org/msg00007.html A very interesting article; thanks for the URL. Still, I think it's a reasonable thing to do in a unit test environment. I suppose "unit test" can mean different things to different people (just like the article says about "object oriented"). The way we're doing it, every time we say "foo() does blah", we write a test case to make sure foo() really does blah. No, we're not doing XP, but this seems like one of the good ideas that can be adopted from XP. In this case, we said, "foo() returns a list blahs". It's actually the case that it'll always be a subclass of blah; exactly which subclass depends on the input. We started out with: assertEquals (foo.__class__.__name__, "blah_1") then I realized that was dumb and changed it to: assertEquals (foo.__class__, myModule.blah_1) which is a little more pythonic, but still a special case. It may still be worth writing that test case, but assert_ (isinstance (foo, myModule.blah)) is really what I want for the unit test. From phr-n2002b at NOSPAMnightsong.com Wed Jul 31 03:15:47 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 31 Jul 2002 00:15:47 -0700 Subject: global interpreter lock not working as it should References: Message-ID: <7xptx4z7to.fsf@ruckus.brouhaha.com> anton wilson writes: > > Quick tangential question: if there's no blocking of any kind, why are you > > using threads, anyway? Off the cuff thinking says this seems like a misuse > > of them. > > For a real-time system. ;) It will work. It would just be nice if they > switched exactly every 10 byte codes becuase that means they only use about > 10 to 20 milliseconds each. Maybe you want to switch to Stackless Python and use microthreads. See www.stackless.org. From mhuening at zedat.fu-berlin.de Mon Jul 22 03:51:41 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 22 Jul 2002 07:51:41 GMT Subject: Parnassus gone?? Message-ID: What happened to The Vaults? I just got this error: Error 400 - Unable to resolve host name - http://www.vex.net/parnassus/. Thanks, Matthias From max at alcyone.com Sun Jul 7 16:15:08 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 Jul 2002 13:15:08 -0700 Subject: FancyURLopener: no HTTP status codes? References: <3D281E6F.2080909@snakefarm.org> Message-ID: <3D28A14C.A65FB894@alcyone.com> Carsten Gaebler wrote: > is there any possibility of getting the HTTP status code from a > urllib.FancyURLopener object? If you just want the code, you want to use httplib directly. urllib.FancyURLopener is an abstraction that works independent of protocol, so it doesn't really know anything about HTTP status codes. You can use something as simple as: try: connection = httplib.HTTPConnection(host) connection.request(REQUEST_TYPE, file) response = connection.getresponse() self.code = response.status connection.close() except socket.error: # socket error self.code = 900 except httplib.HTTPException: # httplib error self.code = 901 except IOError: # TCP/IP IO error self.code = 902 except ValueError: # int(port) failed (bad URL) self.code = 903 The 9xx codes, of course, are inventions here to indicate metaerrors. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From fperez528 at yahoo.com Fri Jul 26 18:41:09 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 16:41:09 -0600 Subject: performance problem in python 2.2 References: <7xn0sedslz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > Also: > > $p?=?2**64; > $c?=?$ARGV[0]; > $n?=?exp(-($c*$c)?/?(2*$p)); > print?1-$n,?"\n"; > > should give a pretty close approximation faster than any of the > iterative methods listed. > cute. I wasn't addressing the point of the existence of an analytic solution to the recursion (I haven't looked at your form, I'm assuming it's right), but simply that for a tight numerical loop, languages like perl and python are simply in a different class than C. Their inherent type flexibility (which means different things in the two, I know) simply prevents the possibility of the kind of optimizations that a compiled, statically typed language like C allows here. The fact that one may spend a year's worth of cpu in computing an expression for which an analytic solution exists is orthogonal to the point I was making. cheers, f. From matt at mondoinfo.com Mon Jul 15 16:29:23 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Mon, 15 Jul 2002 20:29:23 GMT Subject: horizontal line in tkinter???? References: Message-ID: On Mon, 15 Jul 2002 17:18:40 -0300, jubafre at zipmail.com.br wrote: > I want a horizontal line to separate the frames in my tkinter > aplication, how can i insert it???? Use a frame that's one dot tall: >>> from Tkinter import * >>> r=Tk() >>> f=Frame(r,height=20,width=50,bg="green") >>> f.pack() >>> f=Frame(r,height=1,width=50,bg="black") >>> f.pack() >>> f=Frame(r,height=20,width=50,bg="yellow") >>> f.pack() Regards, Matt From gtaylor at lowebroadway.com Tue Jul 9 05:02:38 2002 From: gtaylor at lowebroadway.com (Garry Taylor) Date: 9 Jul 2002 02:02:38 -0700 Subject: Multi-threading on Multi-CPU machines References: <3D29FC43.C239BD5F@earthlink.net> Message-ID: Joseph A Knapka wrote in message news:<3D29FC43.C239BD5F at earthlink.net>... > Garry Taylor wrote: > > > > Hello, > > I am attempting to make a multi-threading function in one of my > > programs in an effort to gain a speed increase, but I'm getting quite > > the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten > > me as to why, > > Yes. CPython threads cannot utilize multiple CPUs, due to the > Global Interpreter Lock, which may only be acquired by one > thread at a time. Apparently Jython threads do not have > this limitation, as the GIL doesn't exist in Jython, or so > I'm told. So if you simply ran your program under Jython > you might see an improvement. > > Cheers, > > -- Joe Thank you both for your anwsers, unfortunatly running under Jython is not an option, as the whole program which I am writing runs to about 5,000 lines and use lots of Python modules which I don't really fancy trying to get to work under Jython. So, am I correct in thinking that there is nothing I can do about this, and still use standard Python? I understand that Solaris has a very good threading library, but from the comments above, I assume that this would make no difference? Do you have any tips/ideas how I could make use of multiple processors in a Python program? Thanks again Garry From claird at starbase.neosoft.com Wed Jul 24 08:42:06 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 24 Jul 2002 07:42:06 -0500 Subject: GUI toolkits References: <3d3e8e2e_4@news.newsgroups.com> Message-ID: <6BD35F86024903BE.21C9C2AF4CD75C43.49FE3231C518DCC1@lp.airnews.net> In article <3d3e8e2e_4 at news.newsgroups.com>, JB wrote: >Stefano Vedovelli wrote: > >> Hello all >> >> in my spare time I am writing a tool in python, with the >> intention of deliver it under GPL. >> >> I am now starting to approach the GUI part. I have read a >> lot about Tkinter, PyQT and wxWindows, but I am now >> actually even more confused. >> >> As the interface will be "quite" rich, I'd like to know >> the opinions of people who already faced this decision, >> which tool they have chosen and why. > >I have chosen PyQt, as Qt is itself excellent and PyQt is >excellent as well. >In my opinion Qt is superior to Tk, though you may get >problems if you your OS is Ms-Windows. >Tkinter is a nice product but suffers somewhat from the >limitations of Tk. You may want to need the Tk megawidgets, >that is a set of additional widgets for Tkinter, but I had >problems with it. >Then you may study pygtk. Gtk+ is excellent as well but I >had problems with pygtk. . . . It's important to know that sensible people choose each of the three possibilities you've mentioned. In the grand scheme of things, all three of these are roughly comparable. Your decision will probably depend on subtle, perhaps subjective, dimensions that are difficult for outsiders to divine. Your question's a reasonable one; even more than with other engineering choices, though, it's important that you specify your situation clearly. What are your platform requirements? What does "rich inter- face" mean to you? Do you prefer to read books or online documentation? ... -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From rodneys at nospam.io.com Wed Jul 17 01:04:08 2002 From: rodneys at nospam.io.com (Rodney Somerstein) Date: Wed, 17 Jul 2002 05:04:08 GMT Subject: Any Python distribution solutions for Mac? References: <080720021958161862%rodneys@nospam.io.com> <20020716140415308+0200@news.t-online.de> Message-ID: <170720020104082917%rodneys@nospam.io.com> In article <20020716140415308+0200 at news.t-online.de>, Dinu Gherman wrote: > I wrote something to create "packages" (.pkg) on OS X. > All Apple update pacakges seem to use this kind of in- > staller. For some reason they are compressed using pax, > which is not always available on other platforms. Also, > my tool never handled multi-packages. And Installer.app > seems to give wrong install size estimates by definition, > but... > > Yep, some people suggested to make a distutils adaptor > for it, but at the time that seemed too complicated to > me. > > I haven't used it (buildpkg.py) for a while, but you > can get it here: > > http://python.net/~gherman/#buildpkg > Thanks for the response, Dinu. I was beginning to doubt that any Mac users actually read this group. I have had one other response which was just a me-too. I'll take a look at buildpkg when I get the opportunity. -Rodney From pyth at devel.trillke.net Mon Jul 1 18:07:37 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 2 Jul 2002 00:07:37 +0200 Subject: New style classes as exceptions (Was: exception handing) In-Reply-To: ; from aahz@pythoncraft.com on Mon, Jul 01, 2002 at 12:32:50PM -0400 References: Message-ID: <20020702000737.J10625@prim.han.de> Aahz wrote: > In article , > Denis S. Otkidach wrote: > > > >New style classes don't work when used as exceptions. I guess it > >should be considered as a bug. > > Nope, that's just the way it currently works. what's your definition of a bug, then? From eike.kock at movatis.com Mon Jul 29 10:46:55 2002 From: eike.kock at movatis.com (Eike Kock) Date: 29 Jul 2002 07:46:55 -0700 Subject: [Announce] Crusader Open-Source Project Message-ID: Crusader is a powerful application server for Python based upon a scaleable, extensible and easy-to-use general purpose server framework. Sub-Projects: 1. The Crusader Server Framework is the foundation for all Crusader-based servers. It can host multiple servers, protocols and applications, is multi-threaded, supports distributed session management, clustering, runtime configuration and deployment, scheduling, logging and more. 2. Spellcaster is a remote object server based on the Crusader Server Framework. It makes Python objects available over the Internet or Intranet in a platform and programming language neutral way. Spellcaster currently uses the XMLRPC protocol and will be SOAP-enabled soon. 3. Snakecharmer is an advanced Python Server Pages (PSP) implementation based on the Crusader Server Framework. It allows you to mix HTML and Python in a ASP/JSP/PHP way, supports HTTP redirects and status codes, access to GET/POST data, file uploads, file inclusion, session management, precompiling and caching. For more information please visit: http://www.movatis.com/crusader Eike -- movatis GmbH Frankfurter Strasse 42, D-53773 Hennef Tel 02242/96 987-0, Fax -296 mailto:eike.kock at movatis.com http://www.movatis.com From fredrik at pythonware.com Sun Jul 14 07:12:00 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Jul 2002 11:12:00 GMT Subject: Problem with shelve / nested lists References: Message-ID: <40dY8.15984$p56.5169770@newsb.telia.net> Michael Schmitt wrote: > I'm trying to use a shelve as a disc based dictionary, but have problems > with nested lists. If I store a nested list as value, inner lists seem to > be immutable. > > According to the library reference, shelves can store "essentially > arbitrary Python objects" and "recursive data types". the shelve only stores things when you write d1['bla'] = value and only fetches things when you use d['bla'] in an expression. if you write d1['bla'][2].append(30) you'll fetch a value from the shelve, modify the return value, but you're not writing it back. (with this in mind, this isn't that different from asking why, say file.read(20) + "hello" doesn't write "hello" to the file) to make this work as you want, think in read/write terms, and make sure you always assign to the shelve when you've modified a value, so it can write it back: value = d1['bla'] value[2].append(30) d1['bla'] = value From aleax at aleax.it Tue Jul 9 17:35:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 21:35:16 GMT Subject: Why self? References: <3D2B19CE.5040409@onsitetech.com> <3D2B540B.4030205@onsitetech.com> Message-ID: Robb Shecter wrote: > Alex Martelli wrote: >>... And the reason you don't have to state that, is that it makes >>absolutely >> no difference whatsoever -- you can try to get any attribute (methods >> included) from any object, it either succeeds or fails (and that only >> partly depends on the object's class). > > Well, I'd say that an object understanding the message I send to it, or > being the type of object I think it is - success or failure - surely is > a big difference! Sort of the name of the whole game... An object can "understand" (well...) the message (out of metaphor: be able to supply the attribute or method you're asking of it) WITHOUT "being the type you think it is". This is called POLYMORPHISM, and IS the whole game. Alex From hesterloli at hotmail.com Sun Jul 28 14:56:39 2002 From: hesterloli at hotmail.com (George Hester) Date: Sun, 28 Jul 2002 18:56:39 GMT Subject: Disappearing Output? Message-ID: I have a very simple Python script in a ASP page. The ASP looks like this: <%@LANGUAGE=Python%> Python Version

Python Test

<% #do some python stuff here import sys Response.write('

Smaller heading

') var = "%s%s%s" % ('Python version = ',sys.version,'') Response.Write(var) %> I actually got this from this group a month ago. Anyway I decided to upgrade (I hate that word) my version of Python at ActiveState to the latest build. I knew I should not have done that but I did because my file associations got crapped out but trying to install a GUI for making Python Scripts. That attempt has really done my system bad. Windows 2000 SP2 IIS 5. I can run in the browser .py files no issue. But if I try to run an ASP as shown above I get output sometimes but often I get absolutely nothing. No output. No errror. Just absolutely nothing. Is this a Python issue, a Python Script issue or something else under the sun? Thanks. -- George Hester _________________________________ From marklists at mceahern.com Fri Jul 26 13:39:03 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 26 Jul 2002 12:39:03 -0500 Subject: extract elements of n char from a list In-Reply-To: Message-ID: > well, i think that i could use : > > nl = [e for e in l if len(e) ==n] > > but is it efficient ? are they more efficient ways ? and when is > it good pythoner technique to use list comprehensions ? List comprehensions are just dandy, aren't they? No doubt you've heard about premature optimization is the root of all evil? Why are you worried about efficiency? What size list are you talking about? What other relevant facts are you not sharing with us? I would recommend you focus more on solving your problem and THEN, if it's too slow, use a profiler to locate bottlenecks. // mark From duduca007 at yahoo.com Wed Jul 24 14:25:27 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Wed, 24 Jul 2002 11:25:27 -0700 (PDT) Subject: GUI toolkits In-Reply-To: <3d3e8e2e_4@news.newsgroups.com> Message-ID: <20020724182527.25909.qmail@web11404.mail.yahoo.com> --- JB wrote: > Stefano Vedovelli wrote: > I have chosen PyQt, as Qt is itself excellent and > PyQt is > excellent as well. > In my opinion Qt is superior to Tk, though you may > get > problems if you your OS is Ms-Windows. > Tkinter is a nice product but suffers somewhat from > the > limitations of Tk. You may want to need the Tk > megawidgets, > that is a set of additional widgets for Tkinter, but > I had > problems with it. > Then you may study pygtk. Gtk+ is excellent as well > but I > had problems with pygtk. I agree with Stefano. I belive that PyQt is the best choice. QT is a extreme stable and portable framework, PyQt follow these premises. The OpenGL widget of PyGtk ? very inefficient. []'s Cadu Moreira KaduSoft President -------------------------- [...15h 30min in Brasilia...] __________________________________________________ Do You Yahoo!? Yahoo! Health - Feel better, live better http://health.yahoo.com From rotundo52 at hotmail.com Sun Jul 21 00:28:50 2002 From: rotundo52 at hotmail.com (Jon J. Morin) Date: Sun, 21 Jul 2002 04:28:50 GMT Subject: getting date into rfc822 format Message-ID: <6Mq_8.6690$Ga1.1849904@news1.news.adelphia.net> Hi all. I'm writing a program that sends email in an environment that does not have sendmail or similar MTA. I am trying to prepend the date to the headers of the email, but many mail clients that I have tested it with show the date as unknown when the message comes in. Here is how I come up with the date: import time date = time.ctime(time.time()) Which gives me a date like this: Sat Jul 20 00:02:03 2002 When what I want is something like this: Fri, 01 Mar 2002 00:18:17 -0500 (EST) Incidentally, I have read the rfc822 and I can't figure out what the -0500 is in the date/time. Can anyone explain this to me? Jon J. Morin University of Maine at Augusta From robert_kuzelj at yahoo.com Wed Jul 3 09:55:18 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 3 Jul 2002 06:55:18 -0700 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: hi jonathan, > Pretty much *everything* in the system is an object. This makes the entire > language uniform in its operation. It makes instrospection easier and it > allows metaclasses to change the behaviour of classes. i know that and i like it. > Then perhaps you could explain your problem and maybe we can help. So far > you've told us how you're going about something, but not why. > > Why do you need to differentiate between classes and "instances"? Perhaps > there's another way to do what you want that will work. lets simply say: the requirement is exactly to destinguish between instances and classes. one could imagine an object that is a mix between a factory and a prototyperegistry. class ProtoFactory: def __init__(self): self.SourceObjects = {} def register(self, name, source): self.SourceObjects[name] = source def create(self, name): source = self.SourceObjects(name) if isinstance(source, types.Instance.Type): return copy.copy(source) else: return source() this is just an example. i am sure, that this can be done differently. the real reason why i want to do this is something i realy dare not to say in this forum ;-) just that i am realy realy nasty! ciao robertj > > Jonathan From jonathan at onegoodidea.com Tue Jul 30 08:21:56 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 13:21:56 +0100 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: On 30/7/2002 12:29, in article ukcu02su9a7r5b at news.supernews.com, "John Roth" wrote: > Why bother with the restrictions? Fredrik had the right idea when > he said that we needed something to make it obvious that functions > are first class objects. That is, allow anonamous functions anywhere > you can have a function object. How far does one go? Classes are first-class objects, should we also have anonymous classes? >>> foo = (class: ... def __init__( self, x y ): ... self.x = x ... self.y = y ... )( 5, 6 ) >>> >>> foo.x 5 >>> I'm a fan of lambda, but when a function is complex enough that it can't be done in an in-(one-)line lambda then it should be pulled out and given a name. Jonathan From pecora at anvil.nrl.navy.mil Tue Jul 9 08:22:38 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 08:22:38 -0400 Subject: Why self? References: <080720021650379803%pecora@anvil.nrl.navy.mil> Message-ID: <090720020822385019%pecora@anvil.nrl.navy.mil> In article , wrote: > In new-style classes, all variables are declared in __slots__. However, > this doesn't seem to solve the problem of referring to class attributes > (including methods and properties), which can also currently be named > using 'self.attr'. A new __metaslots__ or __classslots__ ? Hmmm...__slots__. I really have to catch up on Python. Thanks. Yes, the attributes and methods are still a "problem." -- Lou Pecora From zopestoller at thomas-guettler.de Thu Jul 25 09:26:44 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Jul 2002 15:26:44 +0200 Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> Message-ID: <3D3FFC94.60108@thomas-guettler.de> Alex Martelli wrote: > Thomas Guettler wrote: > ... > >>Yes, I can do foo=str(foo) myself before calling escape, >>but this feature would hurt noone. >> > > Many Python functions expect to get arguments of specific types > (or polymorphic to such types, i.e., supplying all necessary > methods and operations with equal signatures). > > Having them accept arguments of wrong types, with silent coercion, > would hurt all careful developers, by hiding bugs. I agree, but than the exception should have a better message: $ python escape.py Traceback (most recent call last): File "escape.py", line 3, in ? cgi.escape(2) File "/usr/lib/python2.2/cgi.py", line 1024, in escape s = s.replace("&", "&") # Must be done first! AttributeError: 'int' object has no attribute 'replace' A exception with a message like: "Argument must be a string" would be better thomas From hst at empolis.co.uk Tue Jul 9 09:04:34 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 9 Jul 2002 14:04:34 +0100 Subject: Splitting a string every 'n' Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C67@hendrix.empolisuk.com> Simon.Foster at smiths-aerospace.com wrote: > > What is the idiomatic way to split a string into a list > containing 'n' character substrings? I normally do > something like: > > while strng: > substring = strng[:n] > strng = strng[n:] > > > But the performance of this is hopeless for very long strings! > Presumable because there's too much list reallocation? Can't Python > just optimise this by shuffling the start of the list forward? > > Any better ideas, short of manually indexing through? Is there > something like: > > for substring in strng.nsplit(): > > How about: import re rex = re.compile('....', re.DOTALL) for substring in rex.findall(string): HTH Harvey Thomas _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From b.maryniuk at forbis.lt Mon Jul 8 09:31:34 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 8 Jul 2002 15:31:34 +0200 Subject: PKSC1 In-Reply-To: <1026134661.5486.0.camel@ratthing-b3cf> References: <200207081520.35063.b.maryniuk@forbis.lt> <1026134661.5486.0.camel@ratthing-b3cf> Message-ID: <200207081531.34491.b.maryniuk@forbis.lt> On Monday 08 July 2002 15:24, Martin Sj?gren wrote: > There's always a race condition between your fingers while typing 'pkcs' > isn't there? :-) somethnig liek that. :))) -- Sincerely yours, Bogdan M. Maryniuck Intel engineering seem to have misheard Intel marketing strategy. The phrase was "Divide and conquer" not "Divide and cock up" (By iialan at www.linux.org.uk, Alan Cox) From StRanGy at cna2.kav.vest.hr Fri Jul 26 07:49:35 2002 From: StRanGy at cna2.kav.vest.hr (Ivica) Date: 26 Jul 2002 11:49:35 GMT Subject: GUI toolkits References: Message-ID: On Wed, 24 Jul 2002 10:58:38 GMT, Stefano Vedovelli wrote: > Hello all > > in my spare time I am writing a tool in python, with the intention of > deliver it under GPL. > > I am now starting to approach the GUI part. I have read a lot about Tkinter, > PyQT and wxWindows, but I am now actually even more confused. > > As the interface will be "quite" rich, I'd like to know the opinions of > people who already faced this decision, which tool they have chosen and > why. > > Tia > Regards > Stefano Vedovelli Ok this is good but I'm more interested in opinions regarding FXPy (FOX) v. wxWindows or FXPy v. PyQt the pros and cons Tnx From mcfletch at rogers.com Fri Jul 12 12:56:20 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 12 Jul 2002 12:56:20 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <3D2F0A34.8060608@rogers.com> Oh goody, a religious war :) I've been (peripherally) involved in a --go to XML for XML's sake-- projects. We managed to take a readable, readily-parsed, UTF-8 format which dozens of pieces of software could read and write, which could be readily and reliably edited with a plain-text editor, and was compact enough for use as a web-publishing data format, and turned that ISO standard into a format that no one would consider writing or editing by hand (ridiculously voluminous), no-one would download over the internet (same), no software could read or write readily (save a few sample implementations produced by the conversion teams), and which made data validation a hairier step for the programmes dealing with the new format. Months (years) of effort that should have gone elsewhere, across dozens of companies was spent dismantling and re-branding a format which had been designed and evolved over years to do _exactly_ what it needed to do as an interchange format for 3D data. There were conferences where the big question wasn't "how do we make this stuff better for our users", but "do we encode attributes as tags or tag-attributes?", and "how do we encode the data types reliably so that editors know what they are, but the resulting file doesn't look like trash?" Why? Because a group of corporations had decided: 1) this format was to be a "web" format (instead of a 3D interchange and VR format) 2) all things "web" must be blessed by being XML 3) current tools, programmes and users don't matter, because once we are XML-based, everything will just magically work. That, to me, is XML done totally wrong, and projects like it are why people get allergic reactions. The problem with cultivating an allergic reaction is that I _love_ SGML (which I started with way back when Paul and I worked with Professor Beam at Waterloo). I _love_ SGML (and XML by extension) as a _textual_ markup language. It's good for taking a stream of characters and stating what type of text each bit of that stream is. It's even better for describing truly hierarchically structured texts, such as seen in textbooks, manuals and the like (it's not great for poetry or artistic works of many types). I also prefer XML for use in comp-sci problems where there's no readily-available and superiour format available (configuration files are fine in XML (if people prefer), as long as I can sit down and edit one from scratch without _requiring_ an XML editor (which is hard in many examples of XML I've seen, because of the hoops being jumped through to shoe-horn data-typing into a _textual_ markup language)). [As a note, I've not found a decent XML editor along the lines of InContext's SGML editor, with useful support for editing text with the hierarchy visible, but not interfering with navigation, along with intelligent split/join/surround/un-surround/merge/ paste-hierarchical/paste-flat/create entity/use entity/etceteras facilities.] I don't even mind XML being used for SOAP-like systems, "let them eat cake if they're only going to do it a few times a minute, they don't mind wasting some bandwidth, why should I care". In the absence of a better format, yes, go with XML. If you're worried about long-term storage, I'll consider an argument for XML. For real-time work, with an only slightly better format, sure, if we don't have a lot of code depending on that format, go ahead. If you're downgrading service to your customers just to "be XML", then you've screwed up. Mastery of force is not the ability to marshal great force in all situations, but to know where, how and when to apply minimal force to achieve maximal benefit. Mike Fran?ois Pinard wrote: ... >>but it's readable and fairly obvious in meaning. > > > The original non-XML format is also pretty readable and obvious in meaning. > Surely, there are advantages to XML, but at first glance here, it seems we > gain nothing but verbosity and monstrosity. In my opinion, the advantages > have to be pretty real to justify such a change. We should not go XML > for the only sake of going XML. ... From ods at fep.ru Mon Jul 15 13:11:36 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Mon, 15 Jul 2002 21:11:36 +0400 (MSD) Subject: Newbie: Capture output of compile_dir In-Reply-To: <20020715154327.46010.qmail@web13007.mail.yahoo.com> Message-ID: On Mon, 15 Jul 2002, Becky Hehn wrote: BH> BH> I want to be able to capture the output of compile_dir BH> because I want to further process the output of this BH> command. It appears that compile_dir prints output to BH> the screen rather than returning it to the caller. BH> How do I capture the output of this command? If I do BH> something like: BH> output=compile_dir(path) BH> the output of compile_dir gets printed to the screen BH> and the variable output just hold an integer. import sys from cStringIO import StringIO orig_so = sys.stdout sys.stdout = captured = StringIO() compile_dir(path) sys.stdout = orig_so output = captured.getvalue() -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From opus at value.net Sun Jul 7 06:58:13 2002 From: opus at value.net (Opus) Date: Sun, 7 Jul 2002 03:58:13 -0700 Subject: structs in python In-Reply-To: <7xsn2wyrr2.fsf@ruckus.brouhaha.com> Message-ID: <3D27BC55.21407.320A274@localhost> And the __slots__ way is strange if you are using the __variables in your class. class thing(object): __slots__ = ["_thing__var"] # Huh??? def __init__(self,init): self.__var = init For the point idea, the typo there would have been caught in the compile time. And, doing the delta actually makes much more sense overloading __sub__ for the point class. class Point(object): def __init__(self,x,y,color): self.x=x self.y=y self.color = color def __sub__(self,other): return Point(self.X-other.X, self.Y-other.Y, self.color-other.color) True, this is some code to create, but because it is something that is not going to be used that often, it means that you control the way it is done in one place and you don't have to remember, or research how to do it everytime you use it. And, yes, I have used classes in C++ as structs, and I remember that it was the prefered way to handle structs. On 6 Jul 2002 at 23:30, Paul Rubin wrote: > "Sean 'Shaleh' Perry" writes: > > However this breaks down for your delta = ... example. > > > > is > > > > class Point: > > def __init__(x, y, color): > > self.x = x > > self.y = y > > self.color = color > > > > really that much to type? > > Yes, it seems clumsy to me. See how error prone it is: your __init__ > function arg list forgot to mention 'self'. > > The new slots scheme may be better but it doesn't exist in older > Pythons and isn't well documented in 2.2. > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- Eagles may soar, but weasels don't get sucked into jet engines. - Unknown -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From loewis at informatik.hu-berlin.de Wed Jul 31 13:30:17 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 31 Jul 2002 19:30:17 +0200 Subject: newbie : unicode References: <3D473933.8040306@wanadoo.fr> <3D481726.20500@wanadoo.fr> Message-ID: polux writes: > what is or where is sitecustomize.py ? It must be in the Python path, see http://www.python.org/doc/current/lib/module-site.html When you do sys.getdefaultencoding(), what do you get? Regards, Martin From phr-n2002b at NOSPAMnightsong.com Wed Jul 10 03:56:28 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 10 Jul 2002 00:56:28 -0700 Subject: try/finally question References: <7xd6twow3x.fsf_-_@ruckus.brouhaha.com> Message-ID: <7x8z4kow2b.fsf@ruckus.brouhaha.com> Paul Rubin writes: > Is there a reasonable way to skip around a "finally" clause? Oops, ignore this first sentence, it was left by an editing error. The rest of the post is what was intended. Sorry. From gerhard.haering at gmx.de Sun Jul 28 17:21:09 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 28 Jul 2002 23:21:09 +0200 Subject: python mysql interface In-Reply-To: <3d444d8e$1_2@nopics.sjc> References: <3d444d8e$1_2@nopics.sjc> Message-ID: <20020728212109.GA1842@lilith.my-fqdn.de> * Adonis [2002-07-28 16:01 -0400]: > i hav downloaded Python mySQL, but lacks any documentation? Download the source distribution of MySQLdb for documentation and examples. > is there a recommended mySQL module for Python? Yes, MySQLdb, which you seem to have downloaded. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From sholden at holdenweb.com Mon Jul 8 07:50:39 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 8 Jul 2002 07:50:39 -0400 Subject: Concept Error References: <3d27d274$0$24427$afc38c87@news.easynet.co.uk> <3d2809cc$0$24392$afc38c87@news.easynet.co.uk> <3d288a36$0$24413$afc38c87@news.easynet.co.uk> Message-ID: "chris lyon" wrote in message news:3d288a36$0$24413$afc38c87 at news.easynet.co.uk... > Sussed it. > > I had a paramenter called conn and in fact I needed conn.conn > I've just spent a day and a half focussing on the wrong variable ho hum > Working all night isn't always as productive as ytou might imagine ... hoping-you-got-some-sleep-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 11:51:36 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 10:51:36 -0500 Subject: re.finditer References: <2259b0e2.0207230706.41ff60b@posting.google.com> Message-ID: >>>>> "Michele" == Michele Simionato writes: Michele> According to the standard library Michele> http://www.python.org/doc/current/lib/node99.html : Michele> finditer(pattern, string) Return an iterator over all Michele> non-overlapping matches for the RE pattern in string. For Michele> each match, the iterator returns a match object. Empty Michele> matches are included in the result. New in version 2.2. You want 'import sre' >>> import sre >>> import re >>> re.finditer('r+?','library') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'finditer' >>> sre.finditer('r+?','library') Is this a documentation bug? JDH From jason at mastaler.com Wed Jul 17 18:27:24 2002 From: jason at mastaler.com (Jason R. Mastaler) Date: Wed, 17 Jul 2002 16:27:24 -0600 Subject: socket.gethostbyaddr() is slower than Christmas Message-ID: On a certain Redhat-7.3 system, socket.gethostbyaddr() calls to the localhost are taking upwards of 30 seconds to return. What would account for such behavior? Is this a bug? For example, $ python2 Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from socket import * >>> name = gethostname() >>> name 'datavortex.net' >>> gethostbyaddr(name) ('datavortex.net', ['localhost.localdomain', 'localhost', 'im.corp.earthlink.net'], ['127.0.0.1']) >>> The gethostname() call is instantaneous, while the gethostbyaddr() takes an unnaturally long time to finish. -- (http://tmda.net/) From b.maryniuk at forbis.lt Mon Jul 22 08:19:43 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 22 Jul 2002 14:19:43 +0200 Subject: ssh and Python In-Reply-To: References: Message-ID: <200207221419.43635.b.maryniuk@forbis.lt> On Monday 22 July 2002 13:12, Erno Kuusela wrote: > use a rsa key with ssh-agent (or without passphrase if you need > it to run unattended). But sometimes you just need to pass a password. -- Sincerely yours, Bogdan M. Maryniuck "Are [Linux users] lemmings collectively jumping off of the cliff of reliable, well-engineered commercial software?" (By Matt Welsh) From piet at cs.uu.nl Mon Jul 8 06:17:51 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 08 Jul 2002 12:17:51 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: >>>>> "Mike C. Fletcher" (MCF) writes: MCF> Well, and here I was believing utf was a clean and elegant format to make MCF> the best of a bad situation (I'm hoping utf-8 still is, though, of course, MCF> it will have these dang surrogates to contend with ;) ). MCF> "Nothing's clean, nothing's elegant kid. Get used to that. This is the MCF> real world, and out here, we just hack at the corpses until they give us MCF> what we want. There're no master criminals any more, just frustrated MCF> people, impossible situations, and no emotional air conditioning." UTF-8 is still clean and elegant IMHO. But in UTF-8 not every byte sequence is a valid code. The problem with the surrogates is that they are not Unicode characters. Rather they are halfs of Unicode characters in UTF-16 encoding. In UTF-16 encoding Unicode characters > 2**16 are encoded with two 16-bit surrogates, the first one from the range 0xd800-0xdbff, the second one from 0xdc00-0xdfff. Your original input string u'\ud800\udb7f\udb80\U0010fc00\udfff' wasn't a Unicode string, because the surrogates are not Unicode characters. Worse, it wasn't even a valid UTF-16 encoding as it contains consecutive words from the range 0xd800-0xdbff. The encoding (or maybe even the Python parser) should have given an error message. Instead, it produced an invalid UTF-8 byte sequence, which then gives an error message at decoding. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From me at michaelbauers.com Thu Jul 11 22:32:22 2002 From: me at michaelbauers.com (Michael Bauers) Date: Thu, 11 Jul 2002 21:32:22 -0500 Subject: pygame question References: Message-ID: I borrowed the event loop from pygame's chimp example. And they used 'is' for some reason. All I did was add the handler for K_r and made it look like the other code in their loop. "Terry Reedy" wrote in message news:BnqX8.37719$iB1.2146169 at bin4.nnrp.aus1.giganews.com... > > "Michael Bauers" wrote in message > news:uis3ccnreo0u32 at corp.supernews.com... > > I was curious as to why 'is K_SPACE' worked, but 'is K_r' did not. > I had to > > change the test for 'r' to ==. > > > > * code snippet * > > elif (event.type is KEYDOWN and event.key is > > K_SPACE): > > # DO SOMETHING > > elif (event.type is KEYDOWN and > > event.key == K_r): > > # DO SOMETHING ELSE > > I don't know about your question, but I do about eliminating redundant > code 8-) > I would redo as > elif event.type == KEYDOWN: > keyhit = event.key > if keyhit == K_SPACE: #do x > elif keyhit == K_r: # do y > > Should K_r be K_R? What was your error message? (ie, what does 'not > work' mean?) > > Terry J. Reedy > > > From as at ctes.com Thu Jul 25 14:03:42 2002 From: as at ctes.com (Arneau Starl) Date: Thu, 25 Jul 2002 11:03:42 -0700 Subject: Best way to populate a wxListCtrl widget from mysql Message-ID: <75f0ku48rojqeqo7bs5il2df1vf55bg5pb@4ax.com> What is the best way to populate a wxListCtrl from a Mysql query (may return more that one result). I would then Like to select one or more from the displayed results and perform another action on them. Any help so that I don't waste alot of time going in the wrong direction. Arneau From duncan-news at grisby.org Mon Jul 1 05:07:17 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 01 Jul 2002 09:07:17 GMT Subject: Europython pictures Message-ID: <9ZUT8.21128$l6.4303892@newsfep2-win.server.ntli.net> I took lots of pictures at the Europython conference last week. If you're interested in seeing the action, take a look at http://www.grisby.org/Photos/085/ Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From mfranklin1 at gatwick.westerngeco.slb.com Mon Jul 22 11:15:21 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 22 Jul 2002 15:15:21 +0000 Subject: set Pmw.EntryField ? In-Reply-To: <3D3C10DD.A6D472E9@ipm.fhg.de> References: <3D3C10DD.A6D472E9@ipm.fhg.de> Message-ID: <200207221415.g6MEFL707725@helios.gatwick.geco-prakla.slb.com> On Monday 22 Jul 2002 2:04 pm, Markus von Ehr wrote: > Hi, > > in the program (not on init) I want to assign another value to the > Pmw.EntryField. > How can I do it? from the Pmw docs use the setentry method. setentry(text) Set the contents of the entry widget to text and carry out validation as if the text had been entered by the user. If the text is invalid, the entry widget will not be changed and the invalidcommand function will be called. Return the validity of text. > > Thanks for any comments, > > Markus From aleax at aleax.it Thu Jul 25 10:48:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 14:48:09 GMT Subject: asyncore: limiting number of simultaneous connections? References: Message-ID: Steve Holden wrote: ... > which a read condition is accepted. Any time the socket is so listed (in > the select.select() arguments) any number of simultaneous connections > might occur, though this is unlikely. Hmmm... ANY number? Doesn't the N passed in socket.listen(N) provide an upper limit to the number of connection requests that may be at the same time outstanding? Alex From tim.one at comcast.net Sat Jul 13 15:38:28 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 13 Jul 2002 15:38:28 -0400 Subject: sre.finditer break down: is this a bug? In-Reply-To: <9aZX8.47377$n4.11526798@newsc.telia.net> Message-ID: [Jane Austine] > Newly added function sre.finditer and (matchedObject.)finditer > break down and the system crushes on win32 when requested for > next() after StopIteration. > > see: > >> import sre > >> fi=sre.finditer(r'\s','a b') > >> fi.next() > >> fi.next() > >> fi.next() #system halts for ever. [Fredrik Lundh] > well, I'm tempted to just say "don't do that" (if python tells > you to stop iterating, stop iterating ;-), but it sure looks like > a bug. > > bugs are best reported on sourceforge; see > > http://www.python.org/dev/ > > for details and links. I entered a bug report for this: http://www.python.org/sf/581080 I think re has "an issue" here independent of the intended semantics of the iteration protocol when calling next() after StopIteration has been raised, and the bug report shows a derived example with the same symptom but not using finditer. I brought up the business about the intended iteration protocol semantics on Python-Dev. From pixie888 at hotmail.com Tue Jul 9 04:14:56 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Tue, 09 Jul 2002 08:14:56 GMT Subject: Python tutorial Message-ID: <3d2a9b39.94944531@news.skynet.be> Hi, Is there any Python tutorial out there which happens to be written in Dutch? Thanks for answering, Henk From dale at riverhall.NOTHANKS.co.uk Fri Jul 26 07:11:14 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Fri, 26 Jul 2002 12:11:14 +0100 Subject: Challenge/Response authentication Message-ID: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> I've not done any research into this yet so I could have this completely about my ears. We need to do some basic authentication to control access to some resources through HTTP. As I understand it, challenge/response works thus: 1. client prompts server to connect. 2. server invents a random string. 3. server sends random string to client. 4. client produces SHA/MD5 digest of random string 5. client updates digest with password producing client digest 6. client sends client digest to server with userid 7. server looks up client password 8. server produces SHA/MD5 digest of random string 9. server updates digest with client password producing authentic digest 9. server compares client digest with authentic digest 10. if matched client is authenticated. Can anyone see any holes in this and does anyone have any experience of such a scheme? Is there anything we should look out for? I'm planning to use the MD5 module for the digests. Thanks. -- Dale Strickland-Clark Riverhall Systems Ltd From zopestoller at thomas-guettler.de Wed Jul 24 08:32:03 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 24 Jul 2002 14:32:03 +0200 Subject: Content-Type Guesser Message-ID: <3D3E9E43.2050507@thomas-guettler.de> Hi! Has someone a function for guessing the content type given a filename? foo.xml --> text/xml foo.html --> text/html .... It should work for the most common file-extensions thomas From tsailipu at attbi.com Mon Jul 22 20:51:14 2002 From: tsailipu at attbi.com (Philip Tsai) Date: 22 Jul 2002 17:51:14 -0700 Subject: Jython: any workaround for the missing array module Message-ID: <20f81d64.0207221651.6d57a39@posting.google.com> Hello group, I learned from Jython's documentation that the Python array module is currently unsupported. I am writing to see whether you would happen to know a clean, good workaround? So, instead of "import array" in the *.py, one can perhaps do something about equally easy and efficient in Jython.... Thanks much! Philip From mgilfix at eecs.tufts.edu Wed Jul 31 11:20:15 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 31 Jul 2002 11:20:15 -0400 Subject: How to put a bitmap in a wxPanel ? In-Reply-To: <5.1.1.6.0.20020731110330.00a1a9e0@imap.datacraft.com.br>; from m.laranjeira@datacraft.com.br on Wed, Jul 31, 2002 at 11:05:52AM -0300 References: <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> <5.1.1.6.0.20020731110330.00a1a9e0@imap.datacraft.com.br> Message-ID: <20020731112015.G26901@eecs.tufts.edu> Since someone else already gave you pointers, just a suggestion: look at the numerous examples that come with wxPython. There should be a static bitmap example there that would be most educational. -- Mike On Wed, Jul 31 @ 11:05, Marcus Vinicius Laranjeira wrote: > > > All, > > I am using the boa constructor, and I need to put the logo of my company in > the wxPanel. This bitmap will be static and it will be there just for > decoration purposes. > > Anyone can help me ? > > Cheers, > > Marcus > > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (m.laranjeira) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From i.linkweiler at gmx.de Wed Jul 3 14:18:47 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Wed, 03 Jul 2002 20:18:47 +0200 Subject: PythonWin + other GUIs = CRASH! References: <3D232FEE.3010606@gmx.de> Message-ID: <3D234007.1090103@gmx.de> > > >try SCITE or IDLE > IDLE crashes with Qt and pygame, too. It seems to be a general problem: It is not possible to start a GUI-Toolkit, when the application or the IDE is using a GUI itself. The only GUI which seems to work with most IDEs is tkInter. PyQt, wxPython and Pygame will crash. Ingo From mrspnk at yahoo.com Thu Jul 11 15:19:32 2002 From: mrspnk at yahoo.com (Mr Spannik) Date: Thu, 11 Jul 2002 19:19:32 GMT Subject: html login with python? References: Message-ID: <8TkX8.4650$eY6.88462@news2.ulv.nextra.no> Try looking at the urllib-module, think it has a Authentication-feature. If not, use the http-module and do it the hard way. You'll have to put the headers in the http-request manually and to get authenticated put something like : h.putheader("AUTHORIZATION", "Basic %s" % string.replace(base64.encodestring("% \s:%s" % (username, password)), "\012", "")) I know this was a messy reply, but hopefully it will get you going :-) Thomas "Ralf Claus" <102030405 at gmx.net> wrote in message news:agkkpi$2g0$02$1 at news.t-online.com... > Hello, > my Problem : > to check out the onlinestatus of my router, i need a script to login into > the webinterface of my router. > How can i automatically log in. > > Sorry, i hope you understand the problem > > From aleax at aleax.it Fri Jul 5 12:53:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 16:53:53 GMT Subject: possible bug of parser.suite References: <79e3000a.0207050845.faba950@posting.google.com> Message-ID: Fan Guanping wrote: > parser.suite seems broken at least in Python '2.2.1 (#34, Apr 15 2002, > 09:51:39) > [MSC 32 bit (Intel)]'. Is this a bug,or I use it incorrectly? > >>>> parser.suite('class Abc:pass') > >>>> parser.suite('class Abc:\n def hello(self):\n pass') > Traceback (most recent call last): > File "", line 1, in ? > parser.ParserError: could not parse string I think you just need a trailing \n in the second case -- as you've indented, you must also dedent, or else your suite isn't complete. Note that in the first case there was no indent, so no need for a dedent and therefore no need for trailing \n either (though it would not hurt). Alex From lellinghaus at yahoo.com Tue Jul 9 04:08:47 2002 From: lellinghaus at yahoo.com (Lance Ellinghaus) Date: Tue, 9 Jul 2002 01:08:47 -0700 (PDT) Subject: HTML to PDF converter? Message-ID: <20020709080848.68787.qmail@web20903.mail.yahoo.com> Does anyone know of a HTML to PDF converter that is written in Python? Thank you, Lance Ellinghaus ===== -- Lance Ellinghaus __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com From m.faassen at vet.uu.nl Mon Jul 22 09:13:57 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 22 Jul 2002 13:13:57 GMT Subject: Alex Martelli is off the net for a few days :-( References: Message-ID: Laura Creighton wrote: > Some construction workers have severed his phone and internet lines. > Expect him back in a few days, not a few hours. :-( Of course this is a Python Secret Underground coverup -- the martellibot is offline for maintenance. There were some surprising bugs which caused him to From huaiyu at gauss.almadan.ibm.com Wed Jul 10 13:00:45 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 10 Jul 2002 17:00:45 +0000 (UTC) Subject: A better self References: Message-ID: Sean 'Shaleh' Perry wrote: >> >> Before you all react (programmers can be SO conservative), please think >> about it! >> > >I have played with ideas like this in python and other languages, and witnessed >others do the same. > >.foo is REALLY hard to see if the font is not just right. > >.size = .r + .l > >is even worse. > >I am not 100% against the idea as an idea, but the actual usage is not all that >fun. A better (and currently available) convention is _.size = _.r + _.l It has been mentioned several times in this thread. I've used it several times in the past and liked it, esp in iterative algorithms. Some usage patterns include def __init__(_, x, y, z): _.x, _.y, _.z = x, y, z def process(_, x, y, z): actions involving _.x, _.y, _.z, x, y, z _.x, _.y, _.z = x, y, z def update(_): x, y, z = _.x, _.y, _.z actions involving x, y, z _.x, _.y, _.z = x, y, z One could even think of _. as a magic persistence prefix that makes the variable keep its value between method calls. It is also easy to replace _.x with self.x or vice versa in a good editor. Huaiyu From tim_one at email.msn.com Wed Jul 10 01:22:09 2002 From: tim_one at email.msn.com (Tim Peters) Date: Wed, 10 Jul 2002 01:22:09 -0400 Subject: Unicode utf-8 doesn't do back-and-forth? In-Reply-To: Message-ID: [John Machin] > 4 more bits? It needs 21 bits to encode the 2**20 possible > surrogate-described characters plus the basic 64K characters. > assert 21 - 16 == 5 [Martin v. Loewis] > Not really. This makes a total of 2**20+2**16 = 1114112 > characters. Now, math.log(1114112)/math.log(2) is 20.087462841250343, > so it is rather 4.09 additional bits. [John] > (1) Shouldn't you deduct the 2048 surrogates from the count? If Martin were feeling anal about this, he would have asked why you said "characters" instead of "code points". Since he didn't, I have to assume he's trying to be informative instead . > (2) Why did you round up to two decimal places and not zero decimal > places? Can you buy 4.09 cans of beer? I can't, but if there are 1114112 possible "beer points", and you use a full 21 bits to *encode* each possibility, you're just wasting precious storage . For example, the straightforward Huffman beer encoding, assuming equal probabilities, uses less than 20.12 bits per beer point on average (2**20-2**16 points are assigned 20-bit codes, and the remaining 2*2**16 each get a 21-bit code). a-fractional-bit-saved-is-a-fractional-bit-earned-ly y'rs - tim From keith_s at ntlworld.nospam.com Wed Jul 24 03:40:57 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Wed, 24 Jul 2002 08:40:57 +0100 Subject: embedded python question Message-ID: <3D3E5A09.3020400@ntlworld.nospam.com> I am writing a small application that has a command line for entering Python commands, and a message window to show the Python output. I've used PyRun_SimpleString(cmd) to execute the command typed in the command line, and this works fine for simple statements e.g. print 'hello', but for more complex expressions e.g a for loop I get an 'Unexpected EOF while parsing' syntax error. I'm probably missing something obvious here, but I can't see it - any ideas? - Keith From olc at ninti.com Tue Jul 9 22:06:44 2002 From: olc at ninti.com (Michael Hall) Date: Wed, 10 Jul 2002 11:36:44 +0930 (CST) Subject: CGI Help Please. In-Reply-To: Message-ID: SA: Are you sure this script is working OK? It looks like it is printing a Content-Type header for every line in the file being displayed. I would move this line print "Content-Type: text/plain\n\n" outside (and before) the for loop. Next question: what would happen if someone called your script with the following URL: http://yourdomain/yourscript.pl?PageID=/etc/passwd or similar? Never trust user input. You should always check what data is being fed into your scripts. Regexes (re module) is what you need here. Michael On Tue, 9 Jul 2002, SA wrote: > Ok. I 'hacked' at the code for awhile and have finally figured it out. For > anyone that wants to see the results, check my test program below: > > On 7/9/02 11:51 AM, "SA" wrote: > > #!/sw/bin/python > > import cgi > import cgitb > > cgitb.enable(display=0, logdir="/Users/montana/Temp") > > QueryString = cgi.FieldStorage() > for pageID in QueryString.keys(): > QValue = QueryString['pageID'].value > body = open(QValue, "r") > for line in body.readlines(): > print "Content-Type: text/plain\n\n" > print line > body.close() > > print "Finished!" > > The line in the testtext file is of course "Hello World!" So clicking the > Test link on the first webpage sends the querystring (filename of the text > file) to the python cgi script, and the script translates the data and > displays the following on a new web page: > > Hello World! > Finished! > > So everything is groovy now and I can start developing my own website. > Thank You all for your help. > > Thanks. > SA > > > -- -------------------------------- n i n t i . c o m php-python-perl-mysql-postgresql -------------------------------- Michael Hall ninti at ninti.com -------------------------------- From nospam at dsl.pipex.com Mon Jul 8 19:08:37 2002 From: nospam at dsl.pipex.com (Simon Foster) Date: Mon, 08 Jul 2002 23:08:37 GMT Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> Message-ID: <3d2a1b18.94448820@news.dsl.pipex.com> On 06 Jul 2002 02:16:55 -0700, Paul Rubin wrote: >I found Simon Foster's nice little SNTP client on the ASPN Cookbook >site and adapted it to set the hardware clock under Linux: > > http://www.nightsong.com/phr/python/setclock.py > >I find it pretty useful for adjusting my computer clock every >now and then, without the hassle of setting up a real NTP system. GEE Thanks! -- Simon Foster Cheltenham England From pecora at anvil.nrl.navy.mil Sun Jul 21 09:54:31 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Sun, 21 Jul 2002 09:54:31 -0400 Subject: A better self References: Message-ID: <210720020954312190%pecora@anvil.nrl.navy.mil> In article , wrote: > I guess I don't understand what you mean - in my mind the two are > independent. For example, if you're bothered by typing 'self.' then bind > that text to a hotkey, e.g. Ctrl-s. Yep, did that. I use "_" in place of self. >The benefit doesn't depend on your > coding style that much. If readability is your gripe, change the syntax > highlighting to make 'self.' be lighter (so it doesn't jump out as much). Can't do that on the current IDE. No syntax highlighting. -- Lou Pecora - My views are my own. From spenrose at intersight.com Wed Jul 17 17:09:07 2002 From: spenrose at intersight.com (Sam Penrose) Date: Wed, 17 Jul 2002 14:09:07 -0700 Subject: pickle performance on larger objects Message-ID: <6EB49C1A-99C9-11D6-A291-003065B33450@intersight.com> On a recent project we decided to use pickle for some quick-and-dirty object persistence. The object in question is a list of 3,000 dictionaries whose keys and values are short (< 100 character) strings--about 1.5 megs worth of character data in total. Loading this object from a pickle using cPickle took so long we assumed something was broken. In fact, loading is just slow. A list of 10,000 identical dictionaries whose keys and values are short strings takes many seconds to load on modern hardware. Some details: i. A python process which is loading a pickle will use a lot of RAM relative to the pickle's size on disk, roughly an order of magnitude more on Mac OS X. ii. Performance appears to scale linearly with changes in the size of the list or its dicts until you run out of RAM. iii.Python pickle is only about 5x slower than cPickle as the list gets long, except that it uses more RAM and therefore hits a big RAM-to-diskswap performance falloff sooner. iv. You *can* tell a Mac's performance by its MHz. An 800 MHz PIII running Windows is almost exactly twice as fast as a 400 MHz G4 running Mac OS X, both executing the following code from the command line. With 25 items in the dictionaries and 10K dicts used, the former took just under a minute using cPickle, the latter two minutes. v. Generating a list of 3K heterogeneous dicts of 25 items (our real data) by reading in a 750k text file and splitting it up takes on the order of a second. Sample run on 400 MHz G4, 448 megs of RAM: >>> time_cPickle_Load() dumping list of 10 dicts: dumped: 0.00518298149109 loading list of 10 dicts: loaded: 0.1170129776 dumping list of 100 dicts: dumped: 0.0329120159149 loading list of 100 dicts: loaded: 0.849031090736 dumping list of 1000 dicts: dumped: 0.397919893265 loading list of 1000 dicts: loaded: 8.18722295761 dumping list of 10000 dicts: dumped: 4.42434895039 loading list of 10000 dicts: loaded: 133.906162977 #---code follows----------------// def makeDict(numItems=25): d = {} for i in range(numItems): k = 'key%s' % i v = 'value%s' % i d[k] = v return d def time_cPickle_Load(): import time now = time.time from cPickle import dump, load filename = 'deleteme.pkl' for i in (10, 100, 1000, 10000): data = [makeDict() for j in range(i)] output = open(filename, 'w') startDump = now() print "dumping list of %s dicts:" % i dump(data, output) print "dumped:", now() - startDump output.close() input = open(filename) startLoad = now() print "loading list of %s dicts:" % i x = load(input) print "loaded:", now() - startLoad input.close() From eric.brunel at pragmadev.com Mon Jul 29 04:03:35 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 29 Jul 2002 08:03:35 +0000 Subject: pickling problems with Pmw/Tkinter References: Message-ID: Don Arnold wrote: > I'm trying to develop a Tkinter app that pickles the values of a couple of > Pmw counters. Then on its next run, it unpickles these values and loads > them back into the counters. That's the plan, anyway. Here's what I have: > [snip code] > self.bind('',self.shutdown) First: why do you make your app class inherit from Frame? I've seen many people doing that and I can't understand why. There are many things you can do on an actual window (in Tkinter words a Toplevel) that you just can't do on frames: "regular" menubars, specific events for windows, and so on... So I would make app inherit from Tk or Toplevel and do the following: self.protocol('WM_DELETE_WINDOW', self.shutdown) This may solve the problem. In fact, with the binding on , I suspect the contained widgets to be destroyed *before* the binding is called. So the Pmw counters in your _minwordlen and _maxwordlen attributes may already have been destroyed. However, why no exception is raised is a mystery... If you do it that way, put also a self.quit() in your shutdown method or the window won't close. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From cliechti at gmx.net Sat Jul 20 15:23:57 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jul 2002 21:23:57 +0200 Subject: unloading imported modules References: Message-ID: xeon at dacreations.cjb.net (xeon) wrote in news:c21a43ff.0207201104.634f353b at posting.google.com: > Is it possible in python intepreter to unload imported modules? or are > there ways to refresh the loaded functions if ever the module is > updated, other than restarting the intepreter? you can use "reload(modulename)" to refresh it. maybe autoreloading interests you too. here comes the little bit log URL.... (one line, blah balh ;-) http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf- 8&th=2ae8aac3beeb9859&seekm=mailman.1005899002.5050.python- list%40python.org&frame=off chris -- Chris From emile at fenx.com Thu Jul 4 20:22:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 05 Jul 2002 00:22:48 GMT Subject: Math irregularity ... is this normal? References: Message-ID: Some One Else > >>> 2/5.0 > 0.40000000000000002 > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp -- Emile van Sebille emile at fenx.com --------- From giovannic75 at nospam.yahoo.it Sun Jul 28 05:26:58 2002 From: giovannic75 at nospam.yahoo.it (giovanni) Date: Sun, 28 Jul 2002 09:26:58 GMT Subject: connection problems Message-ID: Hello. In these days I am finding some problems in reaching www.python.org. Is it just a problem of mine or what? Is the site under maintenance? thanks in advance Giovanni From gerhard.haering at gmx.de Wed Jul 10 00:39:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 10 Jul 2002 06:39:19 +0200 Subject: Learning how to program... but what's the best way? In-Reply-To: <3D2BB54C.90500@earthlink.net> References: <3D2BB54C.90500@earthlink.net> Message-ID: <20020710043919.GB2895@lilith.my-fqdn.de> * Hans Nowak [2002-07-10 04:17 +0000]: > To give an idea of what I have in mind: A good start could be, for example, > some kind of game that can be scripted in Python, and therefore extended at > will. Sounds difficult. I'd start with something simple. And in fact when I was at that age, and learnt languages like C, C++ and Modula-2, the first programs I wrote were always Tic-Tac-Toe (very simple) and Number Mind. Tic-Tac-Toe should be easy enough to start with. And both of them can be programmed with a simple text-mode interface (print and raw_input), without requiring a GUI. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From shalehperry at attbi.com Tue Jul 30 11:00:53 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 30 Jul 2002 08:00:53 -0700 (PDT) Subject: condensed syntax? In-Reply-To: <3D465FC5.3DE7DEA4@gemini.edu> Message-ID: On 30-Jul-2002 Matthieu Bec wrote: > > > is there any way to condense the following: > > # scan subdir(s) within mydir > for d in os.listdir(mydir): > dd=os.path.join(mydir,d) > if os.path.isdir(dd): > self.subdir.append(dd) > > > what follows doesn't work, but I'm thinking of a something like: > > self.subdir=[(os.path.isdir(dd=os.path.join(mydir,d))?dd:pass) for d in > os.listdir(mydir) ] > so we find a way to kill the join(). oldwd = os.getcwd() os.chdir(mydir) self.subdir = filter(os.path.isdir, os.listdir('.')) os.chdir(oldwd) I like to use filter here because it is concise and portable across python versions. From boud at valdyas.org Thu Jul 18 08:29:33 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 18 Jul 2002 14:29:33 +0200 Subject: Problem with installing PyQt! References: Message-ID: <3d36b8ff$0$12308$e4fe514c@dreader4.news.xs4all.nl> zhao wrote: > Hi, > Thanks for your help. I run "python setup.py install" in > c:\python22\tools\idle and it install the library in "build\lib\idlelib" > and "build\lib\idlelib\Icons", but a Error appears: > file 'idle' does not exist. What happened? > Why should we run the command "python setup.py install"? > Can you write the process step by step? (sorry) > I try to convert .ui file into .py using 'pyuic example.ui -o example.py', > but an empty file was generated. why? > I am not sure how PyQt should be installed on Windows nowadays -- it's been about half a year since I last touched a Windows computer -- but I am sure you are installing from the wrong directory. Idle is part of Python proper -- you should run "python setup.py install" using the setup.py file in the pyqt directory instead -- the directory where you unpacked the PyQt zipfile. -- Boudewijn Rempt | http://www.valdyas.org From zopestoller at thomas-guettler.de Thu Jul 4 06:38:15 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 04 Jul 2002 12:38:15 +0200 Subject: Tuples --> How to use them ? References: Message-ID: <3D242597.3030601@thomas-guettler.de> Marcus Vinicius Laranjeira wrote: > All, > > Supose I have an arbitrary tuple of values that came from a sql query. I > need to run this algorithm: > > t1 <-- new tuple > t1 <-- results from an arbitrary query > l <-- new list > for each value in the tuple do: > a <-- new tuple > add this value to the tuple a > add the tuple a to a the list l > > i.e. I need to create a list of tuples and these tuples will have one, > and only one, number that came from the original tuple. > > Does anyone know how do I do that !? #creating new tuple is not necessary t1=query() l=[] for value in t1: l.append([value]) thomas From marklists at mceahern.com Fri Jul 12 16:35:53 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 15:35:53 -0500 Subject: switch recipe? In-Reply-To: <1026504892.3407.40.camel@software1.logiplex.internal> Message-ID: > Or you could just change it to (untested): > > def make_color_switch(color1, color2): > def color_switch(): > i = 0 > while True: > if i: > yield color2 > else: > yield color1 > i = not i > return color_switch Nice. I guess I'm still not too worried about n maxing out. Don't ints just spill into longs go on forever? Nevertheless, for the generic loop, your suggestion makes me realize we can just dispense with n altogether: def make_loop(*args): """Return a generator that loops through args.""" if not args: raise RuntimeError("Missing parameter: args.") def loop(): i = 0 while True: i = i % len(args) yield args[i] i += 1 return loop This way, the counter never gets bigger than len(args). // m - From shagshag13 at yahoo.fr Wed Jul 24 13:37:07 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 24 Jul 2002 19:37:07 +0200 Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: "Fredrik Lundh" a ?crit dans le message de news: twB%8.673$HY3.188327 at newsc.telia.net... > Alex Martelli wrote: > > > BTW, GvR claimed (less than a month ago on the python-dev list) > > that having an integer argument to readlines was a design error. > > except that he was talking about "readline", not "readlines". so using it like i use it, is ok ? (even if it's over complicated). > (does anyone here even know that readline takes an optional > integer argument, and what it does? ;-) not me. s13. From roy at panix.com Mon Jul 15 08:04:40 2002 From: roy at panix.com (Roy Smith) Date: Mon, 15 Jul 2002 08:04:40 -0400 Subject: isA function? References: Message-ID: "Delaney, Timothy" wrote: > Why would this be bad? Presumably you are testing that the returned objects > have specified semantics. What does it matter if the returned objects are > all of the same type or not - what is important is what happens when you use > them. If the API says "foo() returns an object of class bar", then "isinstance (foo(), bar) is true" is indeed part of the specified semantics. From tebeka at cs.bgu.ac.il Sun Jul 21 06:30:20 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 21 Jul 2002 03:30:20 -0700 Subject: Q: indent settings for Python C style (pep 7) Message-ID: <33803989.0207210230.6b9ec0c3@posting.google.com> Hello All, I recall seeing settings for indent (http://www.gnu.org/software/indent/) to make it produce pep-7 compatible code. Can't find it now. Any pointers? Thanks. Miki. From romberg at smaug.fsl.noaa.gov Fri Jul 5 20:02:28 2002 From: romberg at smaug.fsl.noaa.gov (Mike Romberg) Date: 05 Jul 2002 18:02:28 -0600 Subject: Scope trouble with __init__.py Message-ID: This is a copy of what I entered into the sourceforge bugtracker... I think that there is a small problem with what gets imported into the scope of an __init__.py module with a package. At least if this is the correct behavior it seems a bit funny to me. Consider the following modules located in a subdirectory of the load path called spam: spam/ -------- spam/__init__.py --------------- a = 1 from b import c print "a = ", a -------- spam/b.py ------------------- c = 2 import a --------- spam/a.py ----------------- d = 3 I would expect that when one imported the spam package, you would see 'a = 1' displayed. Instead you get 'a = '. So, it seems that python pulled in the 'a' symbol from b and overwrote the one already in __init__. This would make sense if __init__ did a 'from b import *'. But I think the current behavior might be a bug. Mike Romberg (romberg at fsl.noaa.gov) From loewis at informatik.hu-berlin.de Mon Jul 22 07:59:51 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 22 Jul 2002 13:59:51 +0200 Subject: Failure to set locale References: Message-ID: david at forestfield.co.uk (David Hughes) writes: > As a fairly-newbie, I'm trying to use the locale module for the > first time, using Python 2.2 under Win2k. If I call locale.setlocale > with a locale of 'de' for Germany or 'es' for Spain, I get "Error: > locale setting not supported". Right, you have to use 'german' on Windows; apparently abbreviations are accepted as well. > However, if I use 'ge' and 'sp'(which aren't the ISO approved > names), the correct locale is set. No argument to setlocale is ISO-approved. Python inherits setlocale from ISO 9899 (ISO C), not from any other ISO standard. In ISO 9899, the valid arguments for setlocale are specifically documented as implementation-defined. > The only way I can get the locale set for Denmark is to actually > change the region in Windows' Control Panel. Try "danish", or "danish_Denmark.1252", if you want the full locale name. > Can anyone suggest what's going wrong, please? You are passing unsupported locale names to setlocale. Regards, Martin From cbbrowne at acm.org Thu Jul 18 16:05:24 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 18 Jul 2002 20:05:24 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: In the last exciting episode, pinard at iro.umontreal.ca (Fran?ois Pinard) wrote:: > [James Kew] > >> Should I feel guilty for not learning lex/yacc? > > No. These are for C programmers, and you should not have to program C to > be happy! However, if you live in a Python world, it is not bad that you > put a similar Pytonish tool in your pocket, one of these days! C programmers should. (Feel guilty :-).) Python programmers should only feel guilty if they don't know something about analagous things like TPG or YAPP or such. -- (reverse (concatenate 'string "gro.mca@" "enworbbc")) http://cbbrowne.com/info/sap.html Philosophy: unintelligible answers to insoluble problems. From chris.lyon at spritenote.co.uk Tue Jul 2 07:56:47 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Tue, 2 Jul 2002 12:56:47 +0100 Subject: Simple Conceptual Pickling problems References: <3d217732$0$4276$afc38c87@news.easynet.co.uk> Message-ID: <3d2194c1$0$4280$afc38c87@news.easynet.co.uk> > > SystemError: Failed to import class Programme from module __main__ > > This is the hint. The module's name when the pickle was created was > __main__, which only happens when the module is not imported, but is run > directly. You need to pickle and unpickle from within the same context, > eg, use import in both cases. > > HTH, > Emile van Sebille > emile at fenx.com So , if I understand you, Because I ran the original code using the Pythonwin environment, I produced the objects in module __main__ NOT in the module I though they were being created in ( in my case a module called octavia which contains the class Programmes). When I then ran with my test module, which imported octavia, The Unpickle process believed it was trying to unpickle objects defined in __main__ NOT from within octavia ? So should I then have a module 'above' my octavia module which will import octavia for it to work? Chris From mwh at python.net Mon Jul 29 05:41:14 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Jul 2002 09:41:14 GMT Subject: Guide to the python interp. source? References: Message-ID: "Tim Gahnstr?m /Bladerman" writes: > I noticed, but thought that I just had missed it. I thought there > must be some where for such a large project. But the problem is > ofcourse ever present, "nobody likes to do documentation" Python has masses of documentation, but most of it is aimed at Python programmers, not people who want to hack on the core... > > > Things I want to change is for example, everything should be "call by > > > refferense", > > That may be very hard. If you want things like this: > > > > def f(x): > > x += 1 > > > > i = 2 > > f(i) > > i --> 3 > > > > then you have problems. > > That is exactly what I want to have, that is more intuitive I think and I > don't think it must be that hard either. I don't want to get into an argument with you -- but you're wrong ;-) Have a look at this page I wrote a while's back: http://starship.python.net/crew/mwh/hacks/objectthink.html which explains how Python's object work -- I don't think you can make call by reference work without changing this model, and then you don't have Python any more. FWIW, the way Python objects work is very similar to Lisp and Scheme (and just similar to Java). Cheers, M. -- MAN: How can I tell that the past isn't a fiction designed to account for the discrepancy between my immediate physical sensations and my state of mind? -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From K.Rdt at TU-Berlin.DE Mon Jul 1 06:29:56 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Mon, 01 Jul 2002 12:29:56 +0200 Subject: wxFont-question Message-ID: --------------------------------------------------------------------- Hi I want to change the font to equal letters, but without success. K at Rdt --------------------------------------------------------------------- #********* So 30.06.02 17:45-1 ************** . . . . . . . . r 2 . p y w */ from wxPython.wx import * from wxPython.lib.infoframe import * #============================================ . . . . . . . . . . . . . . */ class MyFrame(wxFrame): def __init__(self,output): wxFrame.__init__(self,None,-1,"Close me...",pos=(0,110),size=(300,100)) .. def OnClose(self,event): .. def OnTimer(self, evt): .. print "--------------------------------------------------------------" f=wxFont(22,wxMODERN,wxNORMAL,wxNORMAL,1,"","") print "--------------------------------------------------------------" ### NO CHANGE From tim.one at comcast.net Sun Jul 21 01:50:34 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 21 Jul 2002 01:50:34 -0400 Subject: Dict in binary pickle causes exception In-Reply-To: <3D38AD65.98564CB7@cosc.canterbury.ac.nz> Message-ID: [greg, on MacPython 2.2] > When I try to unpickle a pickle containing a dictionary > that was written in binary format, I get the following > exception: > > TypeError: dict objects are unhashable > > The same thing happens whether I use pickle or cPickle > to do the unpickling. It's much more useful to show code than to try to describe. Here: Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cPickle >>> d = {1: 2} >>> s = cPickle.dumps(d, 1) >>> cPickle.loads(s) {1: 2} >>> >>> import pickle >>> s = pickle.dumps(d) >>> pickle.loads(s) {1: 2} >>> No problems for me. Show us what you do that fails. From b.maryniuk at forbis.lt Thu Jul 11 03:47:48 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 09:47:48 +0200 Subject: j2ee and python and evil competitors In-Reply-To: References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: <200207110947.48216.b.maryniuk@forbis.lt> On Wednesday 10 July 2002 21:32, Steve Menard wrote: > See, this is something I really don't understand. To fix this, please refer to the RFC standards and ISO numbers. As You see, no one for M$ Word. > I will agree that PDF or > html would have been a better choice, Sure. > but not everyone can generate PDF ya know. Are Your current OS is MS-DOS? Well, it easy cured by UNIX, AFAIK... -----------8<--------- X-Newsreader: Microsoft Outlook Express 6.00.2600.0000 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000 -----------8<--------- Oh... Sorry... DOS-*SHELL* AKA MS Windows...... So You should look at Adobe Distiler or ps2pdf or GhostScript or just visit http://freshmeat.net and search for PDF creation. Anyway, anybody can generate / export / create HTML. > With this kind of attitude, we'll forever be regarded as the > extremists who won't listen to anything .... No. No. No. Just FORWARD BACK to the sender the document you get from the net. This cures easily with procmail: just if attachment contains DOC, forward back to the sender with letter a'la: "Hi.\nIt would be nice get a PDF or HTML instead Microsoft DOC.\n\nThank You, much. Bye.\n\n". Steve, if somebody do wrong, *YOU* do right: create PDF or HTML instead of DOC. P.S. In other hand there is no ISO for PDF... ;-) P.P.S. Maybe UNIX world should enforce the rest folk to use OpenOffice or StarOffice by sending them SXW format? -- Sincerely yours, Bogdan M. Maryniuck Linux: Because a PC is a terrible thing to waste. (By komarimf at craft.camp.clarkson.edu, Mark Komarinski) From aleax at aleax.it Wed Jul 10 11:14:29 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 15:14:29 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> <3D2C4CE1.C4E85A07@tds.net> Message-ID: Edward K. Ream wrote: ... >> def makeCallback(self, val): >> def callback(): return self.myCallback(val) >> return callback > > I tried this, and indeed this does work on 2.2. Really. Thanks very > much. You're welcome! > This "extra" level of indirection is needed. The following does not > work: > > for val in vals: > callback=lambda: self.myCallback(val) # or (val=val) > b = Tk.Button(..., command=callback) > > All the callbacks get bound to a function with the last val in vals. I > have no idea why. Maybe you could explain? Sure. You need to "snapshot" the value of val at the moment you're interested in it -- passing it as an argument is one way to do that. In the for loop that you show, the use of val in: callback=lambda: self.myCallback(val) indicates the variable thus named in outer scope (or global scope), and the relevant value is the one that said variable has _when the lambda is later called_ -- by what time the loop has proceeded to the end and val has stayed bound to the last value. BTW, the for loop using: callback = lambda val=val: self.myCallback(val) should work just fine -- now you're "snapshotting" again (passing val as an argument, so the value that matters is here the one at *function-definition* time, as in the "extra level of indirection" case that I suggest, NOT the value at *function-call* time in the outer or global scope). I consider the use of makeCallback preferable for stylistic reasons, although it does also have the desired snapshot effect -- the latter could also be obtained in other ways. > BTW, the reason I really like Python is that someone like me with > limited knowledge can actually produce some real work. Anyway, thanks > again for your help! Again you're welcome, and I share your evaluation of Python -- a full grasp of the nicer points helps, but for 99% of one's work one can do almost as well without it!-) Alex From aahz at pythoncraft.com Mon Jul 29 15:31:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2002 15:31:13 -0400 Subject: Python design failures (was Re: Let's Talk About Lambda Functions!) References: <3d455445_9@news.newsgroups.com> <3d457011_1@news.newsgroups.com> Message-ID: In article <3d457011_1 at news.newsgroups.com>, JB wrote: >Aahz wrote: >> >> If you're using backticks frequently, you're probably not programming >> Pythonically. There's already repr() to produce the same result as >> backticks, and backticks have the problem that in many fonts they're >> nearly indistinguishable from single quotes. > >I do not understand this. I use __repr__ *and* backticks. >For example > >class AnyClass: > defr __repr__(self): > ... > >a = AnyClass() >myfile.write(`a`) You should use myfile.write(repr(a)) It's much clearer that you're *NOT* doing myfile.write('a') Yes, the Python std lib has backticks in it. Cleaning that up would likely be the first step toward deprecating backticks. In any event, backticks will certainly be available at least until Python 3.0. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From printers at sendme.cz Sat Jul 27 10:51:25 2002 From: printers at sendme.cz (A) Date: Sat, 27 Jul 2002 16:51:25 +0200 Subject: How to redirect output to browser Message-ID: <3D42CF8D.9280.1C2E23@localhost> Hi, Is it possible to send output continuously to a web browser?. For example I have the following code >>> import httplib >>> h = httplib.HTTP('www.cwi.nl') >>> h.putrequest('GET', '/index.html') >>> h.putheader('Accept', 'text/html') >>> h.putheader('Accept', 'text/plain') >>> h.endheaders() I would like to send coming bytes ( here coming bytes of /index.html file) directly to web browser in the same way as I use a web browser on my computer to open a webpage where I can see a progress how webpage is being opened. In other words I do NOT want to wait for downloading the whole file and only after that open that downloaded file in a web browser. Thank you for help Ladislav From emile at fenx.com Sat Jul 20 09:51:04 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 20 Jul 2002 13:51:04 GMT Subject: Python 2.3 References: Message-ID: "David LeBlanc" wrote in message news:mailman.1027118746.7853.python-list at python.org... > True Division? Darn it, i'm used to false division! Where is "to __past__ > deport ..."? ;-) > or maybe exile ;-) -- Emile van Sebille emile at fenx.com --------- From laurent.szyster at q-survey.be Tue Jul 30 13:45:11 2002 From: laurent.szyster at q-survey.be (Laurent Szyster) Date: Tue, 30 Jul 2002 17:45:11 GMT Subject: Good XML tools? References: Message-ID: <3D46D1B5.248A2921@q-survey.be> Gillou wrote: > > I know that plaiying with pyXML is a mess for newbies because of its > lack of good documentation. But PyXML is always said to be in beta > status. And allways will be. Python is not the right language to write XML libraries: it's way too slow. > If you're on a Win32 platform and don't care about portability, you > can play with MSXML 4.0 that's a full featured, fast and fully > documented XML suite. Examples are mainly in VBS or JavaScript but > easily translatable to Python. And for Linux there are Python bindings for libxml and libxslt. See: http://xmlsoft.org/ and http://xmlsoft.org/XSLT/ In many case (if not most) XML processing is far easier with a dedicated language like XSLT. Use Python to generate XML and/or XSLT, but don't use it to transform XML: XSLT is far better at it. Laurent Szyster From spam at ob_scure.dk Sun Jul 7 06:17:10 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 12:17:10 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: <3D281526.6000007@ob_scure.dk> Matt Gerrans wrote: > BCB is great -- and you can still use it for the performance-critical areas > by creating COM Automation servers which are a snap to call from Python. > One of the great things about Python is that it works well with C/C++ so > that you can eat your cake and have it too. I'll consider it, however I don't want to rely too much on COM, in case we'd migrate to some Unix flavour some day. Maybe I'll look into writing some of the algoritms as C modules, but I'm not sure it's worth it (see below). >>The goals of the rewritten piece of software would be: >>* Improved speed > > Python is not going to help in this area, unfortunately, unless you are > talking about improved speed of development! ;-) Yes and no. In my estimate, the primary reason for the slowness of the current job is inefficient dataaccess and datahandling. A few examples: * Using "SELECT TOP 1 value FROM T_MyTable ORDER BY value DESC" to get maximum value. * linear seraches * LOTS of SQL calls returning only oe row When the job was originally written a lot of factors were not known and, well, it did it's job. However now the amount of data requires better performance. >>* Improved scalability - parallel processing on multiple machines/CPUs > > This might be more easily accomplished with Java, depending on exactly how > you intend to implement it. Java is probably the best tool for distributed > processing; in particular JINI is ideal for this kind of thing. I Don't know much Java I must admit. However for my needs I belive XMLRPC will do just fine. I've looked a little into DCOM and, while I won't use it, I must admit I like the idea of having the component automatically instiantiated on the remote machine instead of having to have a running server. Hmm, if only Windows had inetd. >>* Improved scalability - ability to handle greater databases (>1gb) > > This is probably more dependent on your design than the language or platform > you choose. Yes, but I also think that Python makes it easier to get the design right. >>Now, instead of rewriting the job in C++, I'd (of course) like to use > Python. > > Naturally! :-) >>However the CEO (small company, told you :-), made a couple of somewhat >>valid points against it. >>1) He was worried about getting a replacement devlopper in case I left. > > I don't think that is a problem at all, these days. I think Python > developers are becoming pretty ubiquitous. On top of that, any experienced > programmer can learn Python in a snap -- it is so engaging that it is fun > and quick to learn. I'm happy so many people seems to think that, last week I sent a Python example to one of my co-workers and he picked it up immediatly (he's a VB/ASP devloper with a little C++ knowledge). When told about it, most people are somewhat sceptic about using indentation for program structure (funny, it seems to be the same people that never indent their code out of lazyness or whatever ;-). However when they see an actual program, most realize how beneficial it is. >>2) He said, "Name 3 companies using Python for key functions" > > I'd bet *every* company in the Fortune 500 uses Python for one thing or > another, whether they know it or not. Many are probably using it for very > important functions; they just don't advertise it. Why should they -- > their business is not about explaining how they accomplish every task, it is > about doing it. I have developed Python code for one of the largest of > them that is very key to their business, but I doubt that the CEO would know > of it or that the company would tout this fact -- what they care about is > creating and selling thier products. And that's what they should care about I guess. It's funny how it works isn't it. Our CEO is very worried about all this Open Source stuff (be it Python, Linux, *BSD, MySQL, whatever). The problem is not the free as in speach - it's the free as in beer. Many people simply can't belive that something that is gratis can be any good (which is probably a good rule of thumb when speaking of material goods like books and such, just not software). Beeing able to buy MySQL might actually be the convincing factor. [snip] > I think the most compelling argument you can come up with is to write a demo > in Python that works on a subset of the data, as you mentioned above. The > speed with which you can develop and the quality of the code you develop > will be the biggest selling factor. I'm doing it as we speak, shuldn't take long :-) > Be aware that your demo could also convince you that Python is not the right > tool for the job as well. Python is a great tool, but it is not the best > tool for *every* task. I belive it's the perfect tool for this case, but if it's not, it's better to find out now i think. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From tim at bladerman.com Mon Jul 29 04:29:41 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Mon, 29 Jul 2002 08:29:41 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com><_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: "Terry Reedy" skrev > "Tim Gahnstr?m /Bladerman" wrote in message > news:bxX09.1437$HY3.398059 at newsc.telia.net... > > ask a complete novice what he think this peace of code will do > > > > #Here is the program > > x=3 > > inc(x) > > print x > > > > #Bellow is al the function deffinitions > > def inc(x): > > x= x+1 > > Your example is deceptive and biased because you use the same name for > the global and local vars, which is known to be confusing to complete > novices, let alone those with more experience. They will tend to > think that they are the same thing and give the wrong answer on the > basis of that misconception. Much better is > > def inc(temp): > temp = temp+1 > > > You might have to tell him about assignment but not much else for > him to > > understand that this program will print 4 > > I tried your experiment with my wife, who is not even a novice w/r/t > computer programming. She first refused to answer. When she Hmm, Okey. Now we are running two discussions in paralell. One about if it is possible and one about if it is good. Maybe I am wrong in both cases, the first case is getting to seem obvious but I am not really convinced yet about the second. I will have to sit down and think it over a little. But either reason is enough for me to drop the feature. There is actually a third reason to drop it that I have had in my mind since I started. It is good to have it much similar to how most languages work today, namely by CBV. By the way, I won't even dare to tell you guys about the mess I have thought out for the way I intend to handle objects, classes and imports :-) The thesis is not about making a CBR language but make an IDE with debugger for a language suited for novices. Tim From gherman at nospam.com Wed Jul 17 06:53:41 2002 From: gherman at nospam.com (Dinu Gherman) Date: Wed, 17 Jul 2002 12:53:41 +0200 Subject: SVG viewer in python? References: Message-ID: <20020717125620756+0200@news.t-online.de> In gb at cs.unc.edu wrote: > > Does anyone know of an open source SVG viewer written in Python? I'm > working with some students on a project to make SVG drawings (maps in > particular) accessible to visually impaired students. I'm not aware of an entire SVG viewer (that would be challenging, I guess). I know that Sketch has some SVG support and I recently wrote some SVG import and export filters myself for those using the Reportlab Graphics library. See also the online SVG demo below (last link). Regards, Dinu http://sketch.sourceforge.net/ http://www.reportlab.com/ http://www.reportlab.com/extensions.html http://www.reportlab.com/cgi-bin/graphics_demo.cgi From johnmc at velseis.com.au Thu Jul 11 19:54:16 2002 From: johnmc at velseis.com.au (John McMonagle) Date: 11 Jul 2002 16:54:16 -0700 Subject: Pmw.Counter and Pmw.ScrolledCanvas questions References: <18692175.0207102141.1d5279c1@posting.google.com> Message-ID: <18692175.0207111554.4f09fac@posting.google.com> > As for the ScrolledCanvas are you using the .scale() canvas method. If so > the call looks somthing like > > mycanvas.scale("ALL", xorigin, yorigin, xscale, yscale) > > and setting xorigin and yorigin to the top left points from you 'zoom box' > should do what you want, to get those I would bbox the rectangle I guess you > are drawing when they do the button-3-press-move-release dance. Oh and don;t > forget to call resizescrollregion() after zooming. > > This is an example that seems to work (for me!) Thanks for those suggestions Martin. Unfortunately I'm not using the scale method to zoom. I actually need to redraw all the canvas objects because I'm mapping canvas xy coords to eastings/northings on a map. So, from the size of the zoom box I calculate a new scale factor at which to draw my map, I draw my map, then I want the canvas to be scrolled to the point where the zoom box began. What I've got now is my map is correctly drawn after the zoom box drag but it's starting position is at the top left of the scrolled canvas. After drawing items on a scrolled canvas and resizing the scrolled region how do you programatically scroll the canvas to a desired point. Any ideas ? From jdhunter at nitace.bsd.uchicago.edu Sun Jul 28 11:49:56 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sun, 28 Jul 2002 10:49:56 -0500 Subject: How to detect the last element in a for loop References: Message-ID: >>>>> "Tom" == Tom Verbeure writes: Tom> Hello All, Tom> I often have the case where I need to loop through a bunch of Tom> elements, but do something special on for the last line of Tom> code. What about the good, old fashioned index? To my eyes, it is very readable N = len(seq): for i in range(N): do_something(seq[i]) if i==someVal: do_something_else(seq[i]) It's not really that god awful is it? Also, for the example you posted, you can use string.join.... import string seq = range(10) s = string.join(map(str, seq), ', ') Cheers, John Hunter From sadams123 at optushome.com.au Thu Jul 11 22:51:22 2002 From: sadams123 at optushome.com.au (Steven) Date: Fri, 12 Jul 2002 12:51:22 +1000 Subject: window icons in Tkinter Message-ID: <3d2e442c$0$11264$afc38c87@news.optusnet.com.au> Can anyone shed some light on how to get the root window to use an icon other than the 'Tk' symbol? I can't seem to find an example of this anywhere thanks Steven From chris.gonnerman at newcenturycomputers.net Thu Jul 11 08:28:25 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 11 Jul 2002 07:28:25 -0500 Subject: COCOMO - appropriate for languages like Python? (fwd) References: <200207102307.g6AN72822540@panix1.panix.com> <3D2D779D.D988C6F0@mitre.org> Message-ID: <006d01c228d6$753f72c0$0101010a@local> ----- Original Message ----- From: "Mike Brenner" To: "aahzpy at panix.com" Sent: Thursday, July 11, 2002 7:18 AM Subject: Re: COCOMO - appropriate for languages like Python? (fwd) > Hi aahzpy! > > I am very interested in this problem, and would like to help, but I don't know what you mean. > > I viewed this message in textpad, microsoft word, wordpad, and netscape 4.79, and the two paragraphs below look the same. All four of those programs (well, I'm not sure about textpad) auto-wordwrap. So does Outlook Express, for that matter, and newer Mozilla and Netscape 6 releases. 'aahzpy' is using a mailreader which does not, probably a console or terminal-mode program. Here's a ruler for you. You need to be using a monospace font for this to be useful; I generally use Lucida Console. 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 I use Outlook Express, but I've learned to cut my lines off short by pressing enter (end-of-paragraph to the MS software listed) so that I don't get this kind of complaint often. I do run over 80 columns sometimes by accident... Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From boud at valdyas.org Tue Jul 9 05:39:23 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Tue, 09 Jul 2002 11:39:23 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <3d2aafce$0$94901$e4fe514c@dreader3.news.xs4all.nl> Bo M. Maryniuck wrote: > You know, that's funny. :)))))) > > On Tuesday 09 July 2002 01:18, curt finch wrote: >> Issues and concerns >> ? No integrated GUI (Graphic user interface) support. > wxWindows, anygui, Tk, GTK+, QT, fwm and Windoze resources. Did somebody > can make Java soft with... QT or wxWindows widgets? No?!.. > Er, yes. Somebody could: there's qtjava. -- Boudewijn Rempt | http://www.valdyas.org From deltapigz at telocity.com Wed Jul 3 15:25:56 2002 From: deltapigz at telocity.com (Adonis) Date: Wed, 3 Jul 2002 15:25:56 -0400 Subject: REPEAT... UNTIL ? References: <3D234B96.7000704@gmx.de> Message-ID: <3d234fbd$1_1@nopics.sjc> how about the for loop? for x in range(100): print x Adonis "Ingo Linkweiler" wrote in message news:3D234B96.7000704 at gmx.de... > Hi, > > what do you think about adding "repeat .... until" to python syntax? > Often a "repeat-until" is better to use than a "while" loop. > Guido 8-) ??? > > Ingo > From mdehoon at ims.u-tokyo.ac.jp Tue Jul 23 03:19:24 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Tue, 23 Jul 2002 16:19:24 +0900 Subject: Almost got it References: Message-ID: <3D3D037C.6080301@ims.u-tokyo.ac.jp> Thank you all for your help. It almost works -- the source files get compiled and everything seems to be fine, up to the linking stage where two references (__imp___Py_NoneStruct and __imp__PyCObject_Type) are unresolved. These two are (I think) in python22.lib, which gcc seems to find, but somehow it can't find those two routines in it. I also tried to link them as c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -static --entry _DllMain at 12 -s build\temp.win32-2.2\Release\cluster.o build\temp.win32-2.2\Release\clustermodule.o build\temp.win32-2.2\Release\ranlib.o build\temp.win32-2.2\Release\com.o build\temp.win32-2.2\Release\linpack.o build\temp.win32-2.2\Release\cluster.def c:\python22\libs\python22.lib -o build\lib.win32-2.2\Pycluster\cluster.pyd -s to make sure it finds python22.lib, but with the same result. Any ideas? Sorry to bother you guys again. C:\cygwin\home\mdehoon\Software\Cluster>c:\\python22\\python setup.py build --compiler=mingw32 running build running build_py creating build creating build\lib.win32-2.2 creating build\lib.win32-2.2\Pycluster copying Pycluster\__init__.py -> build\lib.win32-2.2\Pycluster running build_ext building 'Pycluster.cluster' extension creating build\temp.win32-2.2 creating build\temp.win32-2.2\Release c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Iranlib/src -Ic:\python22\include -c cluster.c -o build\temp.win32-2.2\Release\cluster.o c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Iranlib/src -Ic:\python22\include -c clustermodule.c -o build\temp.win32-2.2\Release\clustermodule.o clustermodule.c:51: warning: `set_transposed_strides' defined but not used clustermodule.c:188: warning: `do_array_inout' defined but not used c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Iranlib/src -Ic:\python22\include -c ranlib/src/ranlib.c -o build\temp.win32-2.2\Release\ranlib.o c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Iranlib/src -Ic:\python22\include -c ranlib/src/com.c -o build\temp.win32-2.2\Release\com.o c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Iranlib/src -Ic:\python22\include -c ranlib/linpack/linpack.c -o build\temp.win32-2.2\Release\linpack.o writing build\temp.win32-2.2\Release\cluster.def c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -static --entry _DllMain at 12 -s build\temp.win32-2.2\Release\cluster.o build\temp.win32-2.2\Release\clustermodule.o build\temp.win32-2.2\Release\ranlib.o build\temp.win32-2.2\Release\com.o build\temp.win32-2.2\Release\linpack.o build\temp.win32-2.2\Release\cluster.def -L c:\python22\libs -lpython22 -o build\lib.win32-2.2\Pycluster\cluster.pyd -s build\temp.win32-2.2\Release\clustermodule.o(.text+0x74):clustermodule.c: undefined reference to `__imp___Py_NoneStruct' build\temp.win32-2.2\Release\clustermodule.o(.text+0x7c):clustermodule.c: undefined reference to `__imp___Py_NoneStruct' build\temp.win32-2.2\Release\clustermodule.o(.text+0x28da):clustermodule.c: undefined reference to `__imp__PyCObject_Type' collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 Delaney, Timothy wrote: >>From: Delaney, Timothy [mailto:tdelaney at avaya.com] >> >>python setup.py build --compiler-mingw32 >> > > python setup.py build --compiler=mingw32 > > Tim Delaney > > > From DavidA at ActiveState.com Tue Jul 30 13:54:43 2002 From: DavidA at ActiveState.com (David Ascher) Date: Tue, 30 Jul 2002 10:54:43 -0700 Subject: Python equivalent to 'which'? References: Message-ID: <3D46D2E3.4000008@ActiveState.com> Sean 'Shaleh' Perry wrote: > On 30-Jul-2002 Michael Gilfix wrote: > >> Seems like that might make a good convenience function in the >>os.path module. I'm sure many people have wanted such a function >>if they're using python for pure scripting. Perhaps you should try >>submitting a short patch...? Worst case, at least it'll get stored in >>the system. >> > > > I wrote that in about a minute and a half. > > Note it has a large assumption that PATH is defined and it is separated by > colons. This makes it only truly useful on a UNIX box. of course 'which' is a > UNIXism as well. My point is, the python library is for the most part OS > agnostic so I do not see this fitting in too well. > Doing 'which' right is actually fairly complicated -- Trent Mick has the best version I know of at: http://starship.python.net/~tmick/ """ GNU which is a common command line app on Unix. There are Windows ports (for example, the one in the Cygwin distribution), though I find the ones I have seen to be a little stupid. They don't understand the use of the PATHEXT environment variable. They don't support the useful '-a' option to listing all matches on the current PATH. This which has the following features: it is portable (Windows, Linux); it understands PATHEXT on Windows; it can print all matches on the PATH; it can note "near misses" on the PATH (e.g. files that match but may not, say, have execute permissions); and it can be used as a Python module. """ From jepler at unpythonic.net Wed Jul 3 10:34:14 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 3 Jul 2002 09:34:14 -0500 Subject: Thread safetyness in Python In-Reply-To: <20020703135851.GA73351@hishome.net> References: <20020703135851.GA73351@hishome.net> Message-ID: <20020703143408.GA32161@unpythonic.net> On Wed, Jul 03, 2002 at 09:58:51AM -0400, Oren Tirosh wrote: > The resolution is one bytecode operation so a+=1 is atomic but not a=a+1. > The list operations above are atomic. a+=1 is multiple bytecodes. Jeff From mrlogic at users.sourceforge.net Fri Jul 26 15:31:27 2002 From: mrlogic at users.sourceforge.net (Volker Cordes) Date: Fri, 26 Jul 2002 21:31:27 +0200 Subject: Developers needed Message-ID: <3D41A38F.2030106@users.sourceforge.net> Hi, I started a project on sourceforge that you might be interested in: Goal of the project is to develop a python plugin for eclipse (www.eclipse.org). At the moment the project is still in an early state. I have some pre-alpha sourcecode but I need help. So if you are interested and have some knowledge in programming java-classes you're welcome to join. Hope to see you, Volker From gleki at gol.ge Thu Jul 4 03:54:08 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Thu, 04 Jul 2002 09:54:08 +0200 Subject: newbie question on Fredrik Lundh's simple script References: <3D231402.81C0E715@gol.ge> <3D23A23B.5070400@nospam.free.fr> Message-ID: <3D23FF20.444DD764@gol.ge> Nec vicia nostra, nec remedia pati possimus... T. Livius laotseu wrote: > Giorgi Lekishvili wrote: > > > > Fredrik Lundh wrote: > > > > > >>John Boik wrote: > >> > >> > >>>Here is the problem. The frame pops up OK, but when I press the Quit button > >>>nothing happens. When I press it twice, Python shuts down. > >> > >>I assume "Python" means "the IDLE environment" ? > >> > >>IDLE executes Python code inside it's own interpreter, and > >>is also using Tkinter. If you run a program inside IDLE that > >>shuts Tkinter down, you'll also shut IDLE down. > >> > >>That's really IDLE's fault, not Tkinter's... > >> > >>I recommend running the samples in a stand-alone Python > >>interpreter, from the command line. > >> > >>(or use an IDE that knows how to run Python programs in > >>a separate process...) > >> > > > > > > Would you like to tell me which are such IDEs, and among them, which are freeware? > > > > Thank you. > > Giorgi > > > > > > > > > >> > > > > > > Well, I'm not sure it's worth having a look, but I've been told about a > brand new cross-platform, cross-language, fully scriptable and > configurable IDE. > > It's named Emacs... > > laotseu From tim.one at comcast.net Sun Jul 21 01:42:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 21 Jul 2002 01:42:13 -0400 Subject: maximum recursion depth In-Reply-To: Message-ID: [Paul] > ... > Can I optimize my code so that there will be less recursion? yes, but my > recursion depth will still be over 1000 times... > Can I rewrite my code without recursion? Maybe, but I do not want to. > > My question to you: Is there a way to change the limit of the recursion > depth? You've been correctly pointed at sys.setrecursionlimit(), but you should be aware that unless you bought one of those new-fangled machines with infinite memory , your program will eventually crash. From duncan at NOSPAMrcp.co.uk Wed Jul 10 06:20:15 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 10 Jul 2002 10:20:15 +0000 (UTC) Subject: A better self References: <3D2BD37D.8CF82AE@alcyone.com> Message-ID: Erik Max Francis wrote in news:3D2BD37D.8CF82AE at alcyone.com: > Matt Gerrans wrote: > >> In keeping with that concept, '..' would be referring to the base >> class >> (equivalent to java's "super"). > > I think that's definitely mixing metaphors. For one thing, which base > class? Python supports multiple inheritance. > Python already has a 'super' which works properly with multiple inheritance, so presumably it would be a shorthand for super with appropriate arguments rather than referring to a specific base class. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From fredrik at pythonware.com Sun Jul 28 03:42:04 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 28 Jul 2002 07:42:04 GMT Subject: xrange questioin References: <3d43234e$1@duster.adelaide.on.net> Message-ID: Bengt Richter wrote: > >> What is better: for x in range(n) or for x in xrange(n)? > >> (with n is relatively small, like 10 or 100) > > > >for in range() is usually a few percent faster, but if you do some- > >thing inside the loop, you'll hardly notice the difference. > > But speed isn't the only thing. Range builds a potentially > huge list in membory. not if "n is relatively small, like 10 or 100". in CPython, for values up to 100, it builds a list of pointers to an array of preallocated integers. that's just over 400 bytes on most platforms, which is far from huge. > If we didn't have range but we do. what's wrong with just answering the original question? does every answer these days has to contain an essay on some un- related topic, or a sales pitch for the author's favourite library? (that's what blogs and sigs are for, really). From tim.one at comcast.net Fri Jul 26 21:03:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 26 Jul 2002 21:03:56 -0400 Subject: calendar lameness! In-Reply-To: <3D41E488.5C6E6D6A@cascade-sys.com> Message-ID: [James J. Besemer] > ... > And don't get me started on when Easter is. That's easy! Sunday. people-think-too-much-if-they-need-more-precision-than-that-ly y'rs - tim From aleax at aleax.it Wed Jul 24 06:49:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 10:49:13 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: Jeremy Bowers wrote: > On Mon, 22 Jul 2002 23:00:59 -0500, I wrote: >> class M1: >> "M1's docstring." >> def __init__(cls, name, bases, dict): >> pass > > Ah. Moron source located. > > class M1(type): > "M1's docstring." > def __init__(cls, name, bases, dict): > suprt(M1, cls).__init__(name, bases, dict) > > will work as I expected and do the right thing. When your __init__ (or any other method) *just* delegates to the superclass, and nothing else, simply remove that method's definition from your class -- inherit it rather than going to the trouble of overriding just to delegate, which buys you nothing. This goes for metaclasses just as well as for any other class, and for special methods just as well as for non-special ones. Alex From zopestoller at thomas-guettler.de Thu Jul 25 06:47:47 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Jul 2002 12:47:47 +0200 Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> Message-ID: <3D3FD753.7050702@thomas-guettler.de> Max M wrote: > Thomas Guettler wrote: > > >> It would be nice if cgi.escape(int) would not >> throw an exception. >> >> What do you think? > > > > Why? Isn't escape supposed to get a string as an input? Passing it an > int is meaningless. No, it is not meaningless. I have arbitrary objects which I want to write out to a html table. if cgi.escape(foo) would do a foo=str(foo) it would possible to escape integers and floats, too. Yes, I can do foo=str(foo) myself before calling escape, but this feature would hurt noone. thomas From peter at engcorp.com Mon Jul 22 19:37:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 19:37:02 -0400 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> Message-ID: <3D3C971E.D0386D7D@engcorp.com> Paul Rubin wrote: > > Stefan Schwarzer writes: > > > Just to not have to say "foo.foo()" or "from foo import foo". > > > If the main purpose of the module is to provide one function, I think > > > it's cleaner to be able to import the module and call the function > > > without special tricks. > > > > I consider it cleaner to be explicit, and import the module and call > > its function. :-) > > Does that reasoning not also apply to class instances? Why should > class instances be callable through the __call__ method? Because that's how you create an instance of the class (i.e. an object). If you have a reasonable parallel for all modules _in general_ then *that* would be the one reasonable case in which to use this scheme. I can't think of a good one, myself. > > How many actual cases do you know of where a module has a single function? > > Aren't they rare? > > I've written several, there are several in the Python library, and > remember that it's not necessary for the module to have a single > function for a __call__ interface to be useful. __call__ makes sense > if there's a most-important or most-frequently-used function in the > module. It's ok if there are other functions too. Although you can do as you wish, of course, I want to chime in with a "this is a really bad idea" and hope you don't follow through on it. This is, even in the best case, going to make your code less readable to anyone else. It is also likely to cause maintainability problems because making the claim "but this module has only one function!" almost certainly means it will not stay that way forever. Any time you find yourself going to a lot of effort to work around what feels like a small wart or syntactical ugliness (neither of which even apply in this case, IMHO) you should probably stop yourself and say "whoa, what was I thinking?" and do it the standard way. (All free advice of course, worth what it cost you. :-) -Peter From stevenhend at dslextreme.com Fri Jul 5 20:21:24 2002 From: stevenhend at dslextreme.com (Steven C. Hendrickson) Date: Fri, 5 Jul 2002 17:21:24 -0700 Subject: idiots guide to python References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: Mike Johnson wrote in message news:626290cd.0207051529.518f4ce7 at posting.google.com... > I am starting an A-Level course in computing in september, and i will > need to learn how to use python. I have no previous experience of > programming, but could anyone point me in the direction of an "Idiots > Guide"? > > thanks. > > Mike Johnson http://www.python.org/doc/Newbies.html has several downloadable courses; I found the one by Josh Cogliati to be a great start. Get past that, and you will be ready for anything else. Good luck with it. Steve From kalle at lysator.liu.se Tue Jul 30 00:17:08 2002 From: kalle at lysator.liu.se (Kalle Svensson) Date: Tue, 30 Jul 2002 06:17:08 +0200 Subject: Disappearing Output? In-Reply-To: References: <3D4476FB.70200@skippinet.com.au> Message-ID: <20020730041708.GB2081@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [George Hester] > Oh Mark oh Mark thank you. Where is that page of yours? I have > been yanking my hair out on this one. I was about to just trash > Python for good. Thanks. http://starship.python.net/crew/skippy/ Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9RhM8dNeA1787sd0RAhpoAJ9yIyJMFa7H8kwZVncMiQT8ONPDbACgwxZc Nx04+CDdIVGeGftWUyYtv/w= =oegw -----END PGP SIGNATURE----- From shagshag13 at yahoo.fr Mon Jul 22 15:51:06 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 22 Jul 2002 21:51:06 +0200 Subject: print fileinput, and screen ? Message-ID: hello, i've tried fileinput to do inplace modification like : --- countDone = 0 lineI = 0 lineBuffer = [] for line in fileinput.input(FILE_TO_PROCESS,inplace=1, backup='.sav'): if line.find(' 0: lineBuffer[len(lineBuffer) - 1] = lineBuffer[len(lineBuffer) - 1][:-1] + line countDone += 1 for l in lineBuffer: print l.strip() lineBuffer = [] lineI += 1 if lineBuffer != []: for l in lineBuffer: print l.strip() print " Correcting [%s] lines" % countDone # how to be sure this one will never be in FILE_TO_PROCESS ??? but redirect to screen ? --- and as i do some other printing to stdout (print script times, counts, etc.) i'm wondering if that couldn't conflict with "print" for fileinput ? is there a correct way to do it (print in fileinput, and distinct print to screen) ? thanks in advance, s13. From pyth at devel.trillke.net Mon Jul 1 06:43:40 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 1 Jul 2002 12:43:40 +0200 Subject: I'd give up Perl tomorrow if only... In-Reply-To: ; from brueckd@tbye.com on Sun, Jun 30, 2002 at 09:46:40PM -0700 References: Message-ID: <20020701124340.G10625@prim.han.de> brueckd at tbye.com wrote: > On 30 Jun 2002, Aahz wrote: > > > >I suggest that you be a Perl programmer for a while, and see what having > > >CPAN accessible and authoring for it really is like. You explicitly state > > >you aren't familiar with it. I've been author of a couple CPAN modules > > >for about 4 years now, and an extensive user for just as long, and have > > >been a Python module writer for just over a year now. Python is a great > > >language, but in terms of a reusable code repository, *nothing* comes > > >close to the jewel that is CPAN. There is a reason you'll hear this over > > >and over from people coming to Python from Perl. > > > > But somehow one doesn't hear it very often from people who've been using > > Python for a long time > > Just to chime in - Aahz hit the nail on the head here... for whatever > reason, *not* having a CPAN thingy just isn't that painful right now. I somewhat disagree. IMO the standard-lib approach doesn't scale very well. Python seems to get to a stage where the google-path doesn't cut it, either. > It's great that people are trying for it because it *will* be useful, and > eventually an implementation will get done and reach critical mass and > become the standard, but not yet. I'm fully confident that if a CPAN-like > system will be critical in the future, Guido will fire up the time > machine, come back, and have somebody start working on it so it'll be done > in time. >From Guidos keynote at EuroPython i recall some statistics about python's growth. A Comprehensive Python Network (CPYN) could accomodate and support this growth. Better sooner than later, not? holger From cliechti at gmx.net Thu Jul 25 10:23:07 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jul 2002 16:23:07 +0200 Subject: how to get a return value from an exception ? References: Message-ID: "Shagshag13" wrote in news:ahp0n4$upavu$1 at ID-146704.news.dfncis.de: > i need to raise an exception which "carry" some data... i think that > it's something like : ... > it's ok if i do it like in "dive in python" > >>>> class MyError(Exception): > def __init__(self, value): > self.value = value > def __str__(self): > return `self.value` thats fine. maybe you want to pass a string and other args in addition: no need to overload __str__ in this case (unless u want to have the "value" in the message): class MyError(Exception): def __init__(self, message, value): Exception.__init__(self, msg) #call supperclass' init self.value = value >>> try: ... raise MyError("hello",5) ... except MyError, e: ... print e, e.value ... hello 5 > but here what does the `` stand for ? "repr()" i think that's a bad shortcut for it, however some people seem to like it :-( chris -- Chris From asim at jawache.net Sun Jul 28 21:43:26 2002 From: asim at jawache.net (Asim Hussain) Date: Mon, 29 Jul 2002 01:43:26 +0000 (UTC) Subject: New Free 3D/2D Data Visualisation Tool Message-ID: InnerWorld v1.0 - 3D/2D Data Visualisation Tool - http://www.jawache.net/iw ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I've created a FREE Data Visualisation tool called InnerWorld. Tested on Win98 and 2000. + It generates VRML worlds from any form of data. + The data is generated from Plugins, these can be written in C or C++. - Currently the only plugin I've created is called DriveNav and it generates data on the file structure of your computer. + The data is converted to 3D worlds by means of a Scheme (VRML/HTML code wrapped with a layer of Python). - I have created 4 Schemes (3D Lollipop, 3D Tree, 3D Wheel, 2D HTML View), to go with the DriveNav plugin. Creating Schemes is simple, there is lots of documentation on the website with worked examples and the program itself comes with a "scheme development mode" to help in creating Schemes. Plugin creation documentation will be available soon. ( I'm working on the next plugin, which will generate data on a website, this data can then be converted by a scheme to create VRML Site Maps etc... ) Please send comments/requests/bug reports to: asim at jawache.net Thanks Asim Hussain w: www.jawache.net e: asim at jawache.net From djc at object-craft.com.au Tue Jul 16 06:39:29 2002 From: djc at object-craft.com.au (Dave Cole) Date: 16 Jul 2002 20:39:29 +1000 Subject: uniform interface for MySQL & MSSQL References: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> Message-ID: >>>>> "Alex" == Alex Martelli writes: Alex> Johann wrote: >> On Mon, 15 Jul 2002 19:38:28 GMT, Alex Martelli >> wrote: >> >>> Have you tried: http://www.object-craft.com.au/projects/mssql/ >> It does not work. I tried to compile it under Cygwin but some >> files (*.h) are missing :-( >> >> In file included from mssqldb.c:25: mssqldb.h:37: sybfront.h: No >> such file or directory mssqldb.h:38: sybdb.h: No such file or >> directory error: command 'gcc' failed with exit status 1 Alex> Looks like you need freetds (or a Sybase installation, of Alex> course) -- http://www.freetds.org/ I must be blind or something - I just noticed this thread. I stopped doing active development on the MSSQL module when I realised that MS had effectively abandoned the DB library in favour of ADO. If this is not the case I would be interested in hearing the good/bad news. If you are using Linux to talk to an MS SQL Server then you will probably be much more successful using my Sybase module and FreeTDS. This page explains how to get it compiled. http://www.object-craft.com.au/projects/sybase/sybase/node5.html I have only tried compiling with the 0.53 release of FreeTDS which has quite a few bugs. I understand that the CVS snapshots are much much better. I have a set of patches to merge into the 0.35pre1 release - I am going to do a new release any day soon. The patches are all to make the Sybase module work better with FreeTDS. >> I found this module have no cursor.seek(nr) method. :( Alex> Method seek is not part of the DBAPI standard, so it's hardly Alex> surprising that DBAPI compliant modules may lack it:-). (To be Alex> honest, I didn't even know mysqldb supplied that...). What does the method do? Alex> For a shorter-term fix, you might try win32api and ADO as a way Alex> to interface to Microsoft SQL -- not too hard to put a thin Alex> DBAPI compatible interface on top of that. I did that for Alex> think3, back when I worked there (but the code stayed with them Alex> and we never got around to discussing opensourcing some of the Alex> various pieces of code I wrote for them over the years -- don't Alex> hold your breath for THAT, sigh). As I recall, it's a week's Alex> work, tops. There are a few things that you can try. Spend some time evaluating all of the options (while your stamina holds out). - Dave -- http://www.object-craft.com.au From jb at hotmail.com Mon Jul 29 10:50:07 2002 From: jb at hotmail.com (JB) Date: Mon, 29 Jul 2002 16:50:07 +0200 Subject: Let's Talk About Lambda Functions! References: Message-ID: <3d455445_9@news.newsgroups.com> Tim Peters wrote: > [...] > two language features are mentioned as being "failed > experiments" that only compatibility prevents throwing > away: > > `back ticks` > lambda (1) Why are back ticks a failure? I love them. (2) I just wanted to submit a PEP in which I should have proposed to switch to prefix notation like CL. To judge from what you wrote, Mr Guido would not love this proposal too much either? -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From cliechti at gmx.net Thu Jul 18 05:38:15 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Jul 2002 11:38:15 +0200 Subject: slicing and parallel assignment: inconsistent behaviour?? References: Message-ID: tjd at sfu.ca (Toby Donaldson) wrote in news:ad32251c.0207172302.12f4ef4f at posting.google.com: > I was hoping someone might be able to help me with a problem I've run > into with slices and parallel assignment. I want to swap to segments > of a list. For instance: > > >>> B = range(10) > >>> B[1:5], B[5:10] = B[5:10], B[1:5] > >>> B > [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] > > This works as I expect. But if I leave out the 10s in the slice > indices, I get this: > > >>> A = range(10) > >>> A[1:5], A[5:] = A[5:], A[1:5] > >>> A > [0, 5, 6, 7, 8, 1, 2, 3, 4] > > Where has the 9 gone? hint: the first part is 5 elements, the second 4 >>> F = range(10) >>> F[5:], F[1:5] ([5, 6, 7, 8, 9], [1, 2, 3, 4]) and >>> D = range(10) >>> D[1:5], D[5:] = ['a'], ['b'] >>> D [0, 'a', 5, 6, 7, 'b'] >>> D = range(10) >>> D[1:5], D[5:10] = ['a'], ['b'] >>> D [0, 'a', 5, 6, 7, 'b'] >>> using [5:10] or [5:] has the same effect here, but you can see that D[1:5] replaces 4 elements with 'a', and _afterwards_ it replaces [5:] (or [5:10] which is the same here: a list of 2 elements: [8,9] ) with 'b'. an now to your situation. lets do it step by step: >>> D = range(10) >>> D[1:5] = [5, 6, 7, 8, 9] >>> D [0, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] ya see: 11 elements and hece : or :10 _makes_ a difference: >>> D[5:] [9, 5, 6, 7, 8, 9] >>> D[5:10] [9, 5, 6, 7, 8] i think your first example isn't realy doing what you expect it only has all the numbers in it you would expect ;-) HTH chris -- Chris From rich at worldsinfinite.com Tue Jul 9 14:21:54 2002 From: rich at worldsinfinite.com (Rich Harkins) Date: Tue, 9 Jul 2002 14:21:54 -0400 Subject: Splitting a string every 'n' In-Reply-To: <200207091003.50226.rharkins@thinkronize.com> References: <001727B6.C22236@smiths-aerospace.com> <200207091003.50226.rharkins@thinkronize.com> Message-ID: <200207091421.54594.rich@worldsinfinite.com> > On Tuesday 09 July 2002 08:50 am, Simon.Foster at smiths-aerospace.com wrote: > > What is the idiomatic way to split a string into a list > > containing 'n' character substrings? I normally do > > something like: > > > > while strng: > > substring = strng[:n] > > strng = strng[n:] > > > > > > But the performance of this is hopeless for very long strings! > > Presumable because there's too much list reallocation? Can't Python > > just optimise this by shuffling the start of the list forward? > > > > Any better ideas, short of manually indexing through? Is there > > something like: > > > > for substring in strng.nsplit(): > > > Using python2: [s[i:i+n] for i in range(0,len(s),n)] where: s - is the string to split n - is the number of characters to break at i - is some throwaway variable (previous value of i *not* protected) Rich From ods at fep.ru Tue Jul 16 07:27:17 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Tue, 16 Jul 2002 15:27:17 +0400 (MSD) Subject: Iterator for Custom Sequence In-Reply-To: <87u1mzq5xw.fsf@athens.localdomain> Message-ID: On 16 Jul 2002, Patrick W wrote: PW> To learn how to provide iterators for custom sequences, I've PW> made a PW> typical linked list with the following __iter__ method: PW> PW> class LinkedList: PW> .... PW> def __iter__(self): PW> def genitems(ls): PW> n = ls.head PW> while n.data is not None: PW> yield n.data PW> n = n.next PW> return genitems(self) PW> .... __iter__ method can be implemented as generator itself: class LinkedList: ... def __iter__(self): n = self.head while n.data is not None: yield n.data n = n.next ... -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From mgerrans at mindspring.com Wed Jul 10 01:47:31 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 9 Jul 2002 22:47:31 -0700 Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <8xKW8.47005$n4.11322657@newsc.telia.net> Message-ID: > string = "0x0+__import__('os').system('echo 7h1s b0x 1s 0wn3d')" As I said, someone will probably suggest a better re; how's this: r'^0x(\d|[a-f])*$' From spam at ob_scure.dk Sun Jul 7 07:20:51 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 13:20:51 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> Message-ID: <3D282413.1010801@ob_scure.dk> Alex Martelli wrote: > > If you have substantial numeric computations to perform on large > arrays, you're almost surely better off using the Numeric package > to extend Python, particularly if performance is an issue. http://www.pfdubois.com/numpy/ ? It looks just like what I need! Thanks! -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From christophe.delord at free.fr Mon Jul 8 13:29:34 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Mon, 8 Jul 2002 19:29:34 +0200 Subject: structs in python References: <20020706231200.A25295@arizona.localdomain> <7xbs9i91h3.fsf@ruckus.brouhaha.com> Message-ID: <20020708192934.7d16b9c4.christophe.delord@free.fr> The dict can be the __dict__ attribute of a particular class : class Record: def __init__(self, **kw): self.__dict__.update(kw); p = Record(x=10, y=11, color='blue') print p.x On 07 Jul 2002 23:29:28 -0700 Paul Rubin wrote: > list-python at ccraig.org (Christopher A. Craig) writes: > > Why don't you just use a dict? > > > > >>> p = {'x'=10, 'y'=11, 'color'=blue} > > >>> print p['x'] > > 10 > > Typing p['x'] is more cumbersome than typing p.x and doesn't convey > the same type of meaning. p.x sounds more like it refers to a fixed > slot in a structure. -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From aleax at aleax.it Sat Jul 13 17:16:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 21:16:17 GMT Subject: switch recipe? References: Message-ID: Terry Reedy wrote: ... > is easy and clean: > > def firstn(it, n): > while n: > yield it.next() > n -= 1 Marginally easier and cleaner: def take(n, it): for j in xrange(n): yield it.next() Alex From gerhard.haering at gmx.de Tue Jul 16 07:14:54 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 16 Jul 2002 11:14:54 GMT Subject: uniform interface for MySQL & MSSQL References: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> Message-ID: Dave Cole wrote in comp.lang.python: [cursor.seek()] > What does the method do? See PEP 0249. It changes the cursor position. Usage is cursor.scroll(value, mode='relative'), where mode can be 'absolute' or 'relative'. And the method is actually called scroll rather than seek. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gerhard.haering at gmx.de Wed Jul 3 12:23:58 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 3 Jul 2002 16:23:58 GMT Subject: python newsgroup server References: Message-ID: Jonas Geiregat wrote: > is there a special server hosted by python.org a python news server? AFAIK no. But all public newsservers at ISPs/universities/... should have comp.lang.python. If your ISP is worth its money, it has a newsserver. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From aleax at aleax.it Wed Jul 17 17:42:15 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 17 Jul 2002 21:42:15 GMT Subject: 'capwords' is not a string method References: Message-ID: thehaas at binary.net wrote: ... > But "capwords" *is* included in the string module: > >>>> string.capwords(str) > 'Python Rocks' > > So I can still do it, but this seems a little inconsistant to me. Is > there a reason, or is it just an oversight?? > > -- mikeh >>> import string >>> string.capwords('python/rocks') 'Python/rocks' >>> 'python/rocks'.title() 'Python/Rocks' >>> Apparently, they took occasion of the introduction of string methods to replace the semi-crippled capwords (which only capitalizes words _preceded by whitespace_) with the better method title, which capitalizes words even when they are preceded by punctuation, as well as whitespace. It seems sensible to me -- the need met by .title() is more frequent, and if the issue is backwards compatibility, capwords is still around (in the semi-obsolescent string module -- only semi, because it supplies crucial constants such as digits, letters, whitespace, etc). Alex From mikeb at mitre.org Thu Jul 11 08:18:37 2002 From: mikeb at mitre.org (Mike Brenner) Date: Thu, 11 Jul 2002 08:18:37 -0400 Subject: COCOMO - appropriate for languages like Python? (fwd) References: <200207102307.g6AN72822540@panix1.panix.com> Message-ID: <3D2D779D.D988C6F0@mitre.org> Hi aahzpy! I am very interested in this problem, and would like to help, but I don't know what you mean. I viewed this message in textpad, microsoft word, wordpad, and netscape 4.79, and the two paragraphs below look the same. Is this possibly an Internet Explorer problem? Or is it a side-effect of the automatic reposting of python-list at python.org messages to comp.lang.python? Or it is a side-effect of translating from Windows format files to Linux format files? Mike Brenner aahzpy at panix.com wrote: > > This looks like a fascinating post, but it's very hard to read because > each paragraph is on long line instead of multiple shorter lines that > fit on an 80-column display. > > Compare this > > - Software Maintenance time primarily increases as backlog increases (e.g. programmer overtime which the company intends to not pay, other work awaiting action, inadequate functional testing, deferred regression testing which detects reappearance of prior bugs, incomplete impact analysis of past and present changes, incorrect documentation, and the age of parallel development paths). For example, parallel development paths that last more than a few days (fractured baselines) start to take on lives of their own, and become more expensive to merge into a single "golden" baseline as they age. > > to this > > - Software Maintenance time primarily increases as backlog > increases (e.g. programmer overtime which the company intends to not pay, > other work awaiting action, inadequate functional testing, deferred > regression testing which detects reappearance of prior bugs, incomplete > impact analysis of past and present changes, incorrect documentation, and > the age of parallel development paths). For example, parallel development > paths that last more than a few days (fractured baselines) start to take > on lives of their own, and become more expensive to merge into a single > "golden" baseline as they age. From pecora at anvil.nrl.navy.mil Tue Jul 9 13:59:06 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 13:59:06 -0400 Subject: Why self? References: <090720020820257031%pecora@anvil.nrl.navy.mil> Message-ID: <090720021359063518%pecora@anvil.nrl.navy.mil> If I may ask some questions and make a few statements: In article , Andrew Koenig wrote: > 1) In Python, it is generally not possible to determine what the > attributes of an object are by statically examining the source. > For example: > > class Thing: > def __init__(self): > setname(self) > > def printname(self): > print self.name > > def setname(x): > x.name = "Thing" > > At the time the compiler encounters the "print self.name" statement, > how would it know that name is an attribute of the object of which > printname is a member? Note that it hasn't seen the definition of > setname yet. This one is lost on me. Sorry, I'm not operating at your level. What is the point? I advocated initializing object variables in a mandatory __init__ statment. So you should have added def __init__(self): name=None or something like that to be consistent with what I suggested (which by the way was a stab from the top of my head right at that moment). Now the point was made that this might cause excess overhead, slowing down the execution. That I cannot comment on, but explicitly naming object variables in __init__ or wherever might be best seems to take care of this example nicely (execution speed aside) and makes the object variables _explicit_. Did I miss something? > 2) Methods are just functions that happen to be attributes. > In other words, we could have written this: > > class Thing: > def __init__(self): > setname(self) > > def setname(x): > x.name = "Thing" > > def printname(self): > print self.name > > Thing.printname = printname > > t = Thing() > t.printname() > > effectively transforming printname into a method, even though it > does not have the form of a method when it is written. > > It seems to me that dropping the explicit "self" would make these > two programs much messier. In what way then is it cleaner? Hmmm...a pretty bizzare example or else I just don't have enough programming experience. I've never done anything close to that. I will have to rely on others experience (including yours, which I know is substantial). Is this realistic or are you just pulling out a pathological example for argument? After all, I don't think it's the duty of a language design to completely protect the programmer from foolish code (for want of a better phrase). At some point the language has to just give up trying to interpret things and "raise and exception." Tell you what. You're a smart guy (not sarcastic, I mean it). Why not apply your considerable knowledge to finding a solution to the issue of requiring "self." prefixes? It's apparent that lots of people would like to lose that requirement. I'm sure you can demolish my off-the-cuff suggestion at some point. I'm a bush-league amateur. But when you do that you will turn around to see that the issue itself is still there. What would you do? -- Lou Pecora - My views are my own. From mwh at python.net Wed Jul 10 09:29:52 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 10 Jul 2002 13:29:52 GMT Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> Message-ID: Wolfgang Draxinger writes: > Michael Hudson wrote: > > > To me these sentences contradict each other. So I must be missing > > something... > > I want not to add a statically linkes python.lib to my linkage Why not? Do you mean you don't want to use the distributed python.lib? > > For the modules, just don't build them. You really don't want to try > > getting rid of sys, btw. > > Yes I want that! No, you don't: far too much of the internals depends on getting things out of the sys module. You might be able to hide things from the scripts that you execute, but that's a different problem, surely? > I just want the language and the grammar and basic data > types. E.g. I've a virtual file system in my engine. All that's > related to files should go through this natively. > Ok, discarding sys may be not a good idea, but things like > sys.exit, sys.path, sys.dllhandle and similair should definitely not > be touched by engine object scripts. OK, so I think a better (read: easier) strategy might be to /hide/ these objects, not /remove/ them. > >>Can anybody give me some advice for that. > > Yes: don't. > > Why? Because there are probably easier ways of acheiving what you want; executing "engine object scripts" is a heavily custimized environment is almost certain to be more straightforward than heavily customizing the interpreter, and sounds to me as if it will do the job. Cheers, M. -- The ability to quote is a serviceable substitute for wit. -- W. Somerset Maugham From gerhard.haering at gmx.de Mon Jul 15 23:37:57 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 16 Jul 2002 05:37:57 +0200 Subject: could not import mod_python.apache In-Reply-To: References: Message-ID: <20020716033757.GA1069@lilith.my-fqdn.de> * Michael Hoffmann [2002-07-15 21:16 +0200]: > "Gerhard H?ring" wrote: > > * Michael Hoffmann [2002-07-15 16:39 +0200]: > > > Hi, > > > I've the folowing Error when I try to run my pythonscript: > > > > > > make_obcallback(): could not import mod_python.apache. > > > > You could try to fix this manually: the directory lib/python/mod_python > > in the mod_python source distribution should go into the site-packages > > directory of the Python you compiled it against. > > Hi Gerhard, > but I've used the original RPMs from SuSE ... I wouldn't be surprised if these were broken. IIRC SuSE had a seperate RPM called python-nothreads or similar that is required by mod_python. I can't really help much, as I don't use SuSE any more. But my suggestion to ask on the mod_python mailing list still stands. If you have indeed installed both the mod_python and the python-nothread RPMs and you're getting this error, then the SuSE mod_python RPMs are most probably buggy. I suggest building both from source yourself, then. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.7 ?C Wind: 2.8 m/s From hamish_lawson at yahoo.co.uk Fri Jul 12 06:25:27 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 12 Jul 2002 03:25:27 -0700 Subject: Guido van Rossum Tutorial - .PDF or other format? References: Message-ID: <915a998f.0207120225.6b5f768d@posting.google.com> David Wright wrote: > Could someone please advise if this suberb document is available on the Web > in a printer friendly format, such as .pdf or even .doc. (other than the > hypetext version on line and on my PC). Yes, I'd like the *address* too ;-) It is available in various formats, including PDF in A4 and US Letter sizes, at http://www.python.org/doc/current/download.html Hamish Lawson From mgilfix at eecs.tufts.edu Thu Jul 25 09:42:52 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Thu, 25 Jul 2002 09:42:52 -0400 Subject: cmd, readline, and /path/filename completion In-Reply-To: <200207250544.41572.dcinege@psychosis.com>; from dcinege@psychosis.com on Thu, Jul 25, 2002 at 05:44:41AM -0400 References: <20020724175117.B3904@eecs.tufts.edu> <200207250040.58148.dcinege@psychosis.com> <200207250544.41572.dcinege@psychosis.com> Message-ID: <20020725094252.B2011@eecs.tufts.edu> Ah. Was just trying to be helpful :) Glad you solved it though. It can be hard to say what methods you need to override as different implementations expose them differently. I hadn't personally messed with the python one. Perhaps you could submit this to a python cookbook or something. I'm sure others would find it really useful. -- Mike On Thu, Jul 25 @ 05:44, Dave Cinege wrote: > On Thursday 25 July 2002 0:40, Dave Cinege wrote: > > > I'm by no means a coding novice, and I already know I (or somewhere in > > readline) must walk the path and gather a list of executable files. Where > > I'm lost is how to pass this to readline. (Or activate it in readline) > > Just needed to do more homework. The thing to do in my situation > is to override the 'completenames' method of cmd. The method below > completes all executeables in the path just like bash. > > What confused the hell out of me is I couldn't get 'completedefault' > to do anything. Viewing the cmd modules showed that is only > run when the completer index is > 0. Thus, 'commands' (the beginning of > a line) is run against completenames... > > def completenames(self, text, line, begidx, endidx): > l = cmd.Cmd.completenames(self, text, line, begidx, endidx) > path = os.environ['PATH'].split(':') > textlen = len(text) > for dir in path: > try: > files = os.listdir(dir) > except: > continue > for file in files: > if textlen > 0 and file[:textlen] != text: > continue > if os.access(dir+'/'+file, os.X_OK): > l += [file] > return l > > > > -- > The time is now 22:48 (Totalitarian) - http://www.ccops.org/ `-> (dcinege) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From tom.verbeure at verizon.no.sp.am.net Sat Jul 27 16:21:44 2002 From: tom.verbeure at verizon.no.sp.am.net (Tom Verbeure) Date: Sat, 27 Jul 2002 20:21:44 GMT Subject: How to detect the last element in a for loop Message-ID: Hello All, I often have the case where I need to loop through a bunch of elements, but do something special on for the last line of code. Currently, I can solve it this way: first = 1 for port in self.portDefsList: if first == 0: string += ", " else: first = 0 string += str(port) pass This works fine, but it introduces an extra variable. Is there a cleaner way to do this? Thanks, Tom From stevee at recombinant.demon.co.uk Thu Jul 11 16:35:26 2002 From: stevee at recombinant.demon.co.uk (Stephen D Evans) Date: Thu, 11 Jul 2002 21:35:26 +0100 Subject: writing output to file References: Message-ID: <1026419728.3988.0.nnrp-08.d4e54907@news.demon.co.uk> Two simple changes (as per Alex Martelli's alternative suggestion): 1) You can open a file for writing. 2) Redirect your print statement to the resulting file object using the print>>_file modifier, where _file is the file object that print writes to. Without the modifier print writes to sys.stdout 3) The third change is to tweak the code for Python 2.2 (I tested this with 2.2.1). There is no out_stream.close() - Python does this automatically for the lazy and unsuspecting. #!/usr/bin/env python out_stream = file('test.txt', 'w') for line in file('/etc/passwd'): if line.lstrip()[0] == '#': continue temp = line.split(':') if int(temp[2]) > 100 : print>>out_stream, "%10s %30s" % (temp[0], temp[4]) # Stephen D Evans "Allan Wermuth" wrote in message news:agklgl$rvu$1 at news.net.uni-c.dk... > Inspired by an existing Perl script, I wrote this chunk of code, but instead > of > writing the result to the screen, I would like to write output to a another > file. > > #!/usr/bin/python > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue > > temp = line.split(':') > if int(temp[2]) > 100 : > print "%10s %30s" % (temp[0], temp[4]) > > How can I do that? > It's possibly quite simple, in Perl it is ;-) , but I am trying to learn > Python, so > I would appreciate if someone would help me out. > > /Allan Wermuth From JoeSalmeri at comcast.net Tue Jul 23 22:32:26 2002 From: JoeSalmeri at comcast.net (Joe Salmeri) Date: Wed, 24 Jul 2002 02:32:26 GMT Subject: Python + Win32ALL + ASP = Problems accessing Request/Response/Session/Application objects Message-ID: <_ko%8.247434$iB1.13124073@bin4.nnrp.aus1.giganews.com> Python = 2.2 Win32All = build 146 OS = XP Professional How are the ASP Request/Response/Session/Application objects accessed in a module that is imported in an ASP file WITHOUT passing them in as paramaters to each of the functions defined in that module? I have attempted to track down the creation of those objects but have been unable to trace them to the source of their creation. Here is an example of what I am trying to do (all thoughts are greatly appreciated) ----- begin sample.asp ---- <%@language="Python"% <% # At this point the Request/Response/Session/Application objects exist in the global namespace. # Also there is a __ax_main__ module and a ax global that contains that Request/Response/Session/Application objects # The __ax_main__ module and ax global appear to be created by creating an instance of win32com.axscript.client.pyscript.PyScript() import sample_util %> ---- end of sample.asp ---- ---- begin sample_util.py ----- # How can the Request/Response/Session/Application objects be accessed by this module WITHOUT passing them # in as parameters to any functions defined here? def sample_func_1(Request, Response, Session, Application): # this would allow you to reference the objects but each function would need to do this return def sample_func_2(Request, Response, Session, Application): # this would allow you to reference the objects this function would need to do this too return def sample_func_3(): # I want to do something like import ax ax.Response.Write('blah blah') # OR from ax import Request, Response, Session, Application Response.Write('blah blah') ---- end sample_util.py ---- From aleax at aleax.it Thu Jul 25 10:45:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 14:45:23 GMT Subject: how to count lines in a file ? References: <200207251015.40671.rjones@ekit-inc.com> <2259b0e2.0207250631.1e093e64@posting.google.com> Message-ID: <7aU%8.139472$vm5.4528856@news2.tin.it> Michele Simionato wrote: > Can somebody provide a simple example where the idiom > > file(name,'w').write(something) > > fails, in the sense that the file is not closed or something is not > written ? I tried to hang the program with a memory overload [alex at lancelot jython-2.1]$ jython Jython 2.1 on java1.4.0_01 (JIT: null) Type "copyright", "credits" or "license" for more information. >> open('aname','w').write('something\n') >>> [alex at lancelot jython-2.1]$ cat aname [alex at lancelot jython-2.1]$ ll aname -rw-rw-r-- 1 alex alex 0 Jul 25 16:41 aname [alex at lancelot jython-2.1]$ I exited the interactive interpreter with a clean, normal control-D, but as you see file aname was created but its contents not written. Any implementation of Python is perfectly free to choose this behavior if it provides some other advantage. If you KNOW your code will NEVER need to migrate to any other implementation of Python except the one you can test today, then you may choose to use implementation-dependent behavior if it gives you some other important plus. In most situations, however, including scripts MEANT to be throw-away, I would suggest taking the tiny extra effort to avoid implementation-depended behavior. It's far from impossible that you may want to use those scripts on some other implementation of Python, and if they pervasively used implementation-dependent behavior that the other impl. does not supply, you'll get no sympathy whatsoever:-). Alex From mgerrans at mindspring.com Thu Jul 11 03:28:50 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 11 Jul 2002 00:28:50 -0700 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <080720021458067296%pecora@anvil.nrl.navy.mil> Message-ID: > ... Indentation is good, and improves readability, but I > always indent with tabs... Tabs were only useful in the days when all the source, compiler and libraries were on a 360K floppy and every byte was jealously hoarded. Now, in the 21st century, they are nothing but a source of confusion (I always use an editor that shows them explicitly, because they have occasionally caused great strife in Python and make files). If you always just used three spaces, you wouldn't have any of these problems in Python. I think the use of indentation for scoping is one of the greatest things about Python: why clutter up the code with curly braces, which are just information for the compiler? We already use indentation (in C/C++, Java, etc.), so why not make use of that information, throw out the extra typing of curlies (as well as the concomitant religious wars over their placement) and enforce its meaning and consistency? By the way, if you are more enamored of the lexical approach, you might be more interested Ruby. From dswegen at software.plasmon.com Mon Jul 15 06:56:57 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Mon, 15 Jul 2002 11:56:57 +0100 Subject: App implementation help needed Message-ID: <20020715105657.GB12469@software.plasmon> I'm currently designing the second part of a little pet project of mine, and run into a wall regarding how to proceed, and would much appreciate some assitance in figuring out in which direction I should go. The setup is as follows: A daemon has a queue of times when it should perform an action that involves fetching some data from a web site. These times, and associated data (which end up customising the URL), is to be provided by users via a web interface. The user provided events, as well as some user data (username, password) need to be stored. The program will in the first instance be running on Linux, but if for no extra cost I can make it run on other platforms that would be nice (but not at the cost of simplicity). All pretty simple stuff in itself. My problem is how to tie together the different parts (web interface, updating queues, calling a certain function at a certain time with certain user provided data). Are threads the best/easiest way to achieve this? Are fork()s sufficient? Or would having the web interface based on asyncore allow me to avoid using threads/forking entirely? Is using the Queue module appropriate, or would a list be sufficient? Would using sleep(1) in a loop be sufficient (I need second precision, so cron is not really an option), or would sched be more appropriate? I don't want to use a full DB, so should I go with pickling or anydbm? So, lots of questions, probably not enough background information, and somebody who is rather overwhelmed by the options avaliable. I'm hoping to keep this as simple as possible, so please, be gentle :) Any help much appreciated. Cheers Dave From K.Rdt at TU-Berlin.DE Mon Jul 1 05:23:17 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Mon, 01 Jul 2002 11:23:17 +0200 Subject: HT set the font in wxPython? Message-ID: --------------------------------------------------------------------- Hi I want to have an equal spacing font for a monitoring output (s.b.). How can I accomplish this in wxPython? K at Rdt --------------------------------------------------------------------- # Aktive Verbindungen # # Proto Lokale Adresse Remote-Adresse Status # TCP 0.0.0.0:1171 0.0.0.0:0 LISTENING # TCP 130.149.164.212:1171 130.149.4.11:110 ESTABLISHED yy=y.splitlines() for i in yy: if i[:5]==" TCP": ry=string.split(i) print "%5s %22s %22s %22s" % (ry[0],ry[1],ry[2],ry[3]) From martin at v.loewis.de Tue Jul 30 14:05:39 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 20:05:39 +0200 Subject: global interpreter lock not working as it should References: Message-ID: anton wilson writes: > What's the purpose of releasing an reaquiring the lock if no other threads > can run? Other threads *can* run - it is the operating system's choice whether they *will* run. > It's easy to say that one can't assume about the order of running on > different platforms as a scapegoat, but the main problem is that the > GIL is NOT implemented properly with pthreads. Why do you say that? The implementation does work as intended. > So nearly every system that uses pthreads will show this kind of > queue behaviour. I have a feeling that there is a hidden race > condition between when the thread wakes up the other thread and > tries to reaquire the lock. It really should be fixed, or else > what's the point of threads? Threads are for concurrency! And concurrency you get (just modify my example to use infinite loops, then tell me on what system you never ever see a thread switch). Regards, Martin From unlearned at DELETETHIS.learn2think.org Mon Jul 29 15:21:13 2002 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Mon, 29 Jul 2002 13:21:13 -0600 Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> <3D45894A.2090406@motorola.com> Message-ID: <3d4595a9$1_3@hpb10302.boi.hp.com> "Stephen Boulet" wrote in message news:3D45894A.2090406 at motorola.com... > What if you wanted to do things like make a tabbed spreadsheet (tabs on > the bottom that break up a notebook int subparts, not '\t'), is this > possible with csv format? > > Chris Liechti wrote: > > keilj_33 at yahoo.com (Jeffrey Keil) wrote in > > news:67f6bbe5.0207270544.696f6076 at posting.google.com: > > > > > >>Greetings: > >> > >>I'd like to have a Python script open a text file, process the data in > >>the text file and then write a report to an Excel file. I'm not sure > >>how I would write to an Excel file from a Python script. Is there any > >>books that would give me details on doing this? > > > > > > you could use COM. but i think its simpler to write the output to a text > > file again. use tabs to separate columns and name it .csv - excel will > > autodetect the format and load it correctly. > > > > chris >From creating such a file in MS Excel and trying to save it as a .csv file, I got: "The selected file type does not support workbooks that contain multiple sheets." Also from MS Excel Help: """ CSV (Comma delimited) format The CSV (Comma delimited) file format saves only the text and values as they are displayed in cells of the active worksheet. All rows and all characters in each cell are saved. Columns of data are separated by commas, and each row of data ends in a carriage return. If a cell contains a comma, the cell contents are enclosed in double quotation marks. If cells display formulas instead of formula values, the formulas are converted as text. All formatting, graphics, objects, and other worksheet contents are lost. Note If your workbook contains special font characters such as a copyright symbol (?), and you will be using the converted text file on a computer with a different operating system, save the workbook in the text file format appropriate for that system. For example, if you are using Windows and want to use the text file on a Macintosh computer, save the file in the CSV (Macintosh) format. If you are using a Macintosh computer and want to use the text file on a system running Windows or Windows NT, save the file in the CSV (Windows) format. """ -- Daniel Fackrell (unlearned at learn2think.org) When we attempt the impossible, we can experience true growth. From martin at v.loewis.de Thu Jul 11 16:55:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Jul 2002 22:55:23 +0200 Subject: python binaries for Solaris References: <5fa44575.0207110924.7dff8ba8@posting.google.com> Message-ID: joshualevy at yahoo.com (Joshua Levy) writes: > Does anyone know where there are python binaries > pre-compiled for Solaris 9 / SPARC3 / sunfire type > hardware? I need to do some quick benchmarking, > and I don't even have a compiler on the Solaris 9 > machine, so building python would be a pain. I recommend that you install the Solaris 8 binaries from sunfreeware.com. Regards, Martin From martin at strakt.com Tue Jul 9 04:13:16 2002 From: martin at strakt.com (Martin =?ISO-8859-1?Q?Sj=F6gren?=) Date: 09 Jul 2002 10:13:16 +0200 Subject: Table Widget (without Installation) In-Reply-To: <3D2A9948.5090304@thomas-guettler.de> References: <3D2A9948.5090304@thomas-guettler.de> Message-ID: <1026202396.6397.1.camel@ratthing-b3cf> tis 2002-07-09 klockan 10.05 skrev Thomas Guettler: > Hi! > > I am searching for a table widget to > use with python. Is it still true that > tkinter has none? > > I need it for an application on win32 > which should not be installed. All > libraries will be in one directory. > > pyFox, pygtk, wxpython are options. > > pyQt not since it is not allowed for commercial > applications. Well, it is, but it costs money. > Which could be the easiest? I'm a big fan of Gtk myself, and Gtk 2 has a (IMHO) good table widget. Using pygtk from CVS would probably work. Regards, Martin -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From mumbly at oneofus.org Tue Jul 30 10:31:24 2002 From: mumbly at oneofus.org (Tim McNerney) Date: 30 Jul 2002 14:31:24 GMT Subject: Finding count of currently open file descriptors. References: <3D469D2F.6010003@truis.com> Message-ID: <3D46A287.9040405@oneofus.org> Martin v. L?wis wrote: > Tim McNerney writes: > > >>How do I go about finding out the number of file descriptors currently >>open in a program? > > > Depends on your operating system. On Linux, /proc/self/fd contains > this information. > > In a Python debug build, you can find out all file objects, but there > may be file descriptors not controlled by Python file objects (e.g. if > opened by os.open). This is more what I'm looking for -- some generic method which is within Python itself. How would I go about doing this within the debug build? > >>I'm trying to track down a file descriptor leak which may or may not >>be in library calls. Will I run into problems getting an accurate >>count due to the possible delay between doing a close and GC? > > > If you do a close, the file is closed immediately (i.e. when the close > returns). Cyclic GC is usually irrelevant, since file objects cannot > participate in a cycle - they can, however, be referred to from a > cycle. Thanks. --Tim From kalle at lysator.liu.se Fri Jul 5 05:51:31 2002 From: kalle at lysator.liu.se (Kalle Svensson) Date: Fri, 5 Jul 2002 11:51:31 +0200 Subject: Why self? In-Reply-To: References: Message-ID: <20020705095131.GA5631@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Jesper Olsen] > Why is it necessary to use a "self" argument to class methods in > python? This is a FAQ. http://www.python.org/cgi-bin/faqw.py?req=all#6.7 You can also go to http://groups.google.com/groups?q=group%3Acomp.lang.python+explicit+self for more reading about this subject. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9JWwcdNeA1787sd0RAgzCAJ9MCGgdkVj1UJDPFHAm+toIYjpq5QCfSe7a 0E4am6okIHlIvyY5aevE5lU= =GLbX -----END PGP SIGNATURE----- From kp at kyborg.dk Thu Jul 11 04:21:29 2002 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 11 Jul 2002 10:21:29 +0200 Subject: Python in the enterprise: Pros and cons References: Message-ID: <3D2D4008.7050207@kyborg.dk> David LeBlanc wrote: > * Python's obscurity in development shops > > -- We don't WANT to take over the COBOL shops ;o)! I suspect most Linux and > Windows programmers have heard of Python and it would not surprise me to > know that a lot of them where using it internally where it's below the radar > of the people who poll language use (Dataquest, Gartner Group?). IBM, HP and > Intel use Python! > Why not? (in fact i've been hired to do exactly that - hehe) From my point of view, Python encompasses a lot of the elements that the COBOL developers want (and some of what they always claimed COBOL to have .... readability!). * We have portability (surpassing most COBOL variants) * We have speed (at least as much speed as a COBOL developer will expect) * We have large scale database integration (via PyDBI (or what its called) * We have portable GUI's, that are extremely easy to use comparedly. Learning Python is straight forward, and doesn't scare of a COBOL programmer in the way that C++ or Java would. From shalehperry at attbi.com Tue Jul 30 13:01:23 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 30 Jul 2002 10:01:23 -0700 (PDT) Subject: Python equivalent to 'which'? In-Reply-To: <732d35a1.0207300836.3836892e@posting.google.com> Message-ID: On 30-Jul-2002 eg wrote: > Is their a python equivalent to the bash shell command 'which'? I > haven't found it, and 'which' is such a common word that it may be > lost in the noise in my dejanews searches :( > > I could grab the PATH environment variable and walk all the paths, but > I'm hoping python has already done it for me! > Thanks > Eric > -- > http://mail.python.org/mailman/listinfo/python-list >>> def which(exe): ... for d in string.split(os.getenv('PATH'), ':'): ... name = os.path.join(d, exe) ... if os.path.isfile(name): return name ... return None ... >>> which('bash') '/bin/bash' >>> which('foo') that's all 'which' does (-: From dcinege at psychosis.com Fri Jul 26 13:04:25 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Fri, 26 Jul 2002 13:04:25 -0400 Subject: redirect to > and to console ? In-Reply-To: References: Message-ID: <200207261304.25523.dcinege@psychosis.com> On Friday 26 July 2002 4:57, Shagshag13 wrote: > hello, > > i use many python script like that : ./myscript.py file_in > file_out > > i wish i would sometimes like to force output to be redirect to console > instead of file file_out, is there any way of doing that ? (for example to > display errors message while file_in will contain only data processed) > > (or should i do ./myscript.py file_in file_out > log.file and let myscript > handle i/o ?) If you want to be quick and dirty you can pipe to the 'tee' command # tee --help Usage: tee [OPTION]... [FILE]... Copy standard input to each FILE, and also to standard output. ./myscript.py file_in | tee file.out Understand stderr will still only go to the console. I *think* this is what you're asking... -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From pbrown74 at hotmail.com Tue Jul 2 07:30:21 2002 From: pbrown74 at hotmail.com (Paul Brown) Date: Tue, 2 Jul 2002 12:30:21 +0100 Subject: Ant Task Message-ID: can anyone please give me an Ant Task for compiling Jython code thanks paul From jdavis at empires.org Mon Jul 1 05:54:05 2002 From: jdavis at empires.org (Jeff Davis) Date: Mon, 01 Jul 2002 09:54:05 GMT Subject: reloading modules Message-ID: <1FVT8.56956$xy.18941573@twister.socal.rr.com> It seems like it might be common to import a module (that may or may not have already been loaded) and require that you get the newest version at the time of the import. The way I see it, this requires 3 steps: 1) build a table of the modification times of files that have been imported 2) compare a file's modification time to the time stored in the table 3) import the module if it doesn't exist in the table, do nothing if the modification times are the same, and reload it if the modification times are different. My question is: are the python developers planning on including such a standard function at some furture time, or should I just plan on having my own module for that? Or does a 3rd party one exist? Thanks, Jeff From nas at python.ca Mon Jul 8 20:44:16 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 8 Jul 2002 17:44:16 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <96c7f32.0207081518.52ea644a@posting.google.com>; from curt@journyx.com on Mon, Jul 08, 2002 at 04:18:03PM -0700 References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <20020708174416.A5860@glacier.arctrix.com> curt finch wrote: > Our free web timesheet app is written totally in Python. One of our > competitors is saying the following things about python to our > customers. Help me make them look stupid. Please? [Lots of stupid crap deleted] I don't think you have to do anything. They are doing fine job of looking stupid all by themselves. You might suggest that your customers compare application functionality instead of comparing low level implementation details. Other than that, you should probably spend time improving you application rather than worrying about all the morons in this world. You really must be kicking their ass if their best criticism of your product is its implementation language. I can imagine them cooking up with new criticisms right now: Their application code was edited using Emacs and Vi. We only use the Espressomatic 3501(TM) in our shop. Vi and Emacs suck because .... :-) Neil From python at dohao.org Tue Jul 30 23:10:06 2002 From: python at dohao.org (Wenshan Du) Date: 30 Jul 2002 20:10:06 -0700 Subject: Leo should support unicode Message-ID: I think Leo is very nice, I just downloaded leo.py 3.2. I found it open a blank frame sometimes.Why? And, I suggest Leo should support unicode. My Python is 2.2.1, and Windows 2000Pro. From ajs at ix.netcom.com Fri Jul 5 09:41:50 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Fri, 5 Jul 2002 09:41:50 -0400 Subject: __slot__ issues Message-ID: <000a01c22429$b8209f80$0334fea9@carol> Eric Texier writes - >I don't thing it is a bug and I like it like this. I use it, not only to save >memory but also to force myself to declare and init all the variables >instance. When I am there, editing the __slots__ I can use the time >to actually set a default value in the __init__. (nasty c++ habit) What I was pointing to as a bug was the error message under the circumstances of the 2nd part of my post. Not anything else related to the behavior of slots - which I am assuming work as designed. > SystemError: C:\Code\221\Objects\dictobject.c:511: bad argument to internal > function Certainly unlike any error message I've encountered before in Python, and significant, I would think, if one were trying to catch Attribute Errors that one would expect when using slots. I'll probably just send it up as a bug report. Tim straightened me out on tutor - so that I understand now that the purpose of slots is memory related. But like you I am trying to use the facility to kill a few birds with one stone. For my purposes I was hoping to use it to accumulate a list of legal keyword arguments for each class. Perhaps something along the lines of the concatenate idea you suggest would work for my purpose. If not, I'll consider it as something learned and revert to a more standard approach to solving my issue. Art From mwh at python.net Wed Jul 17 06:37:41 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 17 Jul 2002 10:37:41 GMT Subject: get a list printed in hexadecimal notation References: Message-ID: Oliver Eichler writes: > Hi > > Is it possible to print a mixed list with strings and numbers and having the > numbers printed as hexadecimal notation? > > something like: > > >>>l = ('spam',10,15,'more spam') > >>>print l > ('spam',0xA,0xF,'more spam') > > or similar... > > The only way I could think of is to write my own print function. This is likely the case. > Is there an easy way? You may be able to leverage the pprint module. Not sure. Cheers, M. -- 7. It is easier to write an incorrect program than understand a correct one. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From walter at livinglogic.de Wed Jul 3 08:05:52 2002 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Wed, 03 Jul 2002 14:05:52 +0200 Subject: [NEWBIE]-Object referencing?? References: Message-ID: <3D22E8A0.7050107@livinglogic.de> Alistair Campbell wrote: > Hi, > > I have class defined as below > > > ... > class Brew: > > def __init__(self): > self.brew_id="" > self.brew_date="" > self.brew_type="" > self.hydro_init='1040' > self.hydro_final='1000' > self.starter="" > self.amt_start="" > > def alcohol(self): > return > ((string.atoi(self.hydro_init)-string.atoi(self.hydro_final))*0.00036251)*10 > 0 This is simpler written as: return ((int(self.hydro_init)-int(self.hydro_final))*0.00036251)*100 Probably faster and no need to import the string module. (Provided you're using Python 2.2) > ... > > > I assign data from a file so the data that goes into the alcohol method > needs to be converted from string. > The problem is that when I try to reference an instantiation of the Brew() > class, i.e; > > current_brew=Brew() > > I can get all the other data items but a call to; > > current_brew.alcohol > > returns > > current_brew.alcohol is not a call to the alcohol method, it is the alcohol method itself. When you want to call the method you always have to specify the (), even if the method doesn't require arguments, so current_brew.alcohol() will work. > So. I know that the calculation of alcohol content is not true but I am just > fiddling and will put in the correct formula when I get round to it. BTW, is there a reason, why hydro_init and hydro_final are strings instead of int's? > But, what am I doing wrong in relation to my definition or calling of the > Brew.alcohol method? Add () and it will work. Bye, Walter D?rwald From martin at v.loewis.de Tue Jul 30 16:27:56 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 22:27:56 +0200 Subject: Good XML tools? References: <3D46D1B5.248A2921@q-survey.be> Message-ID: Laurent Szyster writes: > And allways will be. Python is not the right language to write XML > libraries: it's way too slow. Notice that PyXML is *not* about writing XML libraries in Python - it is about writing wrappers around existing XML libraries for Python. In some cases, this means to write significant parts in Python, in some cases, the wrapper is very thin. PyXML offers the user a choice of libraries: fast ones, convenient ones, portable ones, etc. Since those properties contradict each other, it is the user's choice. > And for Linux there are Python bindings for libxml and libxslt. And indeed, I hope to include those bindings with PyXML one day. > In many case (if not most) XML processing is far easier with a > dedicated language like XSLT. I would question that claim. XSLT gives impressing results, but sometimes, you do want to have a "real" programming language (with assignments, functions, and all that). Regards, Martin From benjl at cse.unsw.edu.au Tue Jul 2 01:17:03 2002 From: benjl at cse.unsw.edu.au (Benno) Date: 1 Jul 2002 22:17:03 -0700 Subject: Teaching programming -- circular data structures References: Message-ID: <332c7c11.0207012117.51f1fc35@posting.google.com> Roy Smith wrote in message news:... > This is more about how people learn to program than about python, but it > happened in python, and I know folks here are interested in teaching > programming... > > There's a guy at work who is mostly a self-taught perl and TCL > programmer. A while ago, I showed him python, and he's very into it > now. We've done a few projects together, of increasing complexity and > sophistication. > No amount of explaining on my part could convince him that such a thing > wasn't evil, or horribly confusing. Although he could not articulate > exactly what bothered him so much, I think he was vaguely scared of some > sort of infinite loop in the code. > > Is this a common thing? I, as an experienced programmer, found the > circular references perfectly reasonable, but it seemed to blow his > mind. Have people teaching programming (or, more precisely, data > structures) see this before; that people have problems understanding > circular data structures the first time they're exposed to the concept? Looks fine to me! I use them all the time :) (Well OK, I sometimes use them when appropriate). The main thing to worry about here is that you can no longer rely on python to clean things up for you. (Reference counting no longer works.) So you either need to use garbage collection, which detects circular dependancies. Or explicitly break the circ. depends but setting them to None. Or finally use the weak refeerences package to avoid the mess. Benno (Not sure that answered the actual question, but anyway!) From Nemesis at nowhere.it Fri Jul 26 13:08:28 2002 From: Nemesis at nowhere.it (Nemesis) Date: Fri, 26 Jul 2002 17:08:28 GMT Subject: Official documentation Message-ID: <26vrha.ra.ln@Nemesis> Hi all, i've downloaded the documentation in pdf format from www.python.org but i can't get it printed. Acrobat return me this message "This document can't be printed", it seems that the pdf files are "print-protected". Can anyone help me? -- _ _ >>Now on Linux<< _ || Home Page: | \| |___ _____ ___ ___|_|___ || http://digilander.iol.it/nemesis2001 | .` | -_| | -_|_ -| |_ -||| e niente sar? pi? come prima ... |_|\_|___|_|_|_|___|___|_|___||| ... o quasi ;) From cliechti at gmx.net Sun Jul 21 07:37:17 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Jul 2002 13:37:17 +0200 Subject: ssh and Python References: Message-ID: e.d.andersen at mosek.com (edadk) wrote in news:ebc0c915.0207210221.46325b2f at posting.google.com: > There is a telnet and ftp object for Python. But how about ssh? often modules are named py... and Google is your friend, so lets search for "pyssh": http://www.google.com/search?q=pyssh chris -- Chris From gerhard.haering at gmx.de Wed Jul 24 18:46:24 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 25 Jul 2002 00:46:24 +0200 Subject: how to count lines in a file ? In-Reply-To: References: Message-ID: <20020724224624.GA2105@lilith.my-fqdn.de> * Delaney, Timothy [2002-07-25 08:31 +1000]: > > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt] > > > > print len(open('/etc/passwd').readlines()) > > There is currently discussion on python-dev of the file object possibly > becoming collectable by GC (and hence not going away immediately the last > reference you know about disappears). :-/ I thought that Python had a reference-counting garbage collector combined with a mark-and-sweep gc?! So that if a refcount goes to zero, I can count on the object being collected immediately? If this is not true, then some of my own code is buggy, too :-( (I didn't target Jython up to now, where the gc works differently due to the JVM) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fakeaddress at nowhere.org Fri Jul 5 15:15:50 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 05 Jul 2002 19:15:50 GMT Subject: deleting a file References: Message-ID: <3D25F07F.4020606@nowhere.org> Teja Sastry wrote: > > > I want to delete a file in the current directory from inside a python > program. How do i go about doing it. See: os.remove(path) --Bryan From svbrk at start.no Thu Jul 4 09:54:18 2002 From: svbrk at start.no (Svein Brekke) Date: 4 Jul 2002 06:54:18 -0700 Subject: Full-screen display in Tkinter Message-ID: <21298535.0207040554.6caeed01@posting.google.com> I am building a slide show application with Tkinter, and need to create a full-screen window, i.e. supressing title bar and start menu etc. Is that supported in Tkinter? I work on Win2000 with python 2.2, but would like my code to be portable to other platforms. Any help or hints will be appreciated. Svein Brekke From egbert at bork.demon.nl Tue Jul 30 11:15:37 2002 From: egbert at bork.demon.nl (Egbert Bouwman) Date: Tue, 30 Jul 2002 17:15:37 +0200 Subject: Cookbook: Associating multiple values with each key in a dictionary Message-ID: <20020730171536.A992@bork.demon.nl> On page 9 of the free chapter 01 of their cookbook alex and associates present a way to associate multiple values without duplications to a dictionary: d2 = {} d2.setdefault(key, {})[value] = 1 This produces nested dictionaries with unique keys, however with values that I don't need. I prefer a solution with lists, as in the one with duplications allowed: d1 = {} d1.setdefault(key, []).append(value) This function creates a multivalued list without duplications: def keyplus(dic,key,value): dic.setdefault(key, []) if value not in dic[key]: dic[key].append(value) but now I have a feeling that some one-liner is possible. If not, don't we need then a list method 'append_if_not already-there' ? -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From peter at engcorp.com Wed Jul 10 22:29:53 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Jul 2002 22:29:53 -0400 Subject: A better self References: Message-ID: <3D2CEDA1.4ACA69FE@engcorp.com> "Bo M. Maryniuck" wrote: > > I still can't catch why people raise and reply to this really nonsense thread > ("self" vs. "dot" or "this" or "pumpkin" or whatever)? Just go and design + > develope your own language... This is more worse example, if somebody like > use a dot, instead "self": > > .__.foo = .o > .__.__doc__ = .__.foo.__doc__ > > This is more like Morse language... > > bo at oberon:(~) morse -s '.__.foo' > .-.-.-, > .-.-.-, > ..-., > ---, > ---, Actually, the Morse is much easier to write, since it doesn't require the Shift key (god how I hate underscores) and easier to read, since it's harder to tell how many underscores there are in a series of them since fonts generally don't have any space between them, unlike hyphens. If this change were implemented, it would make Python less readable and writable than Morse code, and I therefore nominate it for honor of being the most damaging change at the smallest cost! <_.7 wink> -Peter From tg5027 at citlink.net Wed Jul 24 16:31:11 2002 From: tg5027 at citlink.net (terry) Date: Wed, 24 Jul 2002 16:31:11 -0400 Subject: Numeric data question In-Reply-To: <3D3EF9AD.A0F661BC@noaa.gov> References: <3D3EF9AD.A0F661BC@noaa.gov> Message-ID: >> Do any programming languages have a built in "money" type? >> How is this problem solved in them? Hmmm, my question is getting answered - by the time it is, I will have found out how to properly ask it. I've been programming in MS Access VB since V1, so I've come to accept that a variable that references data that's Access's Currency data type always gets calculated with properly - i.e. no floating point problems. Clearly VB is using that data type information and resolving it internally. But also, there is a declarable data type of Currency for other variables. I believe that Cobol has one too. You're example is what is not acceptable (to the accounting community) - although I did have to use that back in the 60s to write FORTRAN accounting programs and everyone just accepted being a little off. I've also used routines that are based on strings and integers. They all share the common trait of being ugly. >> I imagine someone out there has written a money class already. >> If not you will be doing a service to the community if you do >> it. Alex gave me a source ... I wouldn't know where to start yet. >> no comment on whether you are loonie or not. Thanks, and thanks for your comments. terry From gerhard.haering at gmx.de Tue Jul 9 04:30:40 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 10:30:40 +0200 Subject: Using Python for processing of large datasets (convincing man agment) In-Reply-To: <3D2A98D4.4040002@ob_scure.dk> References: <3D2A98D4.4040002@ob_scure.dk> Message-ID: <20020709083040.GB1252@lilith.my-fqdn.de> * Thomas Jensen [2002-07-09 10:03 +0200]: > Delaney, Timothy wrote: > > [snip - multiple results] > > >or you can actually do it in your sql call - IIRC correctly as a "batch" > >call, or just simply as: > > > >"select a from T_A;select b from T_B;select c from T_C;" > > > >Doing this should reduce your network latency massively. > > I've used this method before, but never to reduce latency, thanks for > the advice! Before you get too excited: .nextset() in the Python DB-API is not meant to be used with multiple select statements sent in one shot. It's meant for stored procedures only. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 24.9 ?C Wind: 1.0 m/s From trash.mail at gmx.ch Fri Jul 5 14:07:53 2002 From: trash.mail at gmx.ch (Roger Ineichen) Date: 5 Jul 2002 11:07:53 -0700 Subject: dynamic path to a method ??? Message-ID: <51a64474.0207051007.19cb0441@posting.google.com> Can anybody tell me how I can construct a dynamic path to a method in an other python class? my situation is: I get the classname, methodname and attributes by a dynamic form. They are strings and the names and attributes are dynamic. I do a iteration over the request an split the names and attributes. Example after iteration over the request: class (instance) = 'personManager' method = 'addPerson(firstname='', lastname='')' attribute1, firstname = 'max' attribute2, lastname = 'miller' how can I construct a dynamic path like: personManager.addPerson( firstname='max', lastname='miller') Thanks for a answer... and have a nice weekend. Roger From nas at python.ca Thu Jul 25 12:18:38 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 25 Jul 2002 09:18:38 -0700 Subject: Speed up Python by up to 5% ? In-Reply-To: ; from edream@tds.net on Thu, Jul 25, 2002 at 03:14:42PM +0000 References: Message-ID: <20020725091838.A13268@glacier.arctrix.com> Edward K. Ream wrote: > It may be possible to speed up the Python interpreter 3% to 5% with a > trivial modification. The "things to do" logic cannot be moved into the SET_LINENO opcode because "python -O" removes the SET_LINENO instructions. You should work from the CVS source if you want to work on this optimization. The CVS version of the code already has some optimizations over 2.2.x. Also, be aware that the code in ceval.c is touchy. It's easy to get a 5% speedup on one type of CPU while losing 5% an another. It's also highly dependent on the benchmark used. The current thinking is that a 10% to 15% speedup could be had by changing ceval to use a register VM rather than a stack VM. Skip Montanaro has started work on a register VM. I've ported his work from Python 1.5.2 to 2.x. The register VM is nearly done. The major work remaining is to modify the compiler. The current compiler has gotten really hairy over the years. Jeremy Hylton is working on a new one for Python 2.3. Since it should be much easier to modify the new compiler I'm going to wait until it's done rather than trying to modify the old one. Neil From jaeggi at NOSPAMembl-heidelberg.de Wed Jul 3 09:13:34 2002 From: jaeggi at NOSPAMembl-heidelberg.de (Daniel Jaeggi) Date: Wed, 03 Jul 2002 15:13:34 +0200 Subject: baffling bug in this bit of code! Message-ID: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> Hi, I'm reasonably new to python but I've used various other languages before. The bug in the following bit of code has got me banging my head as it should be trivial. If anyone can help, I'd be most grateful. This snippet: # find maximum dimension max_x = 0 max_y = 0 for node in self.nodes.keys(): # first x x = self.nodes[node].location.x print "for node",node,"x is",x print "max_x = ",max_x if (x > max_x): print "updating max_x" max_x = x # then y y = self.nodes[node].location.y print "for node",node,"y is",y print "max_y = ",y if (y > max_y): print "updating max_y" max_y = y # and print this out for now print "Max x dim is",max_x print "Max y dim is",max_y produces this output: for node COG0857 x is 269 max_x = 0 updating max_x for node COG0857 y is 8 max_y = 0 updating max_y for node COG0282 x is 312 max_x = 269 updating max_x for node COG0282 y is 145 max_y = 8 for node COG0281 x is 30 max_x = 312 for node COG0281 y is 157 max_y = 8 for node COG0280 x is 170 max_x = 312 for node COG0280 y is 114 max_y = 8 Max x dim is 312 Max y dim is 8 Why does max_x get located and not max_y? Or, more specifically, why does max_y get correctly updated in the first iteration and not subsequently?! Please save me from insanity! Dan _ "There must and shall be aspirin. If I do not have aspirin, I shall die." From djc at object-craft.com.au Mon Jul 29 10:07:17 2002 From: djc at object-craft.com.au (Dave Cole) Date: 30 Jul 2002 00:07:17 +1000 Subject: order of test References: Message-ID: > Andrew McNamara writes: > > >can we be sure of the order of a test expression ? > > >i mean that > > >t=["one","two"] > > >x=10 > > >if x<2 and t[x]=="oups": > > > > > >will never throw an exception if t[2] will be tested before x<2 > > > > It's called lazy evaluation, > > No it's not! Lazy evaluation is more like Haskell... I think the proper term is short circuit evaluation but don't quote me... - Dave -- http://www.object-craft.com.au From aleax at aleax.it Thu Jul 25 04:29:22 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 08:29:22 GMT Subject: Which gui for slow (133 Mhz) pc References: <3d3b9eaa.7275472@news.utanet.at> <9Z%_8.3000$uh7.206@sccrnsc03> <3d3eefb4.4802490@news.utanet.at> Message-ID: Francesco S. wrote: ... >>> What gui can you recommend for my slow pc (win95). ... > Maybe I have to buy a new computer, this will be the best solution. Yes. Not sure about Austria, but around here in Italy you can get used PC's that run rings around yours for 250-300 euros. Meanwhile a Pentium-133 with halfway decent RAM is (a bit of overkill, but OK) fine for such tasks as a dedicated router, firewall and proxy/masquerader for a LAN. My home workplace has grown to 5 desktop PC's, plus three laptops occasionally on, with 10/100 Ethernet w. switches among them and ADSL to the world (with ISDN on autodial as a backup should the ADSL ever go down). At the center sits a Pentium-90 running OpenBSD 3 with only one optional piece of software... Python, of course. It handles all of the networking, proxying, firewalling, etc, and talks to the ADSN router on a physically separate Ethernet. The trick is that the old, VERY old Pentium-90 PC has no graphics installed AT ALL. Not even a monitor (nor kbd, nor mouse) -- I just ssh in for occasional maintenance, but there's not much need of that... for this kind of load, OpenBSD 3 can be installed to do everything on its own, with a little tiny help from a few strategic Python scripts. Of course, my "home central server" PC is not powerful enough to run Win-95, by any means. It IS by far enough to do just about anything else I need from it, though. I've even toyed with running Squid there for a while, for example, though my family's usage patterns are such that it was no benefit, so I took it down again. Alex From krzysiek at dgt-lab.com.pl Mon Jul 8 02:45:06 2002 From: krzysiek at dgt-lab.com.pl (Krzysiek Czarnowski) Date: Mon, 8 Jul 2002 08:45:06 +0200 Subject: Is there a re guru out there? Message-ID: <000c01c2264a$fee21520$2706a8c0@dgtlab.com.pl> I try to convert some LaTeX constructs to "plain" equivalents like \(,\) --> $, \[,\] --> $$ and \frac{...}{...} --> {...\over ...}. The \frac bit appeared not to be trivial since ... should be balanced with respect to { }. I found it hard to specify with regular expressions. Is it possible to achieve with re? Best solution? In practical situations even a partial solution would do. For example the following no_group = r"[^\{\}]" grouped = r"\{%s*\}" % no_group balanced = r"((%s)|(%s))*" % (no_group, grouped) matches any "one-level deep" balanced expression (roughly tested). Is there a better way than just to proceed like this? Krzysztof From jwilhelm at outsourcefinancial.com Wed Jul 17 14:34:37 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 17 Jul 2002 11:34:37 -0700 Subject: python2 import trouble (linux - redhat) In-Reply-To: <3D35A628.A9ADF9B6@noaa.gov> References: <20020714141757.128895ce.mmellor1@yahoo.com> <3D35A628.A9ADF9B6@noaa.gov> Message-ID: <1026930878.3325.1.camel@jwilhelm.ofsloans.com> > #!/usr/bin/python2.2 > (or whatever version) > for their admin tools. > > The point is that the problem with redhat has not been that it uses > 1.5.2. but that all the admin tools require 1.5.2 to by what "python" > invokes. If they has specified the version on thei #! lines, then it > would be no problem to install newer versions as well, and they probably > would ahve provided packages to do so as well. > > If all they have done is upgrade to 2.2 or whatever, then we'll all have > the same problem in a another year or two :-( > > -Chris Actually, if I remember right from when I was browsing the package list, Python 2.2 was the -only- version they provided. So "In Theory", they have completely deprecated 1.5.2. --Joseph Wilhelm From david at forestfield.co.uk Mon Jul 22 06:22:00 2002 From: david at forestfield.co.uk (David Hughes) Date: Mon, 22 Jul 2002 11:22 +0100 (BST) Subject: Failure to set locale Message-ID: As a fairly-newbie, I'm trying to use the locale module for the first time, using Python 2.2 under Win2k. If I call locale.setlocale with a locale of 'de' for Germany or 'es' for Spain, I get "Error: locale setting not supported". However, if I use 'ge' and 'sp'(which aren't the ISO approved names), the correct locale is set. The only way I can get the locale set for Denmark is to actually change the region in Windows' Control Panel. I have also tried using the strings returned from locale.normalize that are supposed to be suitable for use with locale.setlocale but without success. Can anyone suggest what's going wrong, please? From gerhard.haering at gmx.de Mon Jul 1 00:59:34 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 1 Jul 2002 06:59:34 +0200 Subject: Q: Status of MySQL & Python? In-Reply-To: References: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> Message-ID: <20020701045934.GA7687@lilith.my-fqdn.de> * John Hall [2002-07-01 04:35 +0000]: > On Mon, 1 Jul 2002 05:33:16 +0200, Gerhard H?ring wrote: > >* John Hall [2002-07-01 03:12 +0000]: > >> When trying to run the dbBrowser from Samples, MySQLdb/__init__.py > >> does a traceback in line #27 because _mysql is not found. Sure 'nuff, > >> I don't have that. I do have souce C source: _mysql.c Here you tell you have a _mysql.c file lying around. > > [...] > Hi Gerhard, > thanks for the quick reply, but I did NOT D'L the source distribution, > but the binary for Windows. Now you tell me you have used the Windows installer. This one doesn't include any C source files. Did you really execute MySQL-python-0.9.1.win32-py2.2.exe (replace 2.2 as appropriate), didn't you? > Then I ran Setup, > did the c:\mysql\bin mysql-nt --install > then started the service, > then got MySQL Studio and created a database & a table. > I definitely have not compiled anything. > > Should I have a _mysql library or _mysql.py file somewhere? Yes. Under Python 2.2 there will be a MySQL package in site-packages and a .pyd and a module for the exceptions also in site-packages. In earlier Python versions, I think they're installed directly into the Python installation directory. Short and sweet, it doesn't find your _mysql.pyd. I've heard from one user who had strange problems that he could only explain with FAT32 or NTFS weirdness (don't remember which filessystem he used). The zip file I gave him solved his problem: http://www.cs.fhm.edu/~ifw00065/downloads/MySQL-python-0.9.1-Python22.zip it can be installed by unzipping it, changing into the created directory on a command prompt and running "python setup.py install" yourself. If you have the same problem and this workaround works for you, please keep me updated. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fredrik at pythonware.com Thu Jul 25 13:13:27 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Jul 2002 17:13:27 GMT Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: Kristian Ovaska wrote: > I'm sure there are alternative regular languages that are more > readable, altough I've never come across one. The problem of such > languages is, I guess, that since they are more verbose than this very > compact CS notation, you can't just wrap them in a string, but would > need to expand the underlying language or you could just use the language as is, instead of forcing people to write stuff in a really ugly sublanguage. for some examples, see ping's rxb: http://web.lfw.org/python/ and greg ewing's plex: http://www.cosc.canterbury.ac.nz/~greg/python/Plex/ From paul at boddie.net Fri Jul 12 07:47:10 2002 From: paul at boddie.net (Paul Boddie) Date: 12 Jul 2002 04:47:10 -0700 Subject: Python for data driven website? References: Message-ID: <23891c90.0207120347.13313ad7@posting.google.com> "Micah Mayo" wrote in message news:... > > My company is in the early stages of building a web application for > accountants. Right now we're trying to choose which technology we're going > to write it in In the context of Python, Daniel Dittmar has recently adapted my Web Frameworks Overview for the Python Language Wiki: http://www.python.org/cgi-bin/moinmoin/WebProgramming Due to an "upgrade" of my mail service, it's been difficult to contact him to express my approval, so here it is in public. ;-) Paul From sandeep182 at hotmail.com Mon Jul 8 10:50:20 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: 8 Jul 2002 07:50:20 -0700 Subject: How can I retrieve the ID of the last record I added? Message-ID: I'm using mxODBC on Linux to access MySQL and MSSQL. I'm performing inserts from within a transaction and need to get the value of the auto-incremented column for the just inserted row. Is there a method or select I could execute to get that value? Thanks From dreed at capital.edu Sun Jul 14 14:59:30 2002 From: dreed at capital.edu (Dave Reed) Date: Sun, 14 Jul 2002 14:59:30 -0400 (EDT) Subject: Pros/cons of various PostGres modules In-Reply-To: <20020714183312.GA2487@gargamel.hqd-internal> (message from Gerhard Haering on Sun, 14 Jul 2002 20:33:12 +0200) References: <545cb8c2.0207130852.74d88a5@posting.google.com> <20020714005307.GA4849@gargamel.hqd-internal> <200207141808.g6EI87r30238@localhost.localdomain> <20020714183312.GA2487@gargamel.hqd-internal> Message-ID: <200207141859.g6EIxT120262@fourier.capital.edu> > Date: Sun, 14 Jul 2002 20:33:12 +0200 > From: Gerhard Haering > > * Dave Reed [2002-07-14 14:08 -0400]: > > > Gerhard wrote: > > > PyGreSQL is IMO very badly maintained: there was a serious bug with > > > cursor.fetchone() always returning the first row of the resultset, which > > > made cursors basically unusable. It was known for over a year until > > > somebody (me) got annoyed enough to take the half-an hour to look into > > > the Python and C code, write a patch and submit it to the PostgreSQL > > > developers. > > > > Thank you! I've been bit by this bug. PyGreSQL is the one that comes > > with postgresql - correct? > > Yes, and patches and bug reports should go to the PostgreSQL project. > > > I found it worked fine on my Red Hat 7.3 system with their python 1.5.2 > > rpm, but as soon as I tried to get it working with my installation of > > python2.2 I had this problem. > > You were also using a different PostgreSQL version, then: the bugfix ended > up as a last-minute fix in PostgreSQL 7.1.3. Actually, I was trying to recompile the src.rpm that came with Red Hat 7.3 to use Python2.2 and still ended up with the bug. I was starting to think it was a strange interaction with different versions of Python. Hmm, I wonder why that didn't work. > > Can you tell me where the source for this patch is so I can make certain > > it's included in any postgresql installations I make? > > Just ensure you're using the PyGreSQL (in src/interfaces/python) from at > least PostgreSQL 7.1.3. > > > As I understand it - please correct me if I'm wrong - I could install > > pyPgSQL and it would work w/o any changes to my code (other than > > importing that module) if I've stayed with the DB-API. Is this correct? > > In theory, you should only need to adjust the module and the parameters to > the connection method. There are, however, certain differences, mostly wrt > to different ways to access PostgreSQL-specific features like notifications > or exotic SQL features like ARRAYs. Thanks for the info. Dave From b.maryniuk at forbis.lt Thu Jul 4 11:42:39 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 17:42:39 +0200 Subject: sending a file through sockets In-Reply-To: References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> Message-ID: <200207041742.39223.b.maryniuk@forbis.lt> On Thursday 04 July 2002 17:13, Fredrik Lundh wrote: > http://py-howto.sourceforge.net/sockets/sockets.html That's cool. Since I never sent any binary via socket, it'll be suitable for me too. ;-) -- Sincerely yours, Bogdan M. Maryniuck linux: the choice of a GNU generation (ksh at cis.ufl.edu put this on Tshirts in '93) From jepler at unpythonic.net Wed Jul 17 20:56:54 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 17 Jul 2002 19:56:54 -0500 Subject: socket.gethostbyaddr() is slower than Christmas In-Reply-To: References: Message-ID: <20020717195654.A18565@unpythonic.net> On Wed, Jul 17, 2002 at 04:27:24PM -0600, Jason R. Mastaler wrote: > On a certain Redhat-7.3 system, socket.gethostbyaddr() calls to the > localhost are taking upwards of 30 seconds to return. What would > account for such behavior? Is this a bug? gethostbyname() is very little more than a wrapper around the standard library function. I wouldn't expect Python to be the reason this is slow for you, but instead I'd expect some kind of local configuration problem. Jeff From tjreedy at udel.edu Wed Jul 24 19:20:49 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Jul 2002 23:20:49 GMT Subject: A better self (again) References: <2259b0e2.0207241336.498c5dd3@posting.google.com> Message-ID: > I suggest a simple recipe to avoid typing self I really admire the people who think and compose code in their head so fast that typing 's.' is a significant bother even after it becomes pretty automatic. TJR PS. For methods like __add__(s,o), I use 'o.' for other. I do not think I would like the breaking of the current symmetry between the two parameters. From notdanielt3 at gte.net Tue Jul 2 15:43:11 2002 From: notdanielt3 at gte.net (Daniel T.) Date: Tue, 02 Jul 2002 19:43:11 GMT Subject: Memory leak in Mac Python IDE ? References: <020720021354486814%pecora@anvil.nrl.navy.mil> Message-ID: "Louis M. Pecora" wrote: >I run the following code in a file under the IDE (under System 9.1 on a >G4 Mac with 40 MB allocated to Python 2.2 IDE): > >#--Test code > >from Numeric import * > >tab1=zeros((200000,4)) >print shape(tab1) > >#--End Test code > >Check the memory under 'About this Computer' in the Finder. > >Then change tab1 to tab2 and run again (I hit cmd-R several times >quickly and that seems to worsen the problem - don't know why), then >check memory and see that more is used up. Continue this process to >tab3, tab4, etc. and eventually I get an exception -- ran out of >memory, cannot allocate more. Sure enough, under 'About this Computer' >in the Finder, the memory is used up. > >Looks like a memory leak to me, but maybe the IDE is set up to keep >variables around, hence tab1, tab2, etc. are never garbage collected >after the module is run with a new varible name, e.g. tab2 in place of >tab1. > >Anyone know? I take it you are running this in the "Python Interactive" window? Yes, the various objects you are creating stay around until you explicitly get rid of them. ie: del( tab1 ) will get rid of tab1 and free some memory. -- Improve your company's understanding of objects... Hire me. From jblazi at hotmail.com Sat Jul 13 17:28:05 2002 From: jblazi at hotmail.com (JB) Date: Sat, 13 Jul 2002 23:28:05 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: <3d30999a_4@news.newsgroups.com> > I bet you > can do better by exploiting the specifics of this case!-) Well, I can use the fact that I know the maximal sorting key in advance. So I can append sentinel entries to both lists and this makes things much easier. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From fredrik at pythonware.com Sun Jul 28 06:07:50 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 28 Jul 2002 10:07:50 GMT Subject: connection problems References: Message-ID: giovanni wrote: > Hello. In these days I am finding some problems in > reaching www.python.org. Is it just a problem of > mine or what? I can traceroute/ping from here, but the webserver doesn't want to talk to me. you can find a list of mirrors here: http://www.cwi.nl/www.python.org/Mirrors.html From shagshag13 at yahoo.fr Tue Jul 9 07:18:28 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 13:18:28 +0200 Subject: sorting many arrays from one... Message-ID: hello, i'm looking for an "efficient" way of sorting many arrays driven by one, for example drive = [1, 4, 2, 3] other1 = [a, b, c, d] other2 = [ k, j, h, l ] other3 = [14, 18, 19, 11] and i get : drive = [1, 2, 3, 4] other1 = [a, c, d, b] other2 = [ k, h, l, j] other3 = [14, 19, 11, 18] by now i use a list (copy from 'drive') that i sort and then iterate to find index in 'drive' and build my others arrays, but i'm asking if i shouldn't use a dict (for example { 1 : (a, k, 14) , 4 : (b, j, 18) ...) then sort keys and building arrays from dict values... but maybe you have betters ideas ? thanks, s13. From me at michaelbauers.com Thu Jul 11 07:13:12 2002 From: me at michaelbauers.com (Michael Bauers) Date: Thu, 11 Jul 2002 06:13:12 -0500 Subject: Lunar lander source (BMP files) Message-ID: Oh yeah, the Lunar lander program also needs a few BMP files. www.michaelbauers.com/lander.bmp www.michaelbauers.com/landerc.bmp The landerc one should be an image of a crashed lander, but it is identical at present. From mnations at airmail.net Tue Jul 23 17:15:05 2002 From: mnations at airmail.net (Marc) Date: Tue, 23 Jul 2002 16:15:05 -0500 Subject: Problems with after_cancel() Message-ID: <3d3dc4dd@post.usenet.com> **** Post for FREE via your newsreader at post.usenet.com **** !Sorry if this is a repost. I'm not sure if the original one made it! I have what I think is a very simple after call and cancel combo: ... def check(): print "in check" if globals.stop.isSet(): globals.status.clear() globals.stop.clear() print "Application is stopped" return globals.master.after(100, check) def function(gui): gui.print("do something") id2 = check() print id2 globals.master.after_cancel(id2) print "Should be stopped" ... Check is called to begin the process and returns id2, which should be the id for the after command. When I print the value of id2, I get something like "after#25". But when I do the after_cancel command, it doesn't stop. As far as I can tell, this is the right way to do it, but it's not working. Could someone please tell me what the problem is? Thanks, Marc -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From nathan at cjhunter.com Fri Jul 12 15:55:25 2002 From: nathan at cjhunter.com (Nathan Cassano) Date: Fri, 12 Jul 2002 12:55:25 -0700 Subject: Linking to Python 2.2 In-Reply-To: Message-ID: <006501c229de$104bb230$2901a8c0@amos> Thanks for your help Martin, > The correct way depends on the operating system. In this case, you > should study and understand the error messages, and correct them. > > > /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:148: > > undefined reference to `sin' > > This is an error. The symbol "sin" is defined by the math library, so > you need to link with "-lm". Add this linker option, then see what > other errors remain. Proceed for other undefined symbols in the same > way: find out where these symbols are defined, and add the missing > libraries. > In principle, you can use both distutils and the installed > Makefile.pre to obtain the necessary information in a > platform-independent way. However, it would be simpler to just adjust > the build process manually if you target only a few systems. I guess I had a mental black there for a moment. Yes, -lm fixed the problem. I found some other applications that use embedded Python, was able to reuse parts of their autoconf scripts and now it's all compiling fine. Thanks again! Nathan From tlal at nospam.invalid Fri Jul 12 02:28:39 2002 From: tlal at nospam.invalid (Thierry Lalinne) Date: Fri, 12 Jul 2002 06:28:39 GMT Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> Message-ID: In article <3D2C3458.1090902 at thomas-guettler.de>, zopestoller at thomas- guettler.de says... > Does someoone know an editor for editing > hierarchical text data? KeyNote is a nice free outliner/rtf editor with tons of features. It's written in Delphi (win32). You can find it here: http://www.lodz.pdi.net/~eristic/free /Thierry Lalinne From huaiyu at gauss.almadan.ibm.com Mon Jul 15 14:04:05 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 15 Jul 2002 18:04:05 +0000 (UTC) Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: holger krekel wrote: >Huaiyu Zhu wrote: >> Readability for machines does not have to come at the expense of readability >> for humans. A few years back I experimented with an indentation based data >> format that is: >> >> - as readable as emacs's outline mode >> - reduce to common conventions like this paragraph for simple cases >> - allow mixed nested structures of set, sequence, dictionary, and seqdict >> - can include binary data >> - can handle different encodings/encryptions in different elements >> - with average less than 5% bloat, in contrast to XML's over 100% bloat > >do you have any code or design documents for this? > >Sounds quite interesting. The basic idea is quite simple: consider a data structure as a tree; denote the type of branching at each node; indent the subtrees. It appears to me that indentation is easier to handle than quotes and escapes. Here's a simple example: [] # This is a sequence - first item - second item with multiple lines -{} # The third item in the sequence is itself a set - element 1 -## encryption=somescheme # element 2 is binary data the binary data goes here which can be multiple lines as well -{:} # element 3 is a dictionary - key1: value1 - key2: value2 -[:] # The third item in the sequence is itself a seqdict - key1: value1 - key2:- This value is multiline Which keeps the same indentation So that it is human readable There is a complication that I cannot recall at this moment that requires the indentation to be at least two characters. The outermost level could be handled by blank lines to make it more readable. So a bibtex type of file would be like []{:} - bibkey: ... - author: ... - title: ... - bibkey: ... - author: ... - title: ... For deeply nested structures, it is more efficient but less readable to use 0)- a 1)- b 2)- c 3)- d 2)- e in place of - a - b - c - d - e Assuming that the newline character occurs in binary data with 1/256 frequency, and assume that the structural denotations at the beginning of each line occupies less than 10 characters, then the bloat factor for binary data would be less than 5%. OK, hope this makes sense. If this is still interesting I'll dig the thing out. I have documents and code (perl and python) at home, but I'll have to dig through several tar files to find them, maybe on a hard disk that's not mounted. This all started back when I tried to use perl to manage my bibtex files while I did not know Python, so some of them used % and @ to represent hash and array following perl. The format itself also changed somewhat over the years. So don't expect those to be more organized than this post. :-) They certainly have more details, though. Huaiyu From bdesth at nospam.free.fr Wed Jul 17 13:59:31 2002 From: bdesth at nospam.free.fr (laotseu) Date: Wed, 17 Jul 2002 13:59:31 -0400 Subject: uniform interface for MySQL & MSSQL References: Message-ID: <3D35B083.8000605@nospam.free.fr> Johann wrote: > I would like to write a hybrid application which works on Linux and > Windows platform so I need the same API for SQL (MySQL and MSSQL2K). I Err... Just a stupid question : why using MSSQL ? MySql runs on Windows too. laotseu > would like to use Python Database API Specification v2.0 > (http://www.python.org/peps/pep-0249.html) and I found a nice > implementation such interface at > http://www.nmt.edu/tcc/help/lang/python/dbhelpers.html. The problem is > there is no mssql module, only sybase, oracle and mysql. I tried to > use sybase on mssql but it's does not work because I have "no ctsybase > Python module". > I do not want to use odbc because I want to move internal db cursor by > arbitrally number of records. > From bokr at oz.net Wed Jul 24 21:36:07 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 01:36:07 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <7xn0sgpte7.fsf@ruckus.brouhaha.com> Message-ID: On 24 Jul 2002 17:01:52 -0700, Paul Rubin wrote: >bokr at oz.net (Bengt Richter) writes: >> >> If the main purpose of the module is to provide one function, I think >> >> it's cleaner to be able to import the module and call the function >> >> without special tricks. >> Or just use your own trick, e.g., given >> >> ----< PR.py >------ >> #PR.py for Paul Rubin >> def PR(): return 'Hi Paul' >> ------------------- >> >> Define one-line trick: >> >>> def PRimport(name, locs=locals()): locs[name] = getattr(__import__(name),name) >> ... >> >> And use it thus >> >>> PRimport('PR') >> >>> PR >> >> >>> PR() >> 'Hi Paul' > >But that's another special trick, more hair to remember. Why not just >do the obvious thing and make modules work the same way as other objects? Ok, if you have a single function, add two lines of fixed boilerplate to your module if you want it to work that way: ---------------------------- #PR2.py for Paul Rubin def PR2(): return 'Hi Paul' import sys sys.modules[__name__] = eval(__name__) ---------------------------- >>> import PR2 >>> PR2() 'Hi Paul' >>> dir() ['PR2', '__builtins__', '__doc__', '__name__'] Note that you could have substituted foo for eval(__name__) if you wanted to bind PR2 to function foo in the module. Regards, Bengt Richter From gcordova at hebmex.com Wed Jul 3 15:17:49 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 3 Jul 2002 14:17:49 -0500 Subject: REPEAT... UNTIL ? Message-ID: > > Hi, > > what do you think about adding "repeat .... until" to python syntax? > Often a "repeat-until" is better to use than a "while" loop. > Guido 8-) ??? > > Ingo > Given the following: bexpr === boolean expression, exit loop when true. then: """ repeat: ... ... ... until bexpr """ would be exactly the same as: """ while 1: ... ... ... if bexpr: break """ no? -gustavo From tony.papadato at macro4.com Tue Jul 23 10:01:37 2002 From: tony.papadato at macro4.com (tony papadato) Date: Tue, 23 Jul 2002 16:01:37 +0200 Subject: Python on W2000 Message-ID: <000a01c23251$76e64f20$b700000a@m4ipc20> it is possible to generate an executable file and run it on different machines without python installed on them ? Best regards Tony Papadato papadato at infinito.it -------------- next part -------------- An HTML attachment was scrubbed... URL: From bowman at montana.com Tue Jul 16 09:37:45 2002 From: bowman at montana.com (bowman) Date: Tue, 16 Jul 2002 07:37:45 -0600 Subject: Serial Port Returning Garbage. Why? References: Message-ID: <%gVY8.204$fK3.80978@newsfeed.slurp.net> max wrote: > > Serial Connector: 3-wire Are you using a hardware handshake or QON/QOFF? From imbosol at vt.edu Sat Jul 27 16:02:20 2002 From: imbosol at vt.edu (Carl Banks) Date: Sat, 27 Jul 2002 16:02:20 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: Fredrik Lundh wrote: > Carl Banks wrote: > >> So now you're advocating building a framework of closures to replace >> the lambdas? This is what appears odd to me: you want me to inline >> sorts in the interest of not overgeneralizing, but it seems the same >> can be said by your use of make_items_accessor above. > > don't feed the troll. I'm sorry, I didn't realize Martelli was trolling. I'll try not to feed him. :) Seriously, no offense was intended. When he suggested using a wrapper function like make_items_accessor, after advising against a wrapper for sorts because of overgeneralization concerns, it rightly seemed odd to me (especially since I tend to do the opposite), and I wanted to point that out. That point is, overgeneralization concern itself is not good enough reason to avoid wrapping a function or building a framework, without more information about the circumstances. I'm sorry if it seemed like I was trolling. -- CARL BANKS http://www.aerojockey.com From skip at pobox.com Tue Jul 9 15:10:20 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Jul 2002 14:10:20 -0500 Subject: Splitting a string every 'n' In-Reply-To: References: Message-ID: <15659.13596.814225.666911@gargle.gargle.HOWL> Huaiyu> To work with any int n, change to one of these Huaiyu> rex = re.compile('.{,%s}'%n, re.DOTALL) # keeps remainder segment I think you want {1,%s}. Note the spurious empty string at the end if at least one character isn't required: >>> import re >>> rex = re.compile(r"(.{,4})") >>> re.findall(rex, "abcd") ['abcd', ''] >>> rex = re.compile(r"(.{1,4})") >>> re.findall(rex, "abcd") ['abcd'] >>> rex = re.compile(r"(.{,4})") >>> re.findall(rex, "abcde") ['abcd', 'e', ''] >>> rex = re.compile(r"(.{1,4})") >>> re.findall(rex, "abcde") ['abcd', 'e'] -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From pecora at anvil.nrl.navy.mil Wed Jul 10 10:10:11 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 10 Jul 2002 10:10:11 -0400 Subject: Why self? References: <3D2B5331.7090104@onsitetech.com> Message-ID: <100720021010112153%pecora@anvil.nrl.navy.mil> In article <3D2B5331.7090104 at onsitetech.com>, Robb Shecter wrote: > should really be written like this: > > self.__y = self.__x**2 * self.__t/self.__z + self.__a * FFT(self.__tseries) > > to be safe from accidental overwriting by subclasses. Now there's a > beauty! :-) Eeeewwwww! I am not familiar with the double underscore syntax. Can you explain it. OK, I guess I can go online and read about it. I'm a Python user, but not guru. Sorry. -- Lou Pecora - My views are my own. From tdelaney at avaya.com Sun Jul 21 19:49:44 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 22 Jul 2002 09:49:44 +1000 Subject: Python Sets (no not those sets) Message-ID: > From: timothyrandolph at yahoo.com [mailto:timothyrandolph at yahoo.com] > > http://labs1.google.com/ > > and type in: > > Tim Peters > Fredrik Lundh > Alex Martelli > Guido von Rossum Lots of fun - enter your own name, and one of those people ... Tim Delaney From me at michaelbauers.com Thu Jul 11 18:58:18 2002 From: me at michaelbauers.com (Michael Bauers) Date: Thu, 11 Jul 2002 17:58:18 -0500 Subject: pygame question Message-ID: I was curious as to why 'is K_SPACE' worked, but 'is K_r' did not. I had to change the test for 'r' to ==. * code snippet * elif (event.type is KEYDOWN and event.key is K_SPACE): # DO SOMETHING elif (event.type is KEYDOWN and event.key == K_r): # DO SOMETHING ELSE From brian at sweetapp.com Fri Jul 5 12:46:47 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 5 Jul 2002 09:46:47 -0700 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <1025856511.20586.13.camel@lestat.howden.press.net> Message-ID: <000401c22443$8f20dea0$bd5d4540@Dell2> John Abel wrote: > I've set up an server, and client, which works OK, but now I want to > secure the server. Is there a way I can query the IP of the connecting > client? I've looked through the documentation, and can see that > SimpleXMLRPCRequestHandler is based on BaseHTTPServer, which has > client_address, but I can't seem to get access that variable. > > Any pointers would be much appreciated. You could base your security on IP address or you could have the client send a cookie with each RPC call. Using your IP address technique, you can subclass SimpleXMLRPCRequestHandler and write your own do_POST or _dispatch method. Your implementation can be very simple; just check client_address and call the base class implementation if it is correct. You must also register your SimpleXMLRPCRequestHandler subclass with the SimpleXMLRPCServer. Here is an untested example: class AuthenticatingSimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): def _dispatch(self, method, params): if self.client_address not in list_of_valid_addresses: raise Exception, "your IP address is not authorized" else: SimpleXMLRPCRequestHandler._dispatch(self, method, params) server = SimpleXMLRPCServer( some_address, AuthenticatingSimpleXMLRPCRequestHandler ) server.server_forever() Cheers, Brian From jdhunter at nitace.bsd.uchicago.edu Fri Jul 19 11:22:56 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 19 Jul 2002 10:22:56 -0500 Subject: Anybody using 4suite for xslt processing? References: Message-ID: >>>>> "Marko" == Marko Faldix writes: Marko> Hi, sometimes I think I am first man on earth want to Marko> process xslt. Hmm ..., the following works for me from xml.xslt.Processor import Processor p = Processor() p.appendStylesheetUri('tmp/temp.xsl') I use a different import statement than you did; if you use the import above, do you still get the exception? What happens when you do dir(Processor)? Does appendStylesheetUri show up in the listing? What version of 4suite are you using? John Hunter From aleax at aleax.it Tue Jul 9 11:15:20 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 15:15:20 GMT Subject: sorting many arrays from one... References: Message-ID: Shagshag13 wrote: > > "Alex Martelli" > >> I'm not sure how that would save you any storage at all. Since the >> strings DO need to be stored somewhere anyway, what's saved by using >> their id's rather than just references to them, as Python usually does? > > i should have write that i use the same string many times in many files, > so i only use its id which is always shorter than my strings and save > storage. And i was wondering if there was a better/efficient way to handle > id-string mapping. If you never need to flush the memory used for such strings, Python's built-in intern function is an excellent solution. Unfortunately, interned strings DO become "immortal". If the ability to flush the structure periodically (in order to recover all storage) is indeed a must, then you can do better than the code you posted only in performance-marginal aspects (e.g., avoiding the horrid idea of type-checking -- but that won't speed things up) except by using string references rather than arbitrary integers, which would save some more meemory AND time. A reference to a string takes no more memory than a reference to an int, after all. As long as the string object proper is only stored once, having N more references to it from various modules is no more costly (normally LESS costly in all aspects) than having N references to an int instead. If you're comfortable reasoning in C terms...: anything you see in Python as a variable, an item in a list, etc, is a PyObject* -- a pointer to a PyObject. The pointer itself takes 4 bytes on a typical 32-bit machine, whatever kind of object is involved. Python does not make IMPLICIT copies -- assignment, argument passing, etc, all store and/or sling around REFERENCES, i.e., PyObject* things. An object stays alive as long as its reference count is > 0 (except when it's in a garbage-loop that may be collected by GC, but that's another issue that doesn't really matter here). So, say you have several strings all with the same value, e.g. 'disestablishmentarianism', obtained at various times, from various sources, in various modules. If you do nothing special you'll take up N*(24+x) bytes for the objects themselves (x is a small extra overhead for each string object, say another 8 I think) plus N*4 bytes for the references, say N(24+8+4) = N*36 or a bit more. So, it's sure worthwhile to cut this down to N*4+K for some fixed K -- ensuring the value 'disestablishmentarianism' is stored only once and all references to that value refer to the very same Python object. But there's no reason to bring _integers_ into the picture...! class StringStore: def __init__(self): self.store = {} def add(self, s): return self.store.setdefault(s,s) def flush(self): self.store.clear() There -- instantiate one of these, once, and just be sure to pass all strings that need to be stored through the StringStore method of that one instance. This will actually work just as well for tuples of immutable objects, unicode strings, complex numbers, and so on, but this of those as just nice side effects...:-). Do you see why this works, now...? after ss=StringStore(), any ss.add(somestring) returns EITHER the string argument, OR another string equal to that one if one was already in ss.store -- so, somestring = ss.add(somestring) either leaves variable somestring alone, or rebinds it to refer to an identical value that's already stored elsewhere. No need to think of integers or anything like that, right...? The dict's method setdefault is just a shortcut to make this tiny and greased-lightning fast, of course. It has much the same semantics as if s in self.store: return self.store[s] self.store[s] = s return s but is much faster and slicker:-). Alex From whisper at oz.net Sun Jul 7 21:26:30 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 7 Jul 2002 18:26:30 -0700 Subject: Linux clock-setting script In-Reply-To: <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: "Set Your Clock Via Internet" http://www.boulder.nist.gov/timefreq/service/its.htm This particular page focuses on Windows, but the ftp site has sources in C. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Paul Rubin > Sent: Sunday, July 07, 2002 17:44 > To: python-list at python.org > Subject: Re: Linux clock-setting script > > > William Park writes: > > > http://www.nightsong.com/phr/python/setclock.py > > > > > > I find it pretty useful for adjusting my computer clock every > > > now and then, without the hassle of setting up a real NTP system. > > > > Thanks for the pointer, Paul. Exactly what I needed. Do you > know any pure > > shell script that does the same thing? I don't have Python installed on > > every machine. > > I don't know about shell but it should be simple to write the same > thing in Perl or even in C. > -- > http://mail.python.org/mailman/listinfo/python-list From amuys at shortech.com.au Mon Jul 8 05:23:41 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 8 Jul 2002 02:23:41 -0700 Subject: Help with an algorithm wanted References: Message-ID: <7934d084.0207080123.6cffd86e@posting.google.com> "Russell E. Owen" wrote in message news:... > The problem is that the graph has 10 nodes. Rather than hand code 10 > different objects, I'm trying to create a factory that will generate the > required object based on which node (data representation) is a given > from which the others are derived. > Indeed a factory sounds like the way to go. Personally I would stick with the adjacency graph, and generate the the required compound functions at runtime per-request. Python's good at that sort of thing, in fact here's one I prepared earlier.... (uses shortest path impl from recipies I posted before). #!/usr/bin/python import shortest_path as spath # Shortest path requires addition, and I require annotating with a callable. # Obvious solution, create an addable callable ;) class Edge(object): def __init__(self, func): self._func = func def __add__(self, other): return 1 + other def __radd__(self, other): return 1 + other def __call__(self, *args): return self._func(*args) class ConverterFactory(object): def __init__(self, graph): self._graph = graph def getConverter(self, fromNode, toNode=None): def closure(value, toNode=toNode): def convert(value, func): return func(value) return reduce(convert, self.shortestPath(fromNode, toNode), value) return closure def shortestPath(self, fromNode, toNode): if (toNode == None): raise RuntimeException, "Final Representation required" vpath = spath.shortestPath(self._graph, fromNode, toNode) epath = [] for i in range(len(vpath) - 1): epath.append(G[vpath[i]][vpath[i+1]]) return epath if (__name__=='__main__'): AB = Edge(lambda x: x + ' AB') AE = Edge(lambda x: x + ' AE') BA = Edge(lambda x: x + ' BA') CB = Edge(lambda x: x + ' CB') CD = Edge(lambda x: x + ' CD') CE = Edge(lambda x: x + ' CE') DE = Edge(lambda x: x + ' DE') EA = Edge(lambda x: x + ' EA') EC = Edge(lambda x: x + ' EC') ED = Edge(lambda x: x + ' ED') G = { 'A' : { 'B' : AB, 'E' : AE }, 'B' : { 'A' : BA }, 'C' : { 'B' : CB, 'D' : CD, 'E' : CE }, 'D' : { 'E' : DE }, 'E' : { 'A' : EA, 'C' : EC, 'D' : ED }, } factory = ConverterFactory(G) BDconverter = factory.getConverter('B', 'D') Bconverter = factory.getConverter('B') print BDconverter("BString to Dform:") print BDconverter("Another BString to Dform:") print Bconverter("B->D:", 'D') print Bconverter("B->C:", 'C') print Bconverter("B->B:", 'B') print factory.getConverter('D', 'C')("D->C:") print factory.getConverter('C', 'D')("C->D:") And of course when run generates: $ ./converter.py BString to Dform: BA AE ED Another BString to Dform: BA AE ED B->D: BA AE ED B->C: BA AE EC B->B: D->C: DE EC C->D: CD Now the key to understanding the above code is getConverter, so here it is again. def getConverter(self, fromNode, toNode=None): def closure(value, toNode=toNode): def convert(value, func): return func(value) return reduce(convert, self.shortestPath(fromNode, toNode), value) return closure This method creates/returns a closure that will perform the requested conversion. A closure is a function that remembers what variables it was able to see when it was created, so can use them when it gets executed. In this case the converter-closure remembers which object created it (via self), where it's coming from (via fromNode), and where it's going to (via toNode). This means that when you call it, to perform a conversion, it knows which object can calculate the required path for it, and which path it's looking for. Now as the path is a list of function-like objects that represent conversions; and reduce is a function that runs through a list accumulating it's contents (according to a provided 'accumulation function'); And ultimately what we would really like to accumulate the conversions; The converted value we're looking for is really just the accumulated conversions on an initial value.... ...how convenient :). reduce(convert, self.shortestPath(fromNode, toNode), value) 'convert' is just a helper function that knows how to apply a conversion to a value and returns the result. I recommend if you plan to use this that you add some convenience methods to ConverterFactory to allow you to manipulate the graph. For flexibility's sake the code currently recalculates the shortest-path each time you do a conversion, so if you are doing alot of conversions you may find profiling identifies this as a problem (remember... it isn't a problem until profiling says it is!). In this case you may want to move the path calculation outside the closure so you only do it once per getConverter() call. Andrae Muys P.S. I think this might demonstrate one occasion where lambda is superior to the equivelent nested-function. The test-code would have been far less readable if each of the ten 'conversion functions' had been defined independently prior to use. I will note however that while 'convert' could have been defined lambda v,f:f(v); I personally find the nested-function much easier to read. From news at lindbergs.org Sun Jul 7 01:04:11 2002 From: news at lindbergs.org (VanL) Date: Sat, 06 Jul 2002 23:04:11 -0600 Subject: Given PID, make sure a process is running on Unix? References: <3D2761CD.1090503@lindbergs.org> Message-ID: <3D27CBCB.4070405@lindbergs.org> Thank you! This is just what I was looking for. Thanks, VanL Fran?ois Pinard wrote: >[VanL] > > > >>I am trying to get write a python script that on Unix reads a PID from >>a file and, if that process is still running, exits. If the process is >>not running, the process would be started. [...] Any help? >> >> > >You could work along the lines of: > > try: > os.kill(PID, 0) > except OSError: > print PID, 'is not running' > else: > print PID, 'is running' > >Killing a process with signal 0 never kills it. :-) > > > From fperez528 at yahoo.com Mon Jul 8 12:57:10 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 08 Jul 2002 10:57:10 -0600 Subject: Numarray vs Numpy References: Message-ID: Shagshag13 wrote: > Which one is the best ? > > thanks > > s13. numarray is a rewrite of numpy. As such it will address some flaws of numpy's design which have been understood over the last few years of its extensive use in science. But beware that in order to do that, numarray's designers will be forced into breaking compatibility with numpy. So while _most_ numpy code will work with numarray, some critical things will not. Also consider that at this time, numarray is still in early development and not considered production ready by any means. So if you need it for production code, I'd suggest going with numpy and living with some of its limitations. But numarray, once it comes out stable, will be a replacement for numpy with some very nice improvements (fine-grained control of hardware floating point exceptions comes to mind as a major blessing). cheers, f. From tim.one at comcast.net Mon Jul 29 17:50:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 29 Jul 2002 17:50:10 -0400 Subject: Python design failures (was Re: Let's Talk About Lambda Func In-Reply-To: Message-ID: [Neil Schemenauer] > Guido's not big on this kind of "hit and run" cleanup. He prefers it if > someone looks at the entire module while modernizing it. Keep in mind > though, I'm an amateur when it coming to channelling the BDFL and he > might tell you differently himself. [Sean 'Shaleh' Perry] > That is a reasonable attitude. > > Comments from the direct python hackers? Would more work on the lib be > welcomed? Do we want the standard library to be a good example > of python best practices? (sorry i know that sounds like a loaded > question). Best practice is, as Neil said, to *think* about a module, and hard, when "cleaning it up". Widespread mechanical edits aren't welcome, and especially since the last such effort (massive conversion to string methods) introduced several bugs in the process. Better to find modules to love long-term and keep them deeply beautiful, than to splash paint on boils at random just to cover up the oozing pus . From tjreedy at udel.edu Thu Jul 25 10:22:30 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Jul 2002 14:22:30 GMT Subject: DLL files References: Message-ID: "Uwe Mayer" wrote in message news:MPG.17aa19eb2ca3d536989688 at news.rz.uni-karlsruhe.de... > is it possible to write Windows DLL files in python? No. .dll must be machine code and have special structure. (99% certain on this) TJR From zwiskle at vol.at Sat Jul 27 19:55:18 2002 From: zwiskle at vol.at (klemens zwischenbrugger) Date: 28 Jul 2002 01:55:18 +0200 Subject: w32: python ddeserver / excel Message-ID: <1027814118.960.10.camel@julia> Hi, i have to wite a python program, wich delivers results of a serival-interface read via dde. ( well, thats the way it is. I DON'T want to change DDE (DDE is evil, I know) to somewhat else, becaus that will end in work * 10^X ) I've used excel as dde-client. anybody get them running ? I can start a DDEserver oin Python, and I can start a ddeClient in Excel. But seems not to fit; or any idea how to debug this stuff ? running currently win2k, activestate python 2.2; using lib 'DDE' for server and 'excel 97' for client. (in the end, a VB program will be client; but for moment, excel is evil enought.) takk. .klemens -- klemens zwischenbrugger mail: zwiskle at vol.at279009 "today" is one of my favorite days. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 240 bytes Desc: This is a digitally signed message part URL: From johann.hoechtl at myrealbox.com Sun Jul 14 08:21:30 2002 From: johann.hoechtl at myrealbox.com (=?ISO-8859-1?Q?Johann_H=F6chtl?=) Date: Sun, 14 Jul 2002 14:21:30 +0200 Subject: Python and Parrot Message-ID: <3D316CCA.90605@myrealbox.com> Hello ! Can someone quote a bit on Python --> Parrot (the upcoming VM Perl 6 is about to use. Designed for weakly typed programing languages. See http://www.parrotcode.org ) Recent progress has been very fast and according to http://use.perl.org/articles/02/07/03/2241212.shtml the progress of parrots implementation is even likely to speed up. Recent speed measurements of the VM yielded very good results and the ruby folks already seem to have the Parrot VM as a target in mind. http://www.rubygarden.org/article.php?sid=234 Has the situation for Python changed since http://groups.google.com/groups?q=parrot+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&scoring=d&selm=slrna8us88.ol4.akuchlin%40ute.mems-exchange.org&rnum=9 got posted? Regards, Johann From zbortolo at vt.edu Fri Jul 19 12:52:59 2002 From: zbortolo at vt.edu (Zachary Bortolot) Date: 19 Jul 2002 09:52:59 -0700 Subject: Renting CPU time for a Python script Message-ID: <25c15ddd.0207190852.2aecc26c@posting.google.com> Hello Everyone, I am a graduate student conducting research on using computer vision techniques to process digital air photos. As part of my research I am using a genetic optimization routine that I wrote in Python to find values for several key parameters. Unfortunately the genetic algorithm is quite CPU intensive, and each run requires anywhere from five to twelve days to complete on a 450MHz Pentium II. This is problematic since I have to run the program in a computing lab that is frequently used for teaching, which means that I am often unable to complete my runs. I would like to know if anyone has any suggestions on where I might go to rent CPU time that is Python and PIL friendly (the university I am at does have an AIX-based mainframe, but Python is not installed and users are only given 600k of disk space). Speed is not a major issue for me and the program does not use a lot of memory or disk space. However, stability is a definite must. Thanks in advance for any advice or suggestions! Zack Bortolot From jonathan at onegoodidea.com Mon Jul 22 17:49:38 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 22 Jul 2002 22:49:38 +0100 Subject: Anybody using 4suite for xslt processing? References: Message-ID: On 22/7/2002 15:31, in article ahh4su$sl3sj$1 at ID-108329.news.dfncis.de, "Marko Faldix" wrote: > My installation of 4suite dropped the respective directories to > > Python22\Lib\site-packages\Ft > > so I have to use Ft.Xml.Xslt - without Ft 4suites classes can't be found. [...] > What do you have in your directories, which path contains a class with > appendstylesheeturi? I think the 'xml.xslt' package referred to is from the PyXML tools. I had thought that the XSLT implementation in PyXML was incomplete and/or broken but looking at the new O'Reilly "Python & XML" book, it uses PyXML in the XSLT examples, so I guess it's OK. Jonathan From hikage at parkour-belgique.com Tue Jul 30 08:32:42 2002 From: hikage at parkour-belgique.com (Hikage) Date: Tue, 30 Jul 2002 14:32:42 +0200 Subject: Python & X-Chat References: <3d4610d1$0$289$ba620e4c@news.skynet.be> Message-ID: <3d46883c$0$201$ba620e4c@news.skynet.be> Thanks you ;-) "Gerhard H?ring" a ?crit dans le message news: mailman.1028003504.10154.python-list at python.org... > * Hikage [2002-07-30 06:03 +0200]: > > Hello, I seach people who had make script for x-char or had doc about this.. > > > > > > I've found nothing ... HELP HELP ;) > > > > Thanks to the people who can help me :) > > I guess you should check out the latest XChat, quoting from > http://www.xchat.org: > > | 09-JUL-2002 > | Released development version 1.9.2. This version includes a new Python > | interface, written by Gustavo Niemeyer. It has been designed and > | implemented really well! It sure puts the Perl interface to shame. > > Well, it _can_ only have improved, *cough* ;-) > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) > From henk_derudder at hotmail.com Thu Jul 25 10:12:54 2002 From: henk_derudder at hotmail.com (henk_derudder at hotmail.com) Date: Thu, 25 Jul 2002 14:12:54 GMT Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> <3D4005CD.4060404@thomas-guettler.de> Message-ID: <3d400710.533379375@news.skynet.be> On Thu, 25 Jul 2002 16:06:05 +0200, Thomas Guettler wrote: >Alex Martelli wrote: > >> Thomas Guettler wrote: >> ... >> >>>>Many Python functions expect to get arguments of specific types >>>>(or polymorphic to such types, i.e., supplying all necessary >>>>methods and operations with equal signatures). >>>> >>>>Having them accept arguments of wrong types, with silent coercion, >>>>would hurt all careful developers, by hiding bugs. >>>> >>>I agree, but than the exception should have a better message: >>> >> >> Should it? Maybe I should have written than types supplying all >> necessary methods and operations with equal signatures are OK >> too. > > >Dont't take this to serious, I just wanted to know >what other people think Alex does not take it too serious. He is trying to explain how Python works and should work at its fundaments. The more one understands this the better one can program in Python. Just take his explanation for very granted :-) > > thomas > From fredrik at pythonware.com Mon Jul 15 03:16:23 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Jul 2002 07:16:23 GMT Subject: maxlenght in Entry() / Tkinter References: Message-ID: Joaquin Romero wrote: > I can setting a maxlength (max numebers of characters) in a Entry() of > Tkinter? How? matthew showed you how to use an event binding to reject keyboard presses when the value is already long enough. another approach is illustrated by the ValidatingEntry class available from: http://effbot.org/zone/tkinter-entry-validate.htm to make a version that limits the length, just check the length in the validate method; e.g. class MaxLengthEntry(ValidatingEntry): def __init__(self, master, value, maxlength, **kw): self.maxlength = maxlength apply(ValidatingEntry.__init__, (self, master), kw) def validate(self, value): if len(value) <= self.maxlength: return value return None # new value too long and here's how to use the class: root = Tk() entry = MaxLengthEntry(root, "", 20) entry.pack() mainloop() From aleax at aleax.it Sun Jul 14 12:40:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 14 Jul 2002 16:40:09 GMT Subject: function parameter: question about scope References: Message-ID: Uwe Mayer wrote: > hi, > > I've got a object method which works similar to the __deepcopy__() > function of the copy/deepcopy protocol. this function takes an optional > argument "memo={}": > > def getElements(self, types, memo={}): ... > Why does 'memo' keep exising? What "keeps existing" is the DEFAULT value of memo -- it keeps existing because it's stored among the function's attributes. That's how default values of arguments behave: constructed once, when you execute statement def, and thereafter remembered as long as the function object survives. This is generally OK when the default value is immutable, and almost never what you want when it's mutable. Solution: don't use mutable objects as default values for arguments. E.g., change your function's start into: def getElements(self, types, memo=None): if memo is None: memo = {} # proceed as before This is the most idiomatic Python approach. Alex From polux2001 at wanadoo.fr Tue Jul 30 21:11:15 2002 From: polux2001 at wanadoo.fr (polux) Date: Wed, 31 Jul 2002 03:11:15 +0200 Subject: newbie : unicode Message-ID: <3D473933.8040306@wanadoo.fr> Hi I'm using IDLE for windows and when i'm using a char like ? or ? (i'm french :)), i get the error message : UnicodeError: ASCII encoding error: ordinal not in range(128) but if i've understood, Python works with unicode, so there should be no problem ! please help From comcol at ukmail.com Sun Jul 7 16:04:14 2002 From: comcol at ukmail.com (Comcol) Date: 7 Jul 2002 13:04:14 -0700 Subject: sqlite-python-0.2.0.win32-py2.2.exe fails References: <1b8c5fe1.0207060550.72952217@posting.google.com> <1b8c5fe1.0207070212.679882af@posting.google.com> Message-ID: <1b8c5fe1.0207071204.4c57f51b@posting.google.com> "Chris Gonnerman" wrote in message news:... > Try unzipping the installation file and doing the install by hand. > Standard Python Win32 installation packages made by distutils are just > an exe stub with a zipfile appended, and all zip packages I've ever > used can read that format easily. > Usually from Microsoft: > > http://www.microsoft.com/windows95/downloads/ > Many thanks. From phil at river-bank.demon.co.uk Sat Jul 20 05:44:55 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sat, 20 Jul 2002 10:44:55 +0100 Subject: Do GUIs for DBs exist? References: Message-ID: <3D393117.7060407@river-bank.demon.co.uk> Mark Carter wrote: > I was using PySqlite (a module that interfaces Python with the SQLite > database ) the other day, and I was thinking: hey, wouldn't > it be great if it had a GUI like MSAccess. > > Maybe such tools already exist, maybe Tkinter might be useful > (although > I've never used it before). Maybe even an interface written in > CGI/html > would be best. > > Comments? PyQt provides you with what you want. It includes SQL classes that support ODBC3, MySQL, PostgreSQL, Oracle, and data aware GUI widgets like QDataTable, QDataBrowser and QDataView. You can use Qt Designer to build your forms and use the pyuic utility to generate the Python code that implements those forms. PyQt includes an example application that allows you to connect to a database, view it's structure and contents and submit arbitrary queries - all in about 180 lines of handwritten Python. PyQt is available from http://www.riverbankcomputing.co.uk/pyqt/. Phil From andrewm at object-craft.com.au Tue Jul 30 00:35:20 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Tue, 30 Jul 2002 14:35:20 +1000 Subject: order of test In-Reply-To: Your message of "Mon, 29 Jul 2002 11:00:50 GMT." Message-ID: <20020730043520.A42C93900B@coffee.object-craft.com.au> >> It's called lazy evaluation, > >No it's not! Lazy evaluation is more like Haskell... Of course, you are right. That's what I get for rushing. "Lazy evaluation" implies an expression is not evaluated until it is needed to evaluate another expression. As several people have pointed out, I meant "short circuit evaluation". >> and python shares this trait with C. > >This much is true. Whew. ;-) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From dyoo at hkn.eecs.berkeley.edu Mon Jul 15 03:30:56 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 15 Jul 2002 07:30:56 +0000 (UTC) Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: Fredrik Lundh wrote: : Daniel Yoo wrote: :> Fredrik Lundh wrote: : no, I didn't. : can you please spend the two seconds it'll take to : get the attributions right before you post. Hi Fredrik, Yikes! My apologies about the misattribution; I had only paid attention to editing the bottom of the original message, but had forgotten to correct the top half. I'll be more careful in the future. From tim at vegeta.ath.cx Sun Jul 28 13:50:46 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: 28 Jul 2002 10:50:46 -0700 Subject: Programming/Life ratio (was Re: __call__ bad style?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: Aahz graced us by uttering: > Michael Hudson wrote: > > Then I'm ahead of you by ... erm ... 13 years. Wow, I've been > > programming (admittedly only as a hobbyist) for nearly a third of my > > life. That's scary somehow. > > Heh. For me, it's closer to 3/4 of my life, and I've been doing it > for pay more than half my life. Then again, I'm still under 40, and Let's see. Starting with the TRS-80 CoCo 1, that brings us to just over 4/5 of my life actively programming. In fact, for those who've read Linus' book "Just for Fun," his tales of hacking his grandfather's VIC-20 was eerily similar to my childhood... the major differences being the make of computer and the continent. Ah, the nostalgia! =) Thx for the trip! > I'm one of the few people in that category who's used JCL. (Not the > only one, from the last time we had this thread.) > > On the gripping hand, I never really thought of myself as a programmer > until I learned Python. Never did JCL, and never considered myself a programmer till I got I hands on one of the earliest releases of Borland C++. Python came several years later, and I didn't pick it up until the late 1990's, so you all have a good head start of me in that vein. =) Tim Hammerquist -- $ echo espresso > /dev/coffee From jdhunter at nitace.bsd.uchicago.edu Mon Jul 15 16:17:22 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Jul 2002 15:17:22 -0500 Subject: Common list in distinct objects' References: <3d331fa9.361390031@news.byu.edu> <3d332491.362646438@news.byu.edu> Message-ID: >>>>> "Jake" == Jake R writes: Jake> Now that I think about it some more I seem to remember Jake> reading somewhere in the tutorial that class definition is Jake> only processed once and being so means that the default list Jake> (myList=[]) in my __init__ is only created once and thus any Jake> objects created all point to the same list unless I create a Jake> new list (ie pass one in or have the __init__ function do it Jake> when its called) Jake> Does that sound right? Still....I don't think thats what Jake> way it ought to behave. In python, all arguments are passed by reference, which means that the when you pass a list to a function, the copy of the list inside and outside the list are the same. Consider this code: def somefunc(x): x.append('In func') y = [] y.append('Before func') somefunc(y) y.append('After func') print y The contents of y are ['Before func', 'In func', 'After func'] because it is the same list. Now in your case, when a and b are both initialized use the default value of mylist=[], they both refer to the same list '[]' and so appending to one is the same as appending to the other. Likewise, in the following code, both a and b refer to the same list # Compare the following two cases # a and b have the same lists x = [s] a = TestList(x) b = TestList(x) But in this case they do not a = TestList([s]) b = TestList([s]) Note the difference between equality (with the '==' operator) and identity (with the 'is' operator). In python, 2 lists are equal if all the elements compare equal, are are identical if they refer to the same list >>> s = 'Hi' >>> x = [s] >>> y = [s] >>> x==y 1 >>> x is y 0 >>> z = x >>> x==z 1 >>> x is z 1 But note that >>> [] is [] 0 So two copies of [] are not identical (though they are equal). When you create a default arg to a function, python only makes one instance of it, so all functions share the same default object. Thus in the case of your init function, two instances a and b do not refer to two copies of the empty list, but to the same copy of the empty list. See http://www.python.org/cgi-bin/faqw.py?req=all#6.25 Cheers, John Hunter From b.maryniuk at forbis.lt Wed Jul 10 05:59:28 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 10 Jul 2002 11:59:28 +0200 Subject: Why self? In-Reply-To: <3D2B5C2E.6050001@onsitetech.com> References: <3D2B5C2E.6050001@onsitetech.com> Message-ID: <200207101159.28788.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 23:58, Robb Shecter wrote: > 1. So you're uhh... agreeing but not? Troll. > 2. I'm down w/ polymorphism, man! I'm all over over it. There's a big > difference between type and class, for starters, and 'type' as in > 'implements an interface' is what I'm talking about. Please take a look over the Python documentation for BEGINNERS. Is Your current language Object Pascal? > No, you don't know me, but I know OO. :-) But 'OO' != (00 || 'WC') :-P -- Sincerely yours, Bogdan M. Maryniuck linux: because a PC is a terrible thing to waste (ksh at cis.ufl.edu put this on Tshirts in '93) From cliechti at gmx.net Mon Jul 22 17:24:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 22 Jul 2002 23:24:09 +0200 Subject: newbie problems with Tkinter References: Message-ID: Peter Wichert wrote in news:nashha.hp1.ln at localhost.my.domain: > I installed python 2.2.1 on my freebsd4.5 and tried some examples from > my new python-book. But I couldn't get it running. > > 1) Using module "Tkinter" is the first problem. Doing it twice seems > to be better: no that's an illusion. when the import fails, an empty or partly initilized module object exists. importing modules more than once does nothing, as its already loaded (even if its empty, due to errors). reload(modulename) does realy load again. > ImportError: No module named _tkinter you have an installation problem. the error does mean that the pyd/so file _tkinter.so is missing. maybe the tkinter stuff is in a separate install/package. chris -- Chris From pecora at anvil.nrl.navy.mil Tue Jul 2 13:54:48 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 02 Jul 2002 13:54:48 -0400 Subject: Memory leak in Mac Python IDE ? Message-ID: <020720021354486814%pecora@anvil.nrl.navy.mil> I run the following code in a file under the IDE (under System 9.1 on a G4 Mac with 40 MB allocated to Python 2.2 IDE): #--Test code from Numeric import * tab1=zeros((200000,4)) print shape(tab1) #--End Test code Check the memory under 'About this Computer' in the Finder. Then change tab1 to tab2 and run again (I hit cmd-R several times quickly and that seems to worsen the problem - don't know why), then check memory and see that more is used up. Continue this process to tab3, tab4, etc. and eventually I get an exception -- ran out of memory, cannot allocate more. Sure enough, under 'About this Computer' in the Finder, the memory is used up. Looks like a memory leak to me, but maybe the IDE is set up to keep variables around, hence tab1, tab2, etc. are never garbage collected after the module is run with a new varible name, e.g. tab2 in place of tab1. Anyone know? [Also posted to PythonMacSIG -- Sorry if you've seen this before] -- -- Lou Pecora - My views are my own. From cliechti at gmx.net Sun Jul 7 14:16:34 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Jul 2002 20:16:34 +0200 Subject: sys.platform on UNIX References: <85bs9jfm4n.fsf@hilbert.ingoblank.com> Message-ID: User & wrote in news:85bs9jfm4n.fsf at hilbert.ingoblank.com: > I need a boolean function isUnix(), which returns true, > if executed on a UNIX OS. > > I think it's best, to check the 'sys.platform' string. not in every case.... > However, there are lots of possibilities: > 'linux*','freebsd*','sunos*','solaris*','irix*','osx*','hpux' ... etc. i think thats quite good so, as all that unix like systems are different. however if you're interested in POSIX compatibility os.name is better: >>> import os >>> os.name 'nt' it will be 'posix' on any os that calls itself a unix clone... chris -- Chris From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 18:01:20 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 15:01:20 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: <7x3cu6f8sv.fsf@ruckus.brouhaha.com> Alex Martelli writes: > It's not an issue of syntax sugar as superficial as what keyword to > use. A REAL lambda, by any other name -- the ability to package up > ANY chunk of code, not just an expression -- might add power enough > to justify its existence. Today's lambda's just deadweight. I agree that the current incarnation of lambda is deficient. I think it should be strengthened so you can lambdafy arbitrary code, not eliminated. The current version is better than nothing, though. I don't see why the anti-lambda contingent doesn't want to also get rid of anonymous scalar expressions. I mean, a = b + (c * d) the horror! Why not insist on naming the subexpressions, e.g. temp = c * d a = b + temp From whisper at oz.net Mon Jul 29 15:43:23 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 29 Jul 2002 12:43:23 -0700 Subject: decoding XML-ified special chars such as " In-Reply-To: <0C7CA8D8DF75494EB09AB6016990107F016F6164@NOXMAIL.noetixad.com> Message-ID: > Is there a module to take strings such as ", & and turn them > into the characters they normally represent (', &)? > > Gabe Newcomb > Software Test Automation Engineer > 425.372.2732 > Noetix Corporation > www.noetix.com > Well, those are called character entities and those fall under the pervue of HTML or XML. Sorry I can't be more specific, but you should be able to find something to deal with those in one of the distributed with python xml libs or PyXML. It's also trivially easy to just do this with a dict and the re module. Dave LeBlanc From smurf at noris.de Fri Jul 19 02:56:01 2002 From: smurf at noris.de (Matthias Urlichs) Date: Fri, 19 Jul 2002 08:56:01 +0200 Subject: php function "addslashes" / "removeslashes" in python References: Message-ID: <1ffid4y.1h1l6w1eipirkN%smurf@noris.de> Lowel Stern wrote: > Does anyone know if this exists already? > For SQL? Use the database interface properly. http://www.python.org/topics/database/DatabaseAPI-2.0.html If you really need to construct a SQL string manually, use the quote method supplied by the database adapter you're using. -- Matthias Urlichs -- No cute .sig today... From wweexxsseessssaa at telusplanet.net Thu Jul 18 18:58:20 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Thu, 18 Jul 2002 22:58:20 GMT Subject: Tkinter vs. wxPython References: <0C7CA8D8DF75494EB09AB6016990107F016F60C6@NOXMAIL.noetixad.com> Message-ID: >On Thu, 2002-07-18 at 14:19, Gabe Newcomb wrote: >> Ack! >> I've been trying to get into wxPython, but I'm finding the lack >> of documentation difficult. There's some, and I'm very grateful for >> everybody who's contributed it, but I'm somebody who really likes having >> a decent reference and more examples.... PythonCard might be worth looking at. It uses wxWindows and wraps many (not yet all) of the wxWindows components. (You can handle the others yourself, I think). -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From mgerrans at mindspring.com Mon Jul 1 00:41:31 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sun, 30 Jun 2002 21:41:31 -0700 Subject: problem with spawnle References: Message-ID: If you are not averse to using the Win32 extensions on the Windows platform, then win32api.WinExec() or win32api.ShellExecute() will do the job quite nicely. From tjreedy at udel.edu Sat Jul 20 12:07:57 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Jul 2002 16:07:57 GMT Subject: Renting CPU time for a Python script References: <25c15ddd.0207190852.2aecc26c@posting.google.com> <698f09f8.0207192212.76272194@posting.google.com> Message-ID: "Jeremy Fincher" wrote in message news:698f09f8.0207192212.76272194 at posting.google.com... > Fernando P?rez wrote in message news:... > > 1- code in automatic checkpointing and self-restarting abilities. It's fairly > > easy to do, and saves a lot of headaches. > > Do you know of any examples of this in available code, or could you > outline how you would implement something like that? I have a project > right now that such a capability would come quite useful in, but > rather than hazard my own implementation right off, I'd like to try > and leverage some other efforts. Details are project specific, but here is outline. Assume outer loop of long-running program takes 5 minutes. At bottom of loop, write out enough data to restart program. If proccessing multigigabyte file, this might be a simple as writing f.tell() and using f.seek() on restart. For more typical program states, leverage with (c)pickle to write and read. If outer loop takes, say 3 seconds, one might add counter to save after each 100 loops. If outer loop takes, say, a day, look for inner loop save point (but restarting will be harder). Hope this helps. Terry J. Reedy From zopestoller at thomas-guettler.de Fri Jul 5 08:17:11 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 05 Jul 2002 14:17:11 +0200 Subject: GUI-Builder Message-ID: <3D258E47.10507@thomas-guettler.de> Hi! There are several applications for building GUIs with a GUI: Boa constructor and PythonCard are two of them. Can someone compare them (pro/contra)? I couldn't find a page which does this thomas From mh at esh-online.de Mon Jul 15 15:16:49 2002 From: mh at esh-online.de (Michael Hoffmann) Date: Mon, 15 Jul 2002 21:16:49 +0200 Subject: could not import mod_python.apache References: Message-ID: Hi Gerhard, but I've used the original RPMs from SuSE ... Michael "Gerhard H?ring" schrieb im Newsbeitrag news:mailman.1026754722.4497.python-list at python.org... > * Michael Hoffmann [2002-07-15 16:39 +0200]: > > Hi, > > I've the folowing Error when I try to run my pythonscript: > > > > make_obcallback(): could not import mod_python.apache. > > In my experience, this is the single most often experienced problem with > mod_python: For some reason your "make install" step didn't put the > mod_python support modules into the right places. > > You could try to fix this manually: the directory lib/python/mod_python > in the mod_python source distribution should go into the site-packages > directory of the Python you compiled it against. > > I'd also recommend to ask on the mod_python mailinglist in the future, > as that's where the people who're using it hang out. > > Gerhard > -- > This sig powered by Python! > Au?entemperatur in M?nchen: 21.4 ?C Wind: 4.7 m/s > > From mdehoon at ims.u-tokyo.ac.jp Sat Jul 27 05:12:07 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Sat, 27 Jul 2002 18:12:07 +0900 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> Message-ID: <3D4263E7.3000107@ims.u-tokyo.ac.jp> Thanks for your reply. I am having some difficulties setting the CC environment variable, probably due to some peculiarities of our Unix system. But if I solve that and set CC=gcc, would distutils know about it? I would think that distutils would choose the compiler options for the regular cc compiler, but substitute gcc for CC when the actual compilation starts, thus ending up with the wrong compiler options. Or am I missing something here? Does distutils check for the CC environment variable? Thanks again, --Michiel. Martin v. L?wis wrote: > Michiel Jan Laurens de Hoon writes: > > >>It is possible to specify which compiler distutils should use? >> > > You need to set the CC environment variable. > > HTH, > Martin > From pecora at anvil.nrl.navy.mil Fri Jul 19 15:07:12 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Fri, 19 Jul 2002 15:07:12 -0400 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <190720021018041866%pecora@anvil.nrl.navy.mil> Message-ID: <190720021507121883%pecora@anvil.nrl.navy.mil> In article , Terry Reedy wrote: > Certainly, copying a global or builtin method to a local for > repeated use is a standard Python speedup trick. I learn something every day. We should have a collection of speedup tricks listed somewhere. Thanks. -- Lou Pecora - My views are my own. From aahz at pythoncraft.com Fri Jul 19 13:54:55 2002 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2002 13:54:55 -0400 Subject: CANCEL: OSCON Community dinner Weds 7/24 6pm References: Message-ID: Given the lack of response, I'm hereby canceling any official Python community dinner. I hope to see many of you at the conference, though. I'm including the original message below in case someone else wants to run with the ball. In article , Aahz wrote: >[posted to c.l.py with cc to c.l.py.announce and python-dev] > >I'm proposing a Python community dinner at OSCON next week, for Weds >7/24 at 6pm. Is there anyone familiar with the San Diego area who wants >to suggest a location near the Sheraton? If I don't get any >recommendations, we'll probably just have the dinner at the Sheraton. > >If you're interested, please send me an e-mail so I have some idea of >the number of people. Also, please include a way of getting in touch >with you at OSCON in case plans change (phone numbers accepted, but >e-mail addresses preferred). > >(There's a meeting for PSF members at 8pm, so some of us will likely >have to skip out early.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jdavis at empires.org Fri Jul 26 20:21:29 2002 From: jdavis at empires.org (Jeff Davis) Date: Sat, 27 Jul 2002 00:21:29 GMT Subject: performance problem in python 2.2 References: <7xd6tayqt6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Jeff Davis writes: >> 'p' was an unsigned long long int. I slightly modified the algorithm in >> C because it doesn't have (native) support for > 64-bit ints. Since the >> number of possibilities is 2**64 that value will be slightly bigger than >> a 64 bit int could hold. So, I just basically multiplied twice by 2^32 >> and divided twice by 2^32. In other words, I basically treated 'p' as >> sqrt(p)*sqrt(p) and commuted the multiplication so that I would arrive >> at the same result (and the testing seemed to show the same results as >> my other algorithm). I have attached my c code below in case you'd like >> to know exactly what's going on. > > It's amazing that you ended up with an accurate answer doing that. > > You should do this kind of thing completely in floating point: > > double p; > p = pow(2.0, 64.0); /* 2**64 */ > etc. Strange that you mention that, because I sort of thought I might get a more precise answer. After all, mine preserves the entire number 2^64, yours just preserves most. Mine might end up losing it all later in the calculations (because there are more multiplications), is that what you mean? But yes, yours is more elegant, and even if mine did get some extra precision, it didn't affect the results appearently. So, in the future, I will just use doubles and maybe try something else if I really do *need* it. I actually did this more to preserve the type of calculations that the C program was doing compared with the python program. However, I'll use the floats in python as well from now on :) Regards, Jeff > > >> #!/usr/bin/python2.2 >> >> import sys >> >> n = 1.0 >> p = 2L**64 >> c = long(sys.argv[1],10) > > Try "p = 2.**64" instead of "2L**64" and see if you get a speedup. > Also, make c int instead of long unless you want c > 2**31. From dcinege at psychosis.com Wed Jul 24 02:53:51 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Wed, 24 Jul 2002 02:53:51 -0400 Subject: cmd, readline, and /path/filename completion Message-ID: <200207240253.51980.dcinege@psychosis.com> Dunno much about programming readline, so maybe this is obvious. I toying with a unix shell written in python using shlex and cmd. (For now based on the _Python 2.1 Bible_ lextocon example...) It's actually quite functional at this point. (Though replacing bash with it, doesn't quite work yet... ) I'm trying to tweak the readline functionality, and am a bit lost. In Bash cd /etc/ Will display a list of files in /etc/ to complete against. In my shell, I will always see the files in the current directory. What must be done to mimic the bash functionaly? Is it an option that must be turned on in readline? Do I have to snag the line, and if it is a valid path, cd to that path? (then back to PWD) Dave -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From gollem at chatway.nl Tue Jul 2 19:24:23 2002 From: gollem at chatway.nl (gollem) Date: Tue, 02 Jul 2002 23:24:23 GMT Subject: Maximum size of list? References: Message-ID: Thanks Fredrik, I think that will be adequate for the time being ;-) "Fredrik Lundh" wrote in message news:twpU8.46061$n4.11000196 at newsc.telia.net... > "gollem" wrote: > > > What is the maximum listsize in python? In characters > > or items. Thnx. > > 2147483647 items, on most platforms. if you have enough > memory, that is. > > > > From aleax at aleax.it Mon Jul 8 02:18:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 06:18:36 GMT Subject: How to organize test cases with PyUnit References: Message-ID: <09aW8.43329$Jj7.1206765@news1.tin.it> Roy Smith wrote: ... > parser.parse() is supposed to (and does) return a dictionary of > dictionaries. The line "for table in tables:" should read "for table in > tables.keys():". As written, it should raise a TypeError. In the > process of trying to figure out why it wasn't, I added the "print In Python 2.2, you can loop directly on a dictionary, skipping the costly step of extracting its list of keys with a .keys() call -- so, if you're using Python 2.2, no TypeError would be raised here. This is just a part of the benefit you get from Python 2.2's new arrangement for iterators -- ability to iterate directly on such objects as dictionaries and files. Handy, speedy AND readable...! Alex From mgerrans at mindspring.com Mon Jul 29 11:54:05 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 29 Jul 2002 08:54:05 -0700 Subject: DIV and MOD References: Message-ID: > don't know how to do that. % does not work as expected (in this context) Why do you say that? / and % give exactly the results I'd expect: >>> for i in range(10): print '%d / %d is %d; %d %% %d is %d' % (i,3,i/3,i,3,i%3) 0 / 3 is 0; 0 % 3 is 0 1 / 3 is 0; 1 % 3 is 1 2 / 3 is 0; 2 % 3 is 2 3 / 3 is 1; 3 % 3 is 0 4 / 3 is 1; 4 % 3 is 1 5 / 3 is 1; 5 % 3 is 2 6 / 3 is 2; 6 % 3 is 0 7 / 3 is 2; 7 % 3 is 1 8 / 3 is 2; 8 % 3 is 2 9 / 3 is 3; 9 % 3 is 0 From jonathan at onegoodidea.com Fri Jul 12 11:11:34 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 12 Jul 2002 16:11:34 +0100 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <93DC3CC822A7272F.07F7EC43197B112B.AD4BC7C14A3B6591@lp.airnews.net> Message-ID: On 12/7/2002 15:03, in article QkBX8.72747$vm5.2639597 at news2.tin.it, "Alex Martelli" wrote: > Somebody else commented that "XML databases" are a good idea > because some programmers are bad at designing relational schemas. > . > > Now THAT is an idea that sends shivers down my spine. > Maybe I'm just too pessimistic, but I'd really like to look at > the relational schemas autogenerated from DTD's or whatever -- > and if the underlying relational stuff isn't there, or isn't at > all accessible, then please include me out of such plans. Heh. Now that would have been me ;-) Except what I actually said was: > Also, XML databases can be used and make a lot of sense if the data can be > arbitrarily structured. People are often very poor at designing relational > schemas. If the data is complex and hierarchical then a good relational schema is going to be very hard to produce, and thus more likely than not going to be done badly. XML databases can be built (as can most data repositories) on top of an RDBMS, but often they are pure databases similar to an OODB - this is because relational databases aren't fundamentally very good at managing arbitrary hierarchical information, which was my point. Hierarchical data is also not well-suited to relational querying (Oracle's "START WITH ... CONNECT BY" being the best attempt I've seen at it), which is why XML querying languages like XPath and (soon) XQuery exist. An XML database is best thought of as a hierarchical filesystem of XML files. Except that, unlike a filesystem of XML files, the database can maintain indices and a layout that enables optimised querying of fragments of multiple documents. For a reasonable example, take a look at Apache XIndice: One should be wary of getting stuck in one mindset - even if it is a very good one ;-) Jonathan From aleax at aleax.it Sat Jul 27 04:26:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 08:26:51 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> <7x3cu6f8sv.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Alex Martelli writes: >> It's not an issue of syntax sugar as superficial as what keyword to >> use. A REAL lambda, by any other name -- the ability to package up >> ANY chunk of code, not just an expression -- might add power enough >> to justify its existence. Today's lambda's just deadweight. > > I agree that the current incarnation of lambda is deficient. I Great -- we do have one point of agreement. I fear it will be the only one:-). > think it should be strengthened so you can lambdafy arbitrary code, So, invent a syntax that is nice, Pythonic (indentation etc), and free of ambiguity and error-prone aspects. Me, I haven't managed to, but that doesn't say much. It MAY be more significant that no such wonderful syntax has ever been proposed (that I know of) throughout the interminable debates over the years about lambda, anonymous codeblocks, and other such themes. > not eliminated. The current version is better than nothing, though. Here's where we disagree. It adds no real ability to the language, just little traps, pitfalls, annoyances and MTOWTDIs. > I don't see why the anti-lambda contingent doesn't want to also > get rid of anonymous scalar expressions. I mean, "scalar"? What's "scalar" about it? > a = b + (c * d) This could perfectly well be a list expression -- concatenate list b with c repetitions of list d (or, d repetitions of list c). "scalar"...??? The parentheses above are redundant, of course. That may make using them bad style, but allowing them in terms of language _rules_ is one of those MTOWTDIs we can never eliminate without ADDING horrible complications to the syntax. Hypothetically removing the production for lambda from the syntax would of course, just as hypothetically, simplify the syntax. Removing the ability to parenthesize EXCEPT where the parentheses are significant would be a nightmare of complexity for no real gain. It's therefore rather silly to try to equate the two things. > the horror! Why not insist on naming the subexpressions, e.g. > > temp = c * d > a = b + temp If there is further significant use of that c*d result later on, giving it a name (though not one such as 'temp', most likely, unless it's something's temperature I guess) might be a good idea. If the intermediate result is insignificant per se, then naming it would have no added value. It's rarely the case that functions are insignificant. The DO something, or COMPUTE something, which tends to make them worth naming. A result of a multiplication, on the other hand, IS something, and the verb "to be" is fraught with problems (I summarize some of them, albeit in a different context, in http://www.aleax.it/Python/5ep.html -- most significant are the bibliographical pointers to the relevant works of Santayana, Wittgenstein, and most relevantly Korzybski). Summarizing: it's seldom the case that it's optimal to draw attention to what something IS. It's often the case that it's best to draw attention to what something DOES. Thus, naming intermediate results that "just ARE" (results of such ops as adding, multiplying, ...) is only interesting in quite specific cases, basically when the thing you're naming has some domain specific relevance. Naming objects that "DO", i.e., functions, is more often advisable. If in one case in a thousand there's some slight advantage to not-naming a doer, that doesn't mean lambda is pulling its weight -- it's still deadwood, not worth the downsides. Alex From gerhard.haering at gmx.de Tue Jul 23 18:41:24 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Wed, 24 Jul 2002 00:41:24 +0200 Subject: What unicode character has a certain value? In-Reply-To: References: Message-ID: <20020723224124.GA6442@gargamel.hqd-internal> * DogWalker [2002-07-23 15:29 -0700]: > How would I convert the value of a unicode character to a unicode string; unichr > a unicode string to an ascii string (if possible); .encode(encoding, conflict_strategy=None) for example: u"foobar".encode("utf-16") > a unicode character to a decimal number. ord > If I have the decimal value for a unicode character, how do I convert it to > a unicode character? A unicode apostrophe has a decimal value of 8217. How > do I get a string with an apostrophe starting with 8217? > > x = 8217 > s = ??x s = unichr(8217) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From quest at lysator.liu.se Tue Jul 9 10:38:42 2002 From: quest at lysator.liu.se (Anders Qvist) Date: Tue, 9 Jul 2002 16:38:42 +0200 Subject: [snake-farm] Broken build system as of 2002-06-04 In-Reply-To: <2mznx112gm.fsf@starship.python.net> References: <20020709081716.GT20301@lysator.liu.se> <2mznx112gm.fsf@starship.python.net> Message-ID: <20020709143842.GU20301@lysator.liu.se> On Tue, Jul 09, 2002 at 01:59:53PM +0100, Michael Hudson wrote: > Anders Qvist writes: > > > The snake-farm has been choking on the python CVS source since > > 2002-06-04, like thus (on _all_ platforms): > > I've noticed :) > > > The problem occurs only when building the python source in a separate > > build dir. Eg: > > > > cd build > > ../pythonb/dist/src/config > > You mean .../configure, right? Sorry about that. Yes, ../python/dist/src/configure > > make all > > > > It seems to me that sysconfig.py is unaware that building may occur in > > a separate directory. > > Well, it's more than that, because I build like this all the time and > don't get the failures. Are the scripts the snake-farm uses viewable > anywhere? Sure. Have a look at: http://cvs.lysator.liu.se/viewcvs/viewcvs.cgi/?cvsroot=snake-farm However, I can reproduce the error manually on my local Linux box, so it's not likely to be directly related to the scripts. For a demonstration, have a look at: http://h25.ryd.student.liu.se/temp/da_log http://h25.ryd.student.liu.se/temp/strace_log ... generated by the following command line: ( cvs -d :pserver:anonymous at cvs.sourceforge.net:/cvsroot/python co python; mkdir build; cd build; ../python/dist/src/configure; strace -f -o ../strace_log make all ) > da_log 2>&1 & System information: a fairly recent debian install. ii libc6 2.2.5-4 GNU C Library: Shared libraries and Timezone ii kernel-image-2 20020320 Linux kernel binary image for version 2.4.18 ii make 3.79.1-13 The GNU version of the "make" utility. ... but as I said, the problem (with identical traceback) also occurs on: fafner (SunOS fafner 5.8 Generic_108528-13 sun4d sparc SUNW,SPARCcenter-2000) sandra (SunOS sandra 5.7 Generic_106541-10 sun4m sparc sun4m) hal (AIX hal 2 4 000000042E00 unknown) taylor (HP-UX taylor B.11.00 A 9000/829 278863302 two-user license) -- Anders "Quest" Qvist "We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the Internet, we know this is not true." -- Robert Wilensky From grante at visi.com Thu Jul 11 19:06:26 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 11 Jul 2002 23:06:26 GMT Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <080720021458067296%pecora@anvil.nrl.navy.mil> <080720021645110243%pecora@anvil.nrl.navy.mil> Message-ID: In article <080720021645110243%pecora at anvil.nrl.navy.mil>, Lou Pecora wrote: >> Saves typing, yes, but makes your code harder to understand by >> somebody else who has to read and maintain it later. > > True, to some extent, although nobody will have to maintain my code. > > It's strictly specialized to my work and will not be used for > production of anything. If you only knew how many hundreds of hours I've spent maintaining code of somebody else's that was never meant to be seen by anybody or to be used for "production" purposes... -- Grant Edwards grante Yow! Is the EIGHTIES at when they had ART DECO visi.com and GERALD McBOING-BOING lunch boxes?? From phr-n2002b at NOSPAMnightsong.com Wed Jul 31 03:17:23 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 31 Jul 2002 00:17:23 -0700 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: <7xlm7sz7r0.fsf@ruckus.brouhaha.com> Pekka Pessi writes: > If you want to call the __call__ attribute, that is a > no-brainer, too: > > >>> class module(types.ModuleType): > ... def __call__(self, *x, **kw): The problem then is how to make the import statement create this new class of module instead of the regular kind. From dreed at capital.edu Tue Jul 30 16:50:53 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 30 Jul 2002 16:50:53 -0400 Subject: Cookbook: Associating multiple values with each key in a dictionary In-Reply-To: <20020730215002.A2145@bork.demon.nl> (message from Egbert Bouwman on Tue, 30 Jul 2002 21:50:02 +0200) References: <20020730171536.A992@bork.demon.nl> <20020730131414.C7503@eecs.tufts.edu> <20020730215002.A2145@bork.demon.nl> Message-ID: <200207302050.g6UKork08480@localhost.localdomain> > From: Egbert Bouwman > > On Tue, Jul 30, 2002 at 01:14:14PM -0400, Michael Gilfix wrote: > > > > I'm not really sure why you prefer the list method. Is there something > > that you can't accomplish with the nested dictionaries? > > When I need > { 'boys': ['mike', 'egbert'], 'girls': ['laura','lisa'] } > it hurts me when I have to build: > { 'boys': {'mike' : 1, 'egbert' : 1}, 'girls': {'laura' : 1,'lisa' : 1} } > > That adds an extra layer of complexity when i construct it, > I have to remember or document that the values can be thrown away, > and I have now sets of keys, while I need sets of values. > > I try to be a good pythonista, so I and simplicity come first, > and efficiency and implementation come second. > > Of course that all changes when I really need the values, ie when > they don't have some dummy value anymore. But in that case > we simply have a nested dictionary, which is not our subject now. > > As an afterthought: is it necessary that lists are slower than > dictionaries ? Cannot they be subjected to some hash machine as well ? > At least in some cases, ie when you search in lists ? > > egbert The following works: { 'boys': ('mike', 'egbert'), 'girls': ('laura','lisa') } Dave From mwh at python.net Wed Jul 24 07:25:16 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 24 Jul 2002 11:25:16 GMT Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3AEDD6.78B39D70@engcorp.com> <3D3B4F80.B0D6BE07@engcorp.com> <3D3E0D7F.D13E5145@engcorp.com> Message-ID: Peter Hansen writes: > Aahz wrote: > > > > In article <3D3B4F80.B0D6BE07 at engcorp.com>, > > Peter Hansen wrote: > > >I'm trying to follow Aahz' advice and avoid "reference" in favour of > > >"binding" etc, but I guess I carried it too far! :) > > > > Your problem wasn't in your use of "binding", but in your use of > > "name; I use "target" to refer to the general case of thingy that can > > contain a binding, of which names are a subset. "Names" are words > > attached to a namespace (i.e. function local, module global, builtin, or > > object attribute). Another target is an index/key for container > > objects. > > Hmmm... "target" sounds like the wrong direction. Shouldn't it > be a "source" for the binding? Or maybe another term which doesn't > have what seems to me the potential for confusion would be better. Common Lisp calls them "places", which is a reasonable name. It's not that much of an issue in Python as there aren't that many of them (names, attributes, subscripts, slices). In CL, you can define your own (tho' it's a bit tricky). Cheers, M. -- MARVIN: Oh dear, I think you'll find reality's on the blink again. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From huaiyu at gauss.almadan.ibm.com Wed Jul 10 14:10:35 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 10 Jul 2002 18:10:35 +0000 (UTC) Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> <7x1yacjml8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >William Park writes: >> I've seen it, but it's a tarball which you have to download and compile. >> Whereas, 'netdate', 'ntpdate', and 'telnet 13' are ready to run on all >> Linux distribution. > >Why do people keep saying that? Netdate and ntpdate are not on either >of the Red Hat boxes I use (one is RH 7.2 and one is 7.3). The rpm package might be called ntpd or xntpd, or some other variant. One problem with rpm is that if a file is not on the installed system, you have to jump through some loops to figure out which package it is supposed to come from. Hopefully the eventual CPyAN would be able to handle such queries in an easy way. Huaiyu From beej at piratehaven.org Wed Jul 17 21:08:00 2002 From: beej at piratehaven.org (Beej Jørgensen) Date: 18 Jul 2002 01:08:00 GMT Subject: popen2 question References: Message-ID: In article , Rajarshi Guha wrote: >Input/Output Error 173: Broken pipe A Unix process will receive SIGPIPE when it tries to write to a two-ended file descriptor after the other end of the descriptor has been closed. Somehow the python end of the pipe that's hooked to fortran's stdout is being closed before fortran is done writing to it. >cin, cout = popen2.popen2('qnetin') >cin.write('train\n10\n\n1000\n') >line = cout.readline() I think you might want cout, cin = popen2.popen2('qnetin') ^^^^ ^^^ Maybe writing to the wrong end of the pipe messed it up somehow. Or maybe I have it backwards. :) If this is the case, I can't believe it worked at all. >Why does the popen2 command work for the first 2 lines of output and then >fail on the third? I don't know...this clashes with my suggested solution. Are you explicitly closing one end of the pipe before the fortran program finished writing? I know this is all vague, but hopefully there's something helpful here. YMMV. -Beej From aleax at aleax.it Wed Jul 24 10:36:00 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 14:36:00 GMT Subject: Detecting pipe on stdout? References: Message-ID: Alexander Schreiber wrote: > Hi! > > Is there any way for a Python program to detect wether its stdout has > been redirected to a pipe/file (like "./programm | less")? I've didn't > find anything about this in the FAQ and failed to come up with the right > search terms for google. > > Reason: I've got a Python program[0] here which normally colorizes its > output (to the terminal) using escape sequences. This is fine and nice > while running on a terminal, but when running the program with less > attached to it the escape sequences are annoying. Ideally, I want to > detect a pipe attached to stdout and switch of the color (the flag is > already there) in this case. > > Regards, > Alex. > [0] Not written by me. You probably want os.isatty(sys.stdout.fileno()). Not quite what you ask for (it's false whether the redirection is to a pipe OR a file), but probably what you want. Alex From emile at fenx.com Thu Jul 11 20:51:29 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Jul 2002 00:51:29 GMT Subject: Most pythonic way to format a number with commas? References: Message-ID: Ned Batchelder > For dir/ls replacement script, I wanted to format file sizes with > commas as a thousands separator. I didn't find anything in the > standard library, [snip] > Is there one? It's buried in locale... >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'English_United States.1252' >>> locale.format("%8.2f", 1234.56) ' 1234.56' >>> locale.format("%8.2f", 1234.56,3) '1,234.56' -- Emile van Sebille emile at fenx.com --------- From phr-n2002b at NOSPAMnightsong.com Fri Jul 19 02:12:47 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 23:12:47 -0700 Subject: Python robot web client? References: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> <60C215D19EB182D3.4B74CCBAAB7C5A11.2070483D2F315625@lp.airnews.net> Message-ID: <7xwursp7og.fsf@ruckus.brouhaha.com> claird at starbase.neosoft.com (Cameron Laird) writes: > Paul, you've received several useful suggestions. More than > any of these others, though, I think you'll find Pycurl http://pycurl.sourceforge.net/ > addresses your range of re- > quirements "out of the box". > to be co I'll check this and the other suggestions too. All the responses are appreciated. Thanks. From chris.gonnerman at newcenturycomputers.net Sat Jul 20 10:00:02 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sat, 20 Jul 2002 09:00:02 -0500 Subject: Lists & two dimensions References: Message-ID: <005901c22ff5$bf3c7aa0$0101010a@local> ----- Original Message ----- From: "Pichai Asokan" > I am a trainer and in a training session a participant came up with a > problem that stumped me: > > Here is the code snippet that isolates what I want: > -------------------- > board = [[-1] * 3 ]*3 > print board > board[1][2] = 'x' > print board > -------------------- > Output > ----------------------- > [ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ] > [ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ] > ----------------------- > > I thought > board = [[-1] * 3 ]*3 > should give me a list of 9 elements; > but ... > > What is going on? Multiplication of a list by N results in N references to the same list. The inner list contains (references) scalars, so each slot is effectively independent, but the outer list contains lists... so there you go. > Where can we read more to understand what is goingg on? This is a FAQ I think; go to www.python.org and take a look there. (Or someone else may post the pointer if you are lucky). Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From als at usenet.thangorodrim.de Wed Jul 24 14:39:43 2002 From: als at usenet.thangorodrim.de (Alexander Schreiber) Date: 24 Jul 2002 18:39:43 GMT Subject: Detecting pipe on stdout? References: Message-ID: Alex Martelli wrote: >Alexander Schreiber wrote: > >> Is there any way for a Python program to detect wether its stdout has >> been redirected to a pipe/file (like "./programm | less")? I've didn't >> find anything about this in the FAQ and failed to come up with the right >> search terms for google. > >You probably want os.isatty(sys.stdout.fileno()). Not quite what >you ask for (it's false whether the redirection is to a pipe OR a >file), but probably what you want. Yes, thats what I want - I was thinking of less glued to stdout, but the same applies to redirecting stdout somewhere else (like a file). I'm now using sys.stdout.isatty() as suggested by another poster and it does the job. Thanks. Regards, Alex. -- Those who desire to give up Freedom in order to gain Security, will not have, nor do they deserve, either one. -- Benjamin Franklin From gherron at islandtraining.com Fri Jul 12 16:37:11 2002 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 12 Jul 2002 13:37:11 -0700 Subject: Executing outside command In-Reply-To: <3YGX8.82020$eF5.2553773@twister.austin.rr.com> References: <3YGX8.82020$eF5.2553773@twister.austin.rr.com> Message-ID: <200207121337.11359.gherron@islandtraining.com> On Friday 12 July 2002 01:26 pm, David Noriega wrote: > How would I have python execute a command like ogg123? > David M Noriega >>> import os >>> os.system('ogg123') If you wish to provide input to or catch output from the command, then look at the os.popen... family of functions. Gary Herron From pecora at anvil.nrl.navy.mil Sat Jul 20 11:32:24 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Sat, 20 Jul 2002 11:32:24 -0400 Subject: A better self References: Message-ID: <200720021132243925%pecora@anvil.nrl.navy.mil> Since I've been complaining, I'll keep on responding. In article , wrote: > 1) Learn to like it - I've spent more time reading about getting rid of > self than time actually typing 'self.' (i.e. the costs are minimal and it > makes my code more readable and explicit - it's worth it to me!) Well, readability _is_ the issue in numerics and math apps. > 2) Learn to just accept it (perhaps you find it annoying, but at least > it's not something you deal with on every line of code) True, but more lines than most programmers when you do numerics. > 3) Use the smarts of your editor - macros, special syntax highlighting, > etc. Not practical for me (not sure about others) since I tend to develop using an edit/run style. Python is so quick that with the Macintosh IDE I just code a little, then quickly run a test. Correct code until satisfied, then code more new stuff and test. etc. etc. etc. But that eliminates the macros or fancy editor stuff. It's a great way to code though (only with Python :-) ) > 4) Use a shorter name than self, e.g. 's' Yes, that helps. > 5) Use the x,y,z = self.x, self.y, self.z idiom Yes, also works. > 6) Have Python generate the function bodies for you, e.g: > > class SomeClass: > method = MyCoolUnboundMethodMaker('arg:x = y*z + t*arg') Hmmm...what's that? I don't get it (I hope I am about to learn something here.) > 7) Change your design - if something is awkward it *may* be a flaw in the > language, but there's also a really, really good chance that a different > approach to your program would be best. Not too relevant to the math required. You have to write a math expression. -- Lou Pecora - My views are my own. From loewis at informatik.hu-berlin.de Thu Jul 4 05:50:51 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Jul 2002 11:50:51 +0200 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: robert_kuzelj at yahoo.com (Robert Kuzelj) writes: > lets simply say: the requirement is exactly to destinguish between > instances and classes. There is no difference between instances and classes. Classes are objects that are callable, but there are also other objects that are callable. In Python 2.2, an object is called "a class" (or, more precisely, "an old-style class") if its type is ClassType. An object is called "a type" (or "a new-style class") it its type is TypeType. Apart from that, there is nothing special about classes, compared to, say, strings. Regards, Martin From pajer at iname.com Wed Jul 24 21:17:16 2002 From: pajer at iname.com (Gary Pajer) Date: Thu, 25 Jul 2002 01:17:16 GMT Subject: Python 2.2.1 Idle can't find _sre (Win98) References: Message-ID: I tried to follow the instructions in http://www.python.org/2.2.1/ First I downloaded http://www.python.org/ftp/python/2.2.1/UNWISE.EXE over my existing unwise.exe Then I downloaded http://www.python.org/ftp/python/2.2.1/Python-2.2.1.exe Then I started the installer. It detected c:/python22 and offered to install there. I said ok That means it was installing in the same directory as version 2.2 lived. It offered to make backups of existing files, I said yes, please. That's all. Since my first post, I noticed that PythonCard applications crashed with the same error. I found a file called _SED.PYD in the new installation, but in the backup, the filename was lowercase. I renamed the file to _sed.pyd, and now PythonCard apps start, but IDLE still doesn't. Thanks for responding, BTW "Martin v. Loewis" wrote in message news:m3sn290wau.fsf at mira.informatik.hu-berlin.de... > "Gary Pajer" writes: > > > Using Win98SE. > > Python 2.2 has been working fine. On a whim I upgraded to 2.2.1 today. > > Now Idle won't start. > > What exactly did you do to update? What files did you download > (precise URL please), in what order did you perform what actions? > > Regards, > Martin > From shagshag13 at yahoo.fr Mon Jul 8 07:20:21 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 8 Jul 2002 13:20:21 +0200 Subject: Memory ? References: Message-ID: Thanks again, i'm going to look at Numeric extension package, s13. From gtalvola at nameconnector.com Tue Jul 16 13:12:22 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Tue, 16 Jul 2002 13:12:22 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty Message-ID: <61957B071FF421419E567A28A45C7FE514A5C5@MAILBOX.nameconnector.com> Geoffrey Talvola wrote: > In case you're wondering, this is in Webware's WebKit > application server > where there is a pool of N threads, and a queue of > (non-thread-safe) servlet > instances acting as a cache. We only want to create servlet > instances when > all existing instances are in-use. When a given thread needs > a servlet, it > basically does: > > try: > instance = cache.get_nowait() > except Queue.Empty: > instance = new_instance() > # use the instance... > cache.put(instance) > > The problem is that every once in a while get_nowait() > returns Empty when > the queue isn't actually empty, so the size of the cache > grows slowly and > unboundedly over time. But I'd prefer for the cache to > contain at most N > instances where N is the number of threads. > > - Geoff Now that I think of it, maybe a Queue just isn't the right tool for this job. Queues are basically designed for the case where you want block on an empty queue. But for this use I never want blocking. Perhaps a simple combination of a list and a lock would be better, or even a list alone without a lock: try: instance = cachelist.pop() except IndexError: instance = new_instance() # use the instance cachelist.append(instance) As long as pop() and append() are atomic, which I believe they are, then this ought to work. (This actually implements a stack, not a queue, but for this application it doesn't matter.) - Geoff From daniel.dittmar at sap.com Fri Jul 12 04:50:07 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 12 Jul 2002 10:50:07 +0200 Subject: ANN: Python Web Programming Wiki Message-ID: As part of the relaunch of the Python Wiki (http://www.python.org/cgi-bin/moinmoin/), I've copied Paul Boddie's work on Web Programming Frameworks into the Wiki (http://www.python.org/cgi-bin/moinmoin/WebProgramming) and added a few more entries. Feel free to add more information, comparisons, recipes etc. Daniel From huaiyu at gauss.almadan.ibm.com Wed Jul 24 17:34:51 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 24 Jul 2002 21:34:51 +0000 (UTC) Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> <3D3E0E02.89EC9D1@engcorp.com> Message-ID: Peter Hansen wrote: >Huaiyu Zhu wrote: >> >> Peter Hansen wrote: >> >Paul Rubin wrote: >[about putting __call__ in modules] >> >Although you can do as you wish, of course, I want to chime in >> >with a "this is a really bad idea" and hope you don't follow through >> >on it. This is, even in the best case, going to make your code >> >less readable to anyone else. It is also likely to cause maintainability >> >problems because making the claim "but this module has only one function!" >> >almost certainly means it will not stay that way forever. >> >> Why is this so? Modules appear to be just singletons associated with files. >> Why making them more similar to other objects would make programs less >> readable? Maybe some examples of usage would help to clarify the issues. >> As a counterexample, I've been confused many times by 'from foo import foo', >> not knowing which foo is which. > >You can make them as similar to other objects as you wish, but it wouldn't >change my opinion that "module" refers to a specific *kind* of object for >which the __call__ convention has little or no merit. I'm not saying it >should not be there, just that it should not be used if it is. :-) That's still a claim without support. I take it to mean that there is no known reason at all (such as readability) that it should not be there or that it should not be used if it is there. Huaiyu From dpinol at hotmail.com Fri Jul 5 10:15:50 2002 From: dpinol at hotmail.com (=?ISO-8859-1?Q?Daniel_Pi=F1ol_Laserna?=) Date: 5 Jul 2002 07:15:50 -0700 Subject: COM component implementing custom interfaces References: <46585325.0207030824.7a22dfa1@posting.google.com> <3D2387EF.6020306@skippinet.com.au> <46585325.0207040825.7a5201b7@posting.google.com> <3D24EA63.50105@skippinet.com.au> Message-ID: <46585325.0207050615.3cf42b6f@posting.google.com> >Mark Hammond wrote in message >news:<3D24EA63.50105 at skippinet.com.au>... > Daniel Pi?ol Laserna wrote: > > Mark Hammond wrote in message news:<3D2387EF.6020306 at skippinet.com.au>... > > > >>You need to check out the win32com\servers\test_pycomtest.py - this > >>shows how to implement non IDispatch based interfaces. > That is a sample, and requires the PythonCOM test harness to completely > work. So while you can probably not directly run the sample, you should > be able to get enough out of it to make yours work. It works! Thanks I created my class from the win32com help documentation, where I hadn't since any reference to the requirement of using universal.RegisterInterfaces. I understand the registering failed in your example because that TLB didn't exist on my machine universal.RegisterInterfaces('{4A5E2E81-C093-11d4-9F1B-0010A4D198C2}', 0, 0, 93, ["ICapeUnitEdit"]) From sakito at s2.xrea.com Tue Jul 9 09:00:15 2002 From: sakito at s2.xrea.com (sakito) Date: Tue, 09 Jul 2002 22:00:15 +0900 Subject: HTML to PDF converter? In-Reply-To: References: Message-ID: <0pmega.4if.ln@localhost> At Tue, 9 Jul 2002 01:08:47 -0700 (PDT), Lance Ellinghaus wrote: > > Does anyone know of a HTML to PDF converter that is written in Python? > > Thank you, > > Lance Ellinghaus http://www.reportlab.com/toolkit/index.html No? ---- sakito http://sakito.s2.xrea.com/ mailto:sakito at s2.xrea.com From peter at engcorp.com Sat Jul 20 13:32:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Jul 2002 13:32:50 -0400 Subject: PSU Warning: TimeBreachException (was Re: Python 2.3) References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <1027175934.94979.0@iris.uk.clara.net> Message-ID: <3D399EC2.80CFF918@engcorp.com> Gerhard H?ring wrote: > > * Rhymes [2002-07-20 17:13 +0200]: > > Gerhard H?ring wrote: > > >python-dev archives (http://mail.python.org/pipermail/python-dev/). > > how much daily-traffic has this maillist? same as lkml or bugtraq's ? > > This question can easily be answered by looking at the above link. Notice to all PSU members! A bug in an experimental patch to Python 2.6.1beta has accidentally leaked recent mailing list postings into mid-2002. The link above shows that damage was minimal, being limited to a single post by the /F-bot (which was running the patched beta at the time) from February 2005, but collateral damage could be considerable if this breach is treated by some as proof that the time machine really From edream at tds.net Fri Jul 12 11:11:07 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 12 Jul 2002 15:11:07 GMT Subject: tk/tkinter radiobutton in grid bug? Message-ID: <3D2EF186.4CB25463@tds.net> Hi, If b is a radiobutton, b.select() (b -select) does not work when b is embedded in a grid, and works just fine when packed. In either case, the radio buttons work, but in the grid case the proper button is not initially selected. None of the various alternatives to b.select work either. Is this a known bug? I have a dim memory of this being discussed somewhere...Does anyone know a workaround that still uses grids (I'd like to embed the radiobuttons in a labeled frame, and grids are the only way I know to do that.) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From aleax at aleax.it Fri Jul 5 16:50:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 20:50:13 GMT Subject: dynamic path to a method ??? References: <51a64474.0207051007.19cb0441@posting.google.com> Message-ID: <9EnV8.47930$vm5.1717236@news2.tin.it> Roger Ineichen wrote: ... > class (instance) = 'personManager' I'll have to assume this is classInstance or something like that, because the syntax is unlikely to make sense. > method = 'addPerson(firstname='', lastname='')' This is equivalent to: method = 'addPerson(firstname=, lastname=)' so I'm not sure why you're indicating the extra quotes -- maybe you thought they would be somehow preserved? They aren't -- each single quote closes a string (and the immediately following one then opens another string literal and Python juxtaposes the adjacent literals). Maybe you mean: method = "addPerson(firstname='', lastname='')" ??? > attribute1, firstname = 'max' > attribute2, lastname = 'miller' These will fail -- when you assign something to two names in this way, the 'something' needs to be a sequence of exactly two items. > how can I construct a dynamic path like: > personManager.addPerson( firstname='max', lastname='miller') You can easily construct this string by string manipulation. But it's the wrong approach, because then executing such a constructed statement is fraught with dangers -- any error, any malice on the user's part, and you could be reformatting your hard disk or the like. Given all the doubts and strangeness in the foregoing I'm not going into more details at this point, but no matter what, one point IS quite crucial: don't build up statements or expressions for the purpose of using exec or eval on them unconstrainedly. You'll be a far happier person if you avoid this trap. Alex From mgilfix at eecs.tufts.edu Mon Jul 29 09:48:33 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 29 Jul 2002 09:48:33 -0400 Subject: announcement In-Reply-To: ; from gerhard.haering@gmx.de on Sun, Jul 28, 2002 at 09:55:46PM +0000 References: Message-ID: <20020729094832.C15737@eecs.tufts.edu> If you'd like another reference, check out the graphs directory in the CVS project: http://www.sourceforge.net/projects/qualm. I had to deal with some optimization tricks such as double-buffering and creating an extensible canvas class that you might find useful. I was debating whether or not I should whip up an article on graph drawing for PyZine and well, this might be a good way to guage interesting :) -- Mike On Sun, Jul 28 @ 21:55, Gerhard H?ring wrote: > Very nice! It might also come in useful, as I plan to do a > graph-drawing app in wxPython, too. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 15:41:43 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 12:41:43 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: <7xlm7ywa2w.fsf@ruckus.brouhaha.com> "Britt A. Green" writes: > So I know what lambda functions are, they're syntax and how they're used. > However I'm not sure *why* one would use a lambda function. What's the > advantage that they offer over a regular function? You can use them inside other expressions, e.g. suppose you want to sort a bunch of strings starting with the second letter: a = ['apple', 'banana', 'pear', 'watermelon'] a.sort(lambda x,y: cmp(x[1],y[1])) => ['banana', 'watermelon', 'pear', 'apple'] Without lambda, you'd have to define a separate named function: def CompareOnSecondLetter(x,y): return cmp(x[1],y[1]) a = ['apple', 'banana', 'pear', 'watermelon'] a.sort(CompareOnSecondLetter) There's a school of thought that says Python shouldn't have lambda and you should have to use def and give every function a name, but IMO that goes against the decision that functions are objects in Python. Python isn't Fortran. There's a middle ground that says the name "lambda" (which comes from Lisp) wasn't a good choice and another name should have been used instead, like maybe 'func', which does the same thing. I guess that's reasonable. I'm used to lambda from Lisp but another name would probably be less scary to non-Lisp-users. From mf at mrinfo.de Mon Jul 22 10:31:34 2002 From: mf at mrinfo.de (Marko Faldix) Date: Mon, 22 Jul 2002 16:31:34 +0200 Subject: Anybody using 4suite for xslt processing? References: Message-ID: Hi, [snip] > from xml.xslt.Processor import Processor > p = Processor() > p.appendStylesheetUri('tmp/temp.xsl') > > > I use a different import statement than you did; if you use the import > above, do you still get the exception? My installation of 4suite dropped the respective directories to Python22\Lib\site-packages\Ft so I have to use Ft.Xml.Xslt - without Ft 4suites classes can't be found. In Python22\Lib\site-packages\Ft\Xml\Xslt there is a file called Processor.py which contains class Processor. Indeed, inside this class I can't find appendStylesheetUri. Then I searched for string "appendStylesheetUri" in the whole tree \Python22 and found nothing that implements this. Is the installation gone wrong? > > What happens when you do dir(Processor)? Does appendStylesheetUri > show up in the listing? What version of 4suite are you using? > In directory Python22\Lib\site-packages\Ft there is a file __init__.py that says: __revision__ = "$Id: __init__.py,v 1.9 2002/03/22 12:26:51 jkloth Exp $" In diretory Python22\Lib\site-packages\Ft\Lib there is a file __packageInfo__.py that says: version = "0.12.0a2" I rather believe it was 0.12.0a2. What do you have in your directories, which path contains a class with appendstylesheeturi? From darnold02 at sprynet.com Mon Jul 29 19:28:48 2002 From: darnold02 at sprynet.com (Don Arnold) Date: Mon, 29 Jul 2002 23:28:48 GMT Subject: pickling problems with Pmw/Tkinter References: Message-ID: On 29-Jul-2002, Eric Brunel wrote: > > I'm trying to develop a Tkinter app that pickles the values of a couple > > of > > Pmw counters. Then on its next run, it unpickles these values and loads > > them back into the counters. That's the plan, anyway. Here's what I > > have: > > > [snip code] > > self.bind('',self.shutdown) > > First: why do you make your app class inherit from Frame? I've seen many > people doing that and I can't understand why. There are many things you > can > do on an actual window (in Tkinter words a Toplevel) that you just can't > do > on frames: "regular" menubars, specific events for windows, and so on... I was inheriting from Frame because that's what "The Tkinter Life Preserver" and Grayson's book use. I'll try inheriting from Toplevel and see how that works. > > So I would make app inherit from Tk or Toplevel and do the following: > > self.protocol('WM_DELETE_WINDOW', self.shutdown) I haven't seen this method used before, but I'm (obviously) pretty new to Tkinter. > > This may solve the problem. In fact, with the binding on , I > suspect the contained widgets to be destroyed *before* the binding is > called. So the Pmw counters in your _minwordlen and _maxwordlen attributes > > may already have been destroyed. However, why no exception is raised is a > mystery... > > If you do it that way, put also a self.quit() in your shutdown method or > the window won't close. > I was thinking it had something to do with binding , since I later added a 'Save' button to call the method explicitly and it worked fine. > HTH > -- > - Eric Brunel - > PragmaDev : Real Time Software Development Tools - > http://www.pragmadev.com Thanks for all your help! Don From m.laranjeira at datacraft.com.br Wed Jul 31 10:05:52 2002 From: m.laranjeira at datacraft.com.br (Marcus Vinicius Laranjeira) Date: Wed, 31 Jul 2002 11:05:52 -0300 Subject: How to put a bitmap in a wxPanel ? In-Reply-To: References: <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> Message-ID: <5.1.1.6.0.20020731110330.00a1a9e0@imap.datacraft.com.br> All, I am using the boa constructor, and I need to put the logo of my company in the wxPanel. This bitmap will be static and it will be there just for decoration purposes. Anyone can help me ? Cheers, Marcus From olc at ninti.com Wed Jul 3 22:22:22 2002 From: olc at ninti.com (Michael Hall) Date: Thu, 4 Jul 2002 11:52:22 +0930 (CST) Subject: Newbie lists question Message-ID: I have a problem with an HTML select box using option values that are drawn from a MySQL database and put into a list. This is the code that creates the list: db = MySQLdb.connect(user="xyz",passwd="xyz",db="names_db") c = db.cursor() sql = "SELECT last FROM names_table" query = c.execute(sql) result = c.fetchall() selectlist = [] for last in result: #selectlist.append(last) selectlist = selectlist + [last] As you can see, I have tried two ways of building the list. Both seem to produce the same result when the list is iterated through and printed, which looks something like this: ('van Rossum',) ('Wall',) ('Lerdorf',) ('Ousterhout',) When I pass the list to a function that creates a selectbox, my options end up just like they are above: What I'd like is this: I know I could probably strip the round brackets and single quotes out using a regex, but is there an easier way? Is there something pretty basic about lists that I've missed here? TIA Michael Hall From jolsen at mailme.dk Sun Jul 7 07:50:03 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 7 Jul 2002 04:50:03 -0700 Subject: structs in python References: <7xsn2wyrr2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xsn2wyrr2.fsf at ruckus.brouhaha.com>... > > Yes, it seems clumsy to me. See how error prone it is: your __init__ > function arg list forgot to mention 'self'. Exactely! Why self? This part of the python syntax is clumsy :-) Jesper From j-jinkins at usa.net Sat Jul 20 13:13:35 2002 From: j-jinkins at usa.net (Jim Jinkins) Date: Sat, 20 Jul 2002 17:13:35 GMT Subject: args command line... References: <409a56e2.0207200133.35cdc06b@posting.google.com> Message-ID: <3D399A3D.1060002@usa.net> Shagshag wrote: >hello, > >i'm looking for a script able to handle/understand "common" command >line options like : > >ascript.py -option this_is_a_directory/* >ascript.py -another_option file1 file2 file3 -another_option2 >this_is_another_dir > >i think that should exist somewhere... > >(i wish to learn as it should be written in a good pythoner's way but >also gain time by re-using it) > >thanks in advance, > >s13. > > See module getopt in the standard library. Jim Jinkins From gerhard.haering at gmx.de Thu Jul 18 14:02:17 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 20:02:17 +0200 Subject: Sharp Zaurus In-Reply-To: <3d0678bb.0207180926.4893aa31@posting.google.com> References: <1026919964.826307@irys.nyx.net> <3d0678bb.0207180926.4893aa31@posting.google.com> Message-ID: <20020718180217.GA2257@lilith.my-fqdn.de> * William Peterson [2002-07-18 10:26 -0700]: > sarayu balu wrote in message news:<1026919964.826307 at irys.nyx.net>... > > Hi, > > Is there any Python, more appropriately Jython, for this PDA ? > > Is Jython Open Source ? > > Thanks, > > SB > > Python has been ported, as another poster says. > > For Jython, look at http://www.jython.org/platform.html At the bottom > of the page, while discussing Kaffe, it says that Jython requires a > full JVM and will have problems with a VM that only implements the > PersonalJava subset. I believe this is what you have on the Zaurus, so > it's questionable whether Jython will work there. There is a StrongARM port of the Blackdown JDK, but AFAIR it requires an X-Server for GUI stuff. IIRC there _is_ a Java VM that runs on QtEmbedded on a StrongARM proc, probably it's a commercial one. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From blipoh at mail.com Mon Jul 15 23:25:14 2002 From: blipoh at mail.com (Jason) Date: 15 Jul 2002 20:25:14 -0700 Subject: Windows modem question... Message-ID: I've been digging through all of the past posts about using a modem, and everything seems to reference serial modems. I was just wondering if the serial modules will allow me to access internal modems, or if that's a whole other problem. If it is a whole other problem, please steer me in the right direction. Thanks. Jason From b.maryniuk at forbis.lt Wed Jul 10 10:25:02 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 10 Jul 2002 16:25:02 +0200 Subject: Why self? In-Reply-To: <100720021010112153%pecora@anvil.nrl.navy.mil> References: <3D2B5331.7090104@onsitetech.com> <100720021010112153%pecora@anvil.nrl.navy.mil> Message-ID: <200207101625.02587.b.maryniuk@forbis.lt> On Wednesday 10 July 2002 16:10, Louis M. Pecora wrote: > Eeeewwwww! I am not familiar with the double underscore syntax. Just private variables. Don't warry... -- Sincerely yours, Bogdan M. Maryniuck "World domination. Fast" (By Linus Torvalds) From francois.lepoutre at seriatim.com Fri Jul 12 06:16:30 2002 From: francois.lepoutre at seriatim.com (François Lepoutrre) Date: Fri, 12 Jul 2002 11:16:30 +0100 Subject: Python for data driven website? References: Message-ID: Hi, We have delivered a portal with business-content on the web recently and made the switch recently from ms iis-based development into python-based web apps. Develop on win32, deliver on *nix. Application speed is comparable to isapi-based apps. That means fast. But CODING IS SO MUCH EASIER once python fits your brain. Our development base: - python for full and fine-grain programmatic control of the http content delivered, - apache+mod_python for ultra-fast delivery, (you can have database handles and python content persist in into the apache engine - great for speed and gentle to the db engine) - mxodbc for connectivity (our server solutions can be delivered independant from the db-engine on both linux and win32 platforms) and mxdatetime for easy datetime management (a real code saver for date-intensive business apps). For information we have sticked to "proprietary database" for the moment. If you deliver application with relatively simple data structures sure open source db will do. "big iron" may still be worth the money. Possibly for a couple of years. If your application is really data-driven (that the case for ours), the db may well become the bottleneck at some stage). But python will do its part. Clean, robust and no-fuss language. You can deliver fully productive python "servlets" after a couple of weeks... And run them on win32 or *nix. Only asp and php will compete. Clearly the "non Visual Basic Language" for the web. Web-programming is not visual anyway.... I cannot comment on page-based web-programming (asp,jsq,php,psp). No practice in this field. PHP seems pretty strong if your application essentially requires html merging+some scripting. If that is the case i'd stick to php scripting. That was not ours. A "page" approach would have lead to spaghetti-coding. Hugh! In case your app is more of a of servlet thing (often the case for data-driven apps), i'd recommend that you try to understand and test the python cgi model thoroughly first and see if your brains feel comfortable with it. If that is the case : - stick to cgi for a while, roll your own "servlet" stuff (may or not be complex) and optimize later thru mod_python (we did that) or fastcgi, - try a framework that fits your brains (possibly zope if the app is on on the groupware collaborative side, webware if is a more conventional stuff or even the dead-simple mod_python publisher module) You are on the right track. Good luck to you From duncan at NOSPAMrcp.co.uk Wed Jul 10 03:58:04 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 10 Jul 2002 07:58:04 +0000 (UTC) Subject: 8 Queens Problem References: Message-ID: Duncan Booth wrote in news:Xns9246AB0164B5Aduncanrcpcouk at 127.0.0.1: > Here are a couple of solutions based on your version but using > generators. This has the advantage of giving you all the solutions for > possible further processing, instead of just printing them out, and > also allows you to avoid calculating all solutions if you just want > one: I realised after posting that, I should have not tried to follow the structure of the original so closely. Here is (IMHO) a rather cleaner generator based solution: ---- queens.py ---- # 8 queens generator from __future__ import generators from operator import add, sub def queens(col, row): '''Place 'col' queens on a grid col by row. Generates all possible solutions''' if col <= 1: for y in range(row): yield [(0, y)] else: x = col-1 for solution in queens(x, row): t = zip(*solution) diaga, diags, rows = map(add, *t), map(sub, *t), t[1] for y in range(row): if x+y not in diaga and x-y not in diags and y not in rows: yield solution + [(x, y)] for s in queens(8,8): print s break print len(list(queens(8,8))),"solutions" ---- end of queens.py ---- -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From ajs at ix.netcom.com Mon Jul 8 08:41:23 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Mon, 8 Jul 2002 08:41:23 -0400 Subject: Properties - when and why Message-ID: <000501c2267c$c5644c00$734ffea9@Arts> Alex writes - >The obvious solution for this case is to keep your original >get_V method intact and to code V_homogeneous the simple way: >def V_homogenous(self): > V = self.V > return array((V.x,V.y,V.z,1.)) Thanks for the reply, and sorry for the various careless idiocies in my post. But your suggestion is exactly what I concluded to do in my own code until I thought I concluded - and this is the gist of my question - that even with the syntax you suggest I was making now 4 calls to the vector subtract calculation - one for V= self.V and one each time I called for an attribute of V. If I am wrong there - my problem essentially goes away. I was doing it in a context of my code where there are many interrelationships and I may have misintepreted what I was seeing. Are you in fact saying that your suggested solution avoids multiple calls to the calculation that determines the value of self.V? Art From raims at dot.com Sat Jul 20 11:13:11 2002 From: raims at dot.com (Rhymes) Date: Sat, 20 Jul 2002 17:13:11 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <1027175934.94979.0@iris.uk.clara.net> Message-ID: On 20 Jul 2002 14:51:33 GMT, Gerhard H?ring wrote: >python-dev archives (http://mail.python.org/pipermail/python-dev/). how much daily-traffic has this maillist? same as lkml or bugtraq's ? -- Rhymes rhymes at myself.com " ride or die " From ls2311 at netcom.com Mon Jul 22 11:37:01 2002 From: ls2311 at netcom.com (Lowel Stern) Date: Mon, 22 Jul 2002 08:37:01 -0700 Subject: Need some help please References: <2j2hju8c1btu76tu896cuc9qg6oeep9uoi@4ax.com> Message-ID: <4f9ojukhh753ku2eip6g9c6da8vikhta6n@4ax.com> On 21 Jul 2002 01:11:27 +0200, Chris Liechti wrote: >Arneau Starl wrote in >news:2j2hju8c1btu76tu896cuc9qg6oeep9uoi at 4ax.com: >... >> I cannot figure out a way to do the password >> without Expect (which I cannot install on that machine). Is there a >> way around this? > >you could modify /etc/passwd and /etc/shadow with your script. there is the >"crypt" module in the stdlib to encode passwords and return a string which >you can use. >i'm sure thats not the recomended way to do it. maybe someone else comes up >with a better solution. > >chris I needed to do this (run passwd command) from python also. This cannot work as you specified. You need to use expect or it won't work. LS From alberto at chiaroscuro.com Tue Jul 9 06:28:51 2002 From: alberto at chiaroscuro.com (Alberto Berti) Date: 09 Jul 2002 12:28:51 +0200 Subject: HTML to PDF converter? References: Message-ID: mmmm.... a basic one http://www.zope.org/Members/gaaros/ZpdfDocument it's not so zope centered... azazel From tim.one at comcast.net Thu Jul 11 05:33:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 11 Jul 2002 05:33:49 -0400 Subject: sorting many arrays from one... In-Reply-To: <2pWW8.51629$Jj7.1409458@news1.tin.it> Message-ID: [Alex Martelli] > ... > It so happens that Python list's sort method is the best-performing sort > I've ever seen deployed in production code for many special cases of > enormous practical importance See how calm my reply here is? Let this be a lasting retort to all who say I can't take criticism . > (lists that are close to being ordered Unfortunately, it's only some lists that are close to being ordered, although I believe it catches the most frequent real-life cases of that. "Close to being ordered" in general == few inversions, and that general criterion includes cases like [2, 1] + range(3, 1000000) That *could* be sorted with one swap and about a million compares to verify that the remainder is already sorted. list.sort() doesn't realize that, though. I hope to go back someday and generalize the special-casing to handle all few-inversion cases quickly; as-is, it only catches cases where few inversions follow a long prefix that's already sorted or reverse-sorted. Those seem to be most frequent in practice, although Aaron Watters made a strong argument for why general few-inversions cases are likely to arise in some computational geometry algorithms. But if I remembered his argument now, I would have presented it as my own instead of bothering to give him credit . there's-always-50-more-lines-to-write-and-70-to-throw-away-ly y'rs - tim From mgilfix at eecs.tufts.edu Thu Jul 25 09:32:31 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Thu, 25 Jul 2002 09:32:31 -0400 Subject: how to count lines in a file ? In-Reply-To: ; from tdelaney@avaya.com on Thu, Jul 25, 2002 at 10:21:18AM +1000 References: Message-ID: <20020725093231.A2011@eecs.tufts.edu> So, out of curiosity, if I define a metaclass on top of some file object, is this still considered broken code? Is the __del__ semantics meaningless? Would this object ever become part of garbage collection? class file: def __init__ (self, path): self.file = open (path) def __getattr__ (self, name): return getattr (self.file, name) def __setattr__ (self, name, value): return setattr (self, name, value) def __del__ (self): self.file.close () -- Mike On Thu, Jul 25 @ 10:21, Delaney, Timothy wrote: > Pay particular attention to the third paragraph below. The issue is not > whether such resources are closed when they are collected, but whether they > are collected at all. > > 3.1 Objects, values and types > > Objects are never explicitly destroyed; however, when they become > unreachable they may be garbage-collected. An implementation is allowed to > postpone garbage collection or omit it altogether -- it is a matter of > implementation quality how garbage collection is implemented, as long as no > objects are collected that are still reachable. (Implementation note: the > current implementation uses a reference-counting scheme with (optional) > delayed detection of cyclicly linked garbage, which collects most objects as > soon as they become unreachable, but is not guaranteed to collect garbage > containing circular references. See the Python Library Reference for > information on controlling the collection of cyclic garbage.) > > Note that the use of the implementation's tracing or debugging facilities > may keep objects alive that would normally be collectable. Also note that > catching an exception with a `try...except' statement may keep objects > alive. > > Some objects contain references to ``external'' resources such as open files > or windows. It is understood that these resources are freed when the object > is garbage-collected, but since garbage collection is not guaranteed to > happen, such objects also provide an explicit way to release the external > resource, usually a close() method. Programs are strongly recommended to > explicitly close such objects. The `try...finally' statement provides a > convenient way to do this. > > Tim Delaney > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (tdelaney) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From simon at uggs.demon.co.uk Wed Jul 10 16:32:44 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Wed, 10 Jul 2002 20:32:44 GMT Subject: Splitting a string every 'n' References: Message-ID: <3d2c99d8.47288747@news.dsl.pipex.com> On 9 Jul 2002 12:59:48 -0700, b_mcerlean at yahoo.com (Brian McErlean) wrote: >Simon.Foster at smiths-aerospace.com wrote in message news:... >> What is the idiomatic way to split a string into a list >> containing 'n' character substrings? I normally do >> something like: >> >> while strng: >> substring = strng[:n] >> strng = strng[n:] >> >> >> But the performance of this is hopeless for very long strings! >> Presumable because there's too much list reallocation? Can't Python >> just optimise this by shuffling the start of the list forward? >> >> Any better ideas, short of manually indexing through? Is there >> something like: >> >> for substring in strng.nsplit(): >> > >I have a handy class I use for things like this: > > >class Group: > def __init__(self, l, size): > self.size=size > self.l = l > > def __getitem__(self, group): > idx = group * self.size > if idx > len(self.l): > raise IndexError("Out of range") > return self.l[idx:idx+self.size] > >I use it mainly for grouping things like: >for x,y in Group([1,2,3,4,5,6,7,8,...],2): > process_coords(x,y) >but its also applicable to your problem, and works neatly with >strings. > >try: > >for substring in Group(string, n): > > >Don't you just love python's polymorphism! > >You don't state what you want to do if the string isn't a multiple of >N characters. This version includes the shorter string at the end. > >Brian. That's what I wanted! -- Simon Foster Cheltenham England From BPettersen at NAREX.com Tue Jul 9 15:20:07 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 9 Jul 2002 13:20:07 -0600 Subject: Why self? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158F27@admin56.narex.com> > From: Charles Hixson [mailto:charleshixsn at earthlink.net] > > If you are subclassing a class that someone else has written, > you don't > want to accidentally redefine an internal name. Sorry. I can accept > that you should be able to explicitly access it, but to be able to > change it by accident is (would be?) a misfeature. > > I didn't believe that this happened in Python. It does, and > it seems a > significant flaw. My understanding is that if you define a > variable in > a class that subclasses another class, then unless you take definite > steps to cause things to happen otherwise, you are defining a new > variable that is local to the scope of the class that you are > currently > defining, and will not impact routines that you call from parental > classes. Experiment shows that this isn't what happens. > from __future__ import nested_scopes > does not fix this problem, as I assumed that it would. > > Let's be explict: > from __future__ import nested_scopes > class A: > def ma(self): > print "ma, ma" > def pa(self): > self.ma() > class B(A): > def ma(): > print "hello, world" > tst = B() > tst.pa() > [snip] You may have a point, but your example doesn't show it. It is generally seen as one of the bedrocks of OO programming that you should be able to redefine a method in a subclass for more specific behavior. In C++ this is spelled virtual. Whether the same is true of attributes is something I'll let other people worry about... -- bjorn From jonathan at onegoodidea.com Mon Jul 22 05:16:09 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 22 Jul 2002 10:16:09 +0100 Subject: how to ask for class attribute? References: <3D3BC0F8.4648E69A@ipm.fhg.de> Message-ID: On 22/7/2002 9:23, in article 3D3BC0F8.4648E69A at ipm.fhg.de, "Markus von Ehr" wrote: > my class has several attributes self.* > In one method I have to detect if there is > already an attribute self.start_value > How can I detect, if the attribute already exists? Something like this should do the trick: >>> class Foo: ... def hasfoo( self ): ... if hasattr(self, 'foo'): ... print 'yes' ... else: ... print 'no' ... >>> f = Foo() >>> f.hasfoo() no >>> f.foo = 5 >>> f.hasfoo() yes >>> This will be fooled by class attributes or inherited attributes though. If you want to determine if 'foo' is an actual instance variable then you can use: if name in self.__dict__: ... Jonathan From hsfrey at earthlink.net Tue Jul 2 20:53:35 2002 From: hsfrey at earthlink.net (Harvey Frey) Date: Tue, 2 Jul 2002 17:53:35 -0700 Subject: GoTo considered missing Message-ID: <002901c2222c$100a2180$289dfea9@t9k2t3> OK. I'm a spaghetti-coder from way back, new to Python. I didn't even realize there was no "goto" till I tried to rewrite a big C program in Python. Breaks and Continues are fine for single loops, but: What is the approved Python method for getting from the bottom of a set of nested loops to the top? Maybe I could rewrite the big loop with function calls, but I'd be knee-deep in recursion. Harvey ========================= Harvey S. Frey MD PhD Esq. hsfrey at harp.org www.harp.org C'est Vrai. C'est Frey! ========================= From petrk at pochtamt.ru Fri Jul 19 07:12:34 2002 From: petrk at pochtamt.ru (Petr Klyushkin) Date: 19 Jul 2002 15:12:34 +0400 Subject: __del__ in classes derived from Tkinter classes References: Message-ID: Hello, Fredrik! >>>>> "Fredrik" == Fredrik Lundh writes: Fredrik> Petr Klyushkin wrote >> I'm a Python and Tkinter newbie. I've noticed that __del__ >> methods of my classes derived from Tkinter classes are never >> called. Is this normal behavior, or I am doing something wrong? [...] Fredrik> tkinter maintains an internal widget tree. if you want to Fredrik> print "hey" when your toplevel widget is destroyed, over- Fredrik> ride the "destroy" method: [...] So, when will Python object be destroyed? Suppose, I have following code: def f(): test2 = Test() f() When will test2 (Python object! not a Tk widget it represents) be destroyed? Fredrik> (and using __del__ is usually bad style even outside Fredrik> Tkinter, but that's another story). Why? -- C'ya, Peter. --=[petrk at pochtamt.ru]=--=[http://petrk.pochtamt.ru]=-- --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=-- From Chris.Barker at noaa.gov Thu Jul 18 12:39:59 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 18 Jul 2002 09:39:59 -0700 Subject: Sharp Zaurus References: <1026919964.826307@irys.nyx.net> Message-ID: <3D36EF5E.1C3EDF1B@noaa.gov> sarayu balu wrote: > Is there any Python, more appropriately Jython, The Zuarus is based on QT-embedded (or whatever they are calling it), so CPython and PyQT couldbe an opiton too, if someone wants to do the port. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From shagshag13 at yahoo.fr Tue Jul 9 10:25:51 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 16:25:51 +0200 Subject: sorting many arrays from one... References: Message-ID: "Alex Martelli" > I'm not sure how that would save you any storage at all. Since the > strings DO need to be stored somewhere anyway, what's saved by using > their id's rather than just references to them, as Python usually does? i should have write that i use the same string many times in many files, so i only use its id which is always shorter than my strings and save storage. And i was wondering if there was a better/efficient way to handle id-string mapping. > > and again great thanks for all your advices / replies... > You're welcome! so just thanks, s13. From hbbizp at lasaa.com Thu Jul 18 09:41:42 2002 From: hbbizp at lasaa.com (hbbizp at lasaa.com) Date: Thu, 18 Jul 2002 13:41:42 +0000 (UTC) Subject: Fight a evil in Portugal Message-ID: <1026999663.159168@spynews3> =================================================== VEJA O SITE PARA MAIS INFO: http://www.acc11.cjb.net/ =================================================== (SITE SOBRE CRIMES) OPINI?O PROFISSIONAL DE UM PSICOLOGO CERTIFICADO SOBRE A VERDADEIRA PERSONALIDADE DE L|E|O|N|A|R|D|O P|A|R|E|D|E|S ====== N?o conhe?o o sr. l_e_o_n_a_r_d_o e como tal n?o me posso pronunciar, mas a decri??o que ? feita, corresponde a uma perturba??o de personalidade (vulgo "psicopatia") chamada de narcisismo, ou aquilo a que Kernberg chamaria de "personaliade narcisista maligna". Estas pessoas consideram-se o centro do mundo, acham-se merecedoras de tudo, que tudo o que os outros fazem se deve a eles, elogiam e bajulam as pessoas como forma de as seduzir, mas seguidamente insultam-nas e criticam-nas pelas costas como forma de demonstrarem superioridade; aqueles que se deixam manipular e enganar s?o elogiados como pessoas "bestiais", mas depressa passam a "bestas" quando se atrevem a dizer a verdade e a queixarem-se dos problemas. Quando a auto-imagem de perfei??o que o narcisista tem, ? colocada em causa, ele pode inclusivamente psicotizar, isto ?, perder a no??o da realidade, e amea?ar as pessoas de morte, ou que ir? destruir as suas carreiras, chegando mesmo a acreditar que a critica ? infundada e motivada por uma conspira??o de invejosos... tratamento? Psicoterapia! Muita! Mas estas pessoas s? come?am a encarar esta hipotese quando chegam aos 40-50 e come?am a ver que, afinal, apesar de tanta megalomania nunca passaram da cepa torta... ====== Pelo que se pode ver pela descri??o feita, essa "pessoa" ? um criminoso psicopata que precisa de ser detido, seja na pris?o ou no J?lio de MAtos (Hospital dos doentes mentais). Vamos ajudar a que isso aconte?a, para tal fa?a o seguinte: Enviar - emails para info at advanced-reality.pt Telefonar - (213520871 - 213549523 - 938406012) Enviar - sms (938 406 012) Enviar - faxes (213520870) ====================== http://www.acc11.cjb.net/ ====================== Obrigado a todos pela vossa preciosa ajuda face ?s injusti?as :) liddty From jdhunter at nitace.bsd.uchicago.edu Sun Jul 28 21:11:19 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sun, 28 Jul 2002 20:11:19 -0500 Subject: Where to find freeze References: Message-ID: >>>>> "Ali" == Ali K writes: Ali> I would like to know where to find the freeze utitly or any Ali> other utility for making exe files. If you look in the src dir of your python distribution, it will be in the Tools/freeze subdir. See the README in that subdir for more info. You may also be interested py2exe: in http://starship.python.net/crew/theller/py2exe John Hunter From jdhunter at nitace.bsd.uchicago.edu Fri Jul 26 12:54:35 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 26 Jul 2002 11:54:35 -0500 Subject: Derivative of string as a name of list or dictionary (or class?) References: <82fe0bb.0207260749.3059e20a@posting.google.com> Message-ID: >>>>> "Alex" == Alex Martelli writes: Alex> Sure, but the frown is first of all against the very task Alex> that the OP wants to perform: setting arbitrary names in the Alex> global space. Alex> What if one of the name is 'print'? Boom. Python has a Alex> couple of dozen keywords -- what ensures against attempts to Alex> redefine one? While I agree whole heartedly that it's best to do this on attributes of a class, what do you think of the following approach to manipulating globals, which I discovered doing a little more reading on this issue in the c.l.python archives. name = 'seq' val = ['John', 'Hunter', 'was', 'here'] globals()[name] = val print seq globals()['print'] = 'Clobber?' print seq #no clobber John Hunter From aleax at aleax.it Tue Jul 9 03:49:04 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 07:49:04 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2A2586.5070302@ob_scure.dk> <4QuW8.46343$Jj7.1305133@news1.tin.it> <7xd6txwhu6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Alex Martelli writes: >> > I'm a little scared though about using SQL too extensivly. >> >> Joe Celko's "SQL for Smarties" might be just what you need to move you >> to the next level of SQL usage (or, to turn you off it for life, >> depending:-). > > Philip Greenspun's SQL for Web Nerds > > http://philip.greenspun.com/sql/index.html > > is pretty good (at least for non-SQL-whizzes like me) and has a > reasonable amount of info on performance tuning and optimization. Indeed, a fast scan seems to show that Philip's coverage is quite different from Joe's -- Joe talks about SQL (lots of SQL, very advanced SQL, SQL to do things you wouldn't think could be done in SQL [and maybe in some cases shouldn't!-)]), while Philip does a reasonably wide-ranging survey of Oracle issues, including the very best piece of advice of them all -- *hire an expert*. There's a think3 application that uses a RDBMS and supports many different RDBMS brands. Towards the end of my long stay in think3, most substantial installations of this application were being deployed on either MS SQL Server, or Oracle. It seems the customers using MS SQL Server were more or less "OK, not happy, but OK" with our performance. OTOH, the customers using Oracle tended to fall in two widely separated camps -- a group perfectly happy with our performance, a group deeply dissatisfied with it. Funny -- why...? Solution: MS SQL Server ain't all that tunable -- it gives you reasonable performance if you program and administer it reasonably, and that's about it... no superb performance, no horrors either. Oracle, OTOH, _is_ very highly tunable, and *demands* such kind of tuning -- if you give it proper care and feeding you get stellar performance and scalability, otherwise it can truly be the pits. The happy Oracle-using customers were large firms who had hired (or home-grown) full-time experts at Oracle tuning, working full time to keep the datases humming, including those used by our application. The unhappy ones were mostly small and middling firms who _thought_ they could just buy Oracle, perhaps pay for a once-off installation / tuning / training for low-skilled or overworked/wide-responsibility sysadm staff, and forget it. Wrong. Very wrong. If you can afford Oracle, you can afford to hire (or at least regularly retain a freelance) expert help to tune it, keep it tuned, make it perform to its potential. If you can't, you may be better off with cheaper stuff (not necessarily MS SQL Server, which has the big minus of constraining you to wimpy Windows servers, but, say, SAP/DB, nee Adabas -- free, and there's a lot of expertise around for it from the times when it was a costly, enterprise-grade commercial RDBMS). Disclaimer: this is basically hearsay -- I couldn't tune an Oracle DB myself any more than I could tune a fish -- AND it may be based on now-obsolete versions of the products named (for all I _know_, the Oracle you can buy today is self-tuning, and/or the MS SQL Server you can buy today requires half a dozen full-time staff with degrees in nuclear engineering -- I just find such hypotheses unlikely:-). Alex From mwh at python.net Fri Jul 19 05:09:45 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 19 Jul 2002 09:09:45 GMT Subject: raw_input References: <3D36C5F1.9C966A8F@millfilm.co.uk> Message-ID: Eric Texier writes: > It's there anything better than raw_input to query a string > input from the user in a console window. My pyrepl package: http://starship.python.net/crew/mwh/hacks/pyrepl.html ? Probably overkill. Cheers, M. -- Remember - if all you have is an axe, every problem looks like hours of fun. -- Frossie -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From wyojustin at hotmail.com Mon Jul 15 18:55:47 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Mon, 15 Jul 2002 22:55:47 GMT Subject: Tkinter.create_dot() Message-ID: I'm using a Tkinter.Canvas to create a picture of thousands of dots. I am using Tkinter.Canvas.create_line() with a line of length one for each dot which really seems to bog down the computer. Is there a better way? Thanks, Justin Shaw From tilah78 at hotmail.com Fri Jul 19 15:10:42 2002 From: tilah78 at hotmail.com (Rafael Garci­a) Date: Fri, 19 Jul 2002 15:10:42 Subject: stop running script at any momment Message-ID: Hello. How can I stop/pause a running script at any momment (for example when user clicks on a button)from the Python/C API? I use the function PyRun_SimpleFile(...) to run a script file. Thanks for your attention, Rafael Garcia, tilah78 at hotmail.com From mertz at gnosis.cx Wed Jul 10 18:52:18 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Wed, 10 Jul 2002 18:52:18 -0400 Subject: Open document formats References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: |See, this is something I really don't understand. I will agree that PDF |or html would have been a better choice, but not everyone can generate |PDF ya know. With this kind of attitude, we'll forever be regarded as |the extremists who won't listen to anything .... Who on earth cannot generate PDF?! As far as I know, every OS, since maybe 1985, has had drivers for postscript printing. Almost all the applications that do not use OS drivers also support postscript. That's probably enough right there to address the need for open format... no one here would complain about documents made available as .ps (or better still, .ps.gz). However, PDF does have some advantages over PS. One might use ps2pdf or Ghostscript to perform the ps->pdf conversion, if that is desired. The commercial Adobe Acrobat program will also output directly to PDF. These tools are freely available to users of just about every platform, usually in either source or pre-compiled versions. Now if the question is "who is TOO LAZY to generate PDF?"... maybe the answer is different. -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From anton.wilson at camotion.com Tue Jul 9 09:52:59 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 9 Jul 2002 09:52:59 -0400 Subject: Multi-threading on Multi-CPU machines In-Reply-To: References: Message-ID: <200207091355.JAA09603@test-area.com> > With a multithreaded approach you might keep the array in memory > and have the main thread farm out work requests to worker threads > via a bounded queue. You want the queue a bit larger than the > number of worker threads, and you can determine the optimal size > for a work request (could be one item, or maybe two, or, say, 4) > via some benchmarking. Upon receiving a work request from the > Queue, a worker thread would: > -- get a local copy of the relevant points from the > large array, > -- enter the C-coded computation function which > -- releases the GIL, > -- does the computations getting the nes points, > -- acquires the GIL again, If the bounded queue were declared in a C extention module, would a thread doing the calculations really have to reaquire the GIL everytime that thread accessed this C data structure? Could mutexes be used instead? > -- put back the resulting new points to the same area > of the large array where the input came from, > then go back to peel one more work request from the Queue. From jdhunter at nitace.bsd.uchicago.edu Mon Jul 22 10:29:50 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 22 Jul 2002 09:29:50 -0500 Subject: how to delete or change... References: Message-ID: >>>>> "Shagshag13" == Shagshag13 writes: Shagshag13> hello, i'm looking for the easiest way to delete or Shagshag13> change last n character(s) of a text file. Shagshag13> (i must avoid using a temp file - i had many huge Shagshag13> files not enough place left, and can buy new hdd ;o) There are some unknown's here that would be helpful to know. You say it's a text file but then talk about opening in binary. Is it ASCII? How large all the files? Is it feasible for you to work in memory? If so, something like import string fname = 'somefile.dat' str = open(fname, 'r').read() seq = map(None, str) #convert the string to a list seq[-4:] = map(None, 'John') #replace the last 4 chars with 'John' h = open(fname, 'w') h.write(string.join(seq, "")) should work for you. Also, you say when you tried the binary seek you got an I/O error. Was there anything informative about that error that you can post? Cheers, John Hunter From nhodgson at bigpond.net.au Fri Jul 12 20:01:52 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 13 Jul 2002 00:01:52 GMT Subject: pyCard_turtleTimes References: Message-ID: Cousin Stanley: > I'd be interested to know how other machines/platforms compare > for the ones that take the longest here ... ChaosScript2and3 ..... 157 hopalong ...................... 554 madness ...................... 482 Its not a simple multiplier on your results, possibly due to different CPU:Video performance ratios on the two machines. I see a lot of variation in times with subsequent runs of ChaosScript2and3 taking 117 and 184 seconds. Cheap locally assembled box Processor ... AMD Athlon 600 Memory ...... 384 MB Video ........... NVIDIA RIVA TNT2 64 Software Window 2000 Python 2.2 Mmm, performance of these applications is so central to my efficiency that I must buy a better machine ;-) Neil From Lutz.Schroeer at kybernetik-manufaktur.de Fri Jul 26 16:08:59 2002 From: Lutz.Schroeer at kybernetik-manufaktur.de (Lutz Schroeer) Date: 26 Jul 2002 20:08:59 GMT Subject: DMOZ query? Message-ID: Hi, after looking through google groups, I found that the last answer to the question "How to query DMOZ.ORG without downloading the large RDF files?" is about one year ago. Did anybody write a module for this during this period or should my plans for this weekend include some DMOZ HTML parser programming? Lutz From dyoo at hkn.eecs.berkeley.edu Wed Jul 10 04:07:25 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 10 Jul 2002 08:07:25 +0000 (UTC) Subject: Learning how to program... but what's the best way? References: <3D2BB54C.90500@earthlink.net> Message-ID: Hans Nowak wrote: : The problem is, I don't expect my student to swoon over "hello world", or to : get excited about doing basic mathemathical computations. Nor will standard : computer science stuff about bits, bytes, hexadecimal numbers etc be appealing. : Sure, those concepts are important, and will be dealt with in due time, but : what I'm looking for right now is a way to capture people's interest-- to do : something funny, or cool, or useful even for someone who doesn't know programming. Hi Hans, You may be interested in the Livewires project: http://livewires.org.uk/python They have some PDF worksheets on learning Python through games, and they look very interesting: one of the last projects is programming Spacewar! Best of wishes to you! From cartermark46 at ukmail.com Fri Jul 19 05:19:34 2002 From: cartermark46 at ukmail.com (Mark Carter) Date: 19 Jul 2002 02:19:34 -0700 Subject: Do GUIs for DBs exist? References: Message-ID: > Isn't the main point of Access was it's relatively easy to combine its > SQL engine with forms and that it includes the development environment > to do so? > > Is that what you were referring to Yes. From cliechti at gmx.net Mon Jul 15 13:51:39 2002 From: cliechti at gmx.net (Chris Liechti) Date: 15 Jul 2002 19:51:39 +0200 Subject: Serial Port Returning Garbage. Why? References: Message-ID: mlai at intrinsyc.com (max) wrote in news:f128688f.0207150939.1af19401 at posting.google.com: > I need some help. many people who post here do ;-) > I've been trying to establish a bi-directional serial communications > link between two microprocessors with a python script. The link is > used by a 'master' processor to transmit commands to a 'slave' > processor, while also allowing the 'slave' to return any output back > to the 'master' for analysis. The information garnered from the > 'slave' is used to determine subsequent actions. ... > Anyway, I'm using the os module's functions to read and write to the > serial port, and i'm using os.system to invoke the stty program to set > the properties of the serial port connection. The reason for using > stty is because the termios and fcntl modules aren't available for > use. >... > Knowing all of this, does anyone know what could be causing the output > to become garbled? maybe your port is not configured to transmit binary data. usualy the linux drivers interpret the characters and provide line editing etc, like in a console. my module uses the termios and fnctl module, but you might get some ideas on how to configure your port: http://pyserial.sf.net chris -- Chris From phr-n2002b at NOSPAMnightsong.com Tue Jul 23 16:38:55 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 23 Jul 2002 13:38:55 -0700 Subject: Mastering Regular Expressions 2nd Ed. References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> Message-ID: <7xn0si9o2o.fsf@ruckus.brouhaha.com> Tim Roberts writes: > The multi-thousand byte full expression to match a valid RFC822 e-mail > address was practically worth the price all by itself! Argggh! That sounds like regular expressions aren't really the best way to match RFC822 addresses. From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 21:48:48 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 22 Jul 2002 18:48:48 -0700 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> <7x7kjne14g.fsf@ruckus.brouhaha.com> Message-ID: <7xsn2bjjsv.fsf@ruckus.brouhaha.com> Chris Liechti writes: > if a __call__ feature was added, it would of course only work in newer > versions of python. so every code that uses this not backwards compatible. Every time a new feature is added to Python, it generally isn't backwards compatible. Maybe module.__call__ isn't important, but feature X is important. That means if feature X and module.__call__ both get added to some future Python version, and your program needs feature X, it might as well also use module.__call__. From markus.vonehr at ipm.fhg.de Thu Jul 4 10:58:46 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 04 Jul 2002 16:58:46 +0200 Subject: TkInter and pygame? Message-ID: <3D2462A6.B1BB696D@ipm.fhg.de> Hi, is there a possibility to mix TkInter windows with pygame sprites for example? (in one application) Thanks for any comments, Markus From mfranklin1 at gatwick.westerngeco.slb.com Tue Jul 16 10:39:00 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 16 Jul 2002 14:39:00 +0000 Subject: Tkinter.create_dot() In-Reply-To: References: Message-ID: <200207161342.g6GDgf728898@helios.gatwick.geco-prakla.slb.com> On Monday 15 Jul 2002 10:55 pm, Justin Shaw wrote: > I'm using a Tkinter.Canvas to create a picture of thousands of dots. I am > using > Tkinter.Canvas.create_line() > with a line of length one for each dot which really seems to bog down the > computer. > > Is there a better way? Not really but you could use a PhotoImage like so:- from Tkinter import * root=Tk() canvas=Canvas(root) canvas.pack() pxmap=PhotoImage(width=10, height=10) for x in range(10): for y in range(10): pxmap.put('red', (x, y)) canvas.create_image(10, 10, image=pxmap) root.mainloop() This will create a red square at 10, 10 in the canvas. Cheers Martin From j_r_ashley at MAKGifts.com Thu Jul 25 01:44:36 2002 From: j_r_ashley at MAKGifts.com (James Ashley) Date: Thu, 25 Jul 2002 05:44:36 GMT Subject: A better self References: Message-ID: In article , Bengt Richter wrote: > On Wed, 24 Jul 2002 08:34:33 GMT, Alex Martelli wrote: >>should coding in lower levels be considered (on the other >>hand, protectionist legislation shouldn't be considered even then, >>but that's another issue:-). >> > What are you protecting with that "shouldn't"? ;-) Perhaps that was a "generally, any sane person won't, but sometimes bueracracies insist upon insanity" kind of generalization? > > ISTM everyone believes in protectionism, only differing in their > ideas of what to protect and how to do it ;-) ROFL...nicely said. I've thought up a few responses to this, and I'm curious about your answer to them all, but they all seem to whirl around politics rather than software development, and, therefore, are even more off-topic than I'm willing to get on this sort of forum. Regards, James From dswegen at software.plasmon.com Thu Jul 4 11:11:16 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Thu, 4 Jul 2002 16:11:16 +0100 Subject: OpenOffice Python Bindings In-Reply-To: <200207041457.00217.b.maryniuk@forbis.lt> References: <200207041457.00217.b.maryniuk@forbis.lt> Message-ID: <20020704151116.GA27256@software.plasmon> On Thu, Jul 04, 2002 at 02:57:00PM +0200, Bo M. Maryniuck wrote: > Hello, all. > Somebody something heard sbout this (Python Bindings for OpenOffice)? > If yes, please link me there at least... Google search: "python openoffice bindings" First result, in the links section. Cheers Dave From alex.tournier at iwr.uni-heidelberg.de Tue Jul 9 09:08:29 2002 From: alex.tournier at iwr.uni-heidelberg.de (Alex Tournier) Date: 9 Jul 2002 06:08:29 -0700 Subject: leastSquaresFit Message-ID: Here's a question/problem with the leastSquaresFit function which is part of Numeric module.Hope you can help, I try the example given in the documentation and here is what i get: >>> from Scientific.Functions.LeastSquares import leastSquaresFit >>> import Numeric >>> >>> # The mathematical model. ... def exponential(parameters, x): ... a = parameters[0] ... b = parameters[1] ... return a*Numeric.exp(-b/x) ... >>> # The data to be fitted to. ... data = [(100, 4.999e-8), ... (200, 5.307e+2), ... (300, 1.289e+6), ... (400, 6.559e+7)] >>> >>> fit = leastSquaresFit(exponential, (1e13, 4700), data) Traceback (innermost last): File "", line 1, in ? File "/usr/lib/python1.5/site-packages/Scientific/Functions/LeastSquares.py", line 66, in leastSquaresFit -0.5*Numeric.array(chi_sq[1])) File "/usr/lib/python1.5/site-packages/Numeric/LinearAlgebra.py", line 61, in solve_linear_equations _assertRank2(a, b) File "/usr/lib/python1.5/site-packages/Numeric/LinearAlgebra.py", line 47, in _assertRank2 raise LinAlgError, 'Array must be two-dimensional' LinearAlgebraError: Array must be two-dimensional Anybody have an idea were this might come from, I use the Numeric module all the time without any prob, but I can't get this leastSquaresFit function to work!! Cheers, Alex From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 16:24:54 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 15:24:54 -0500 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: >>>>> "Mack" == Mack writes: Mack> Thanks. I just checked out the doc Whats new in 2.0 and Mack> found it. I didn't think my redhat 7.1 was that old. I'll Mack> just upgrade then. It's not, but redhat uses python for a lot of things (like their installer) and I think they have been reluctant to upgrade for fear of "if it ain't broke, ...". But if I recall correctly, you can also install 2.1 from the 7.1 RPMs cd. But I'm not sure. JDH From newfroups at jerf.org Fri Jul 12 10:55:12 2002 From: newfroups at jerf.org (Jeremy Bowers) Date: Fri, 12 Jul 2002 14:55:12 GMT Subject: Python to XML to Python conversion References: <3D2E1793.8030600@jerf.org> Message-ID: <3D2EBECF.4060907@jerf.org> Alex Martelli wrote: > Jeremy Bowers wrote: > ... > >>the choice of *last* resort, when you absolutely *need* easy parsing in >>multiple languages or environments and can't get it any other way. It is > > > I think this assertion, as it stands, is untenable. There just about > IS *some* other way -- e.g., inventing your own little language for > data description and writing from scratch the needed parsers in all > languages and environments of interest. That's order N effort rather then constant effort, thus that's not easy parsing in other environments, that's the virtually impossible job we were faced with 10 years ago. (SGML wasn't all that easy either, from what I gather.) > Are you SERIOUSLY claiming that such reiterated reinventions of the > wheel -- which were a good part of the data interchange "state of the > art" before XML appeared -- should be used in preference to XML?! No. This it rather negates the rest of your message, since it seems to be based on my making that non-claim. From tim.one at comcast.net Thu Jul 4 16:54:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 04 Jul 2002 16:54:49 -0400 Subject: replacing instance __setattr__ In-Reply-To: Message-ID: [Robin Becker] > that's my confusion. Also as you point out I seem to think that methods > are data attributes which are callable, obviously my failure again. The notion that data attributes are attached to instances while methods are attached to classes isn't unique to Python. Most Python programmers don't have to worry about the distinction, but if you're doing metaprogramming or introspection tricks, then you have to learn how the language actually works. > I obviously come from a more dynamic direction all these distinctions > seem pretty arcane and silly to tcler's, lispers, gpmers etc. Tcl isn't an OO language so I don't see its relevance. I don't know what gpmers refers to. WRT Lisp I can't guess whether you have CL's CLOS in mind or some other Lisp's OO package. They all have their own quirks, although AFAIK a distinction between classes and instances is made by all OO languages except the handful of prototype-based languages. From cbbrowne at acm.org Sat Jul 13 21:46:05 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 14 Jul 2002 01:46:05 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <7x65zj60ku.fsf@ruckus.brouhaha.com> Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard) wrote: > [Christopher Browne] >> Yacc and Lex provide nice formal ways to describe grammars, can work with >> the "Langues-du-jour," and it would be very instructive to see that they >> _are_ usable for building parsers for small languages. > > Python users are blessed with many lexers/parsers systems. Even if > I glanced around, I surely do not know them all. My favorite so far is > SPARK, which is not only very elegant, but also quite simple to use and > powerful at what it can recognise. I also learned to like PLY. Fair enough... I'm pointing at Lex/Yacc since they provide _declarative_ ways of describing grammars, which is commonly not what scripting language schemes use. (I'm afraid I'm not familiar with SPARK/PLY; perhaps they are different?) In addition, Lex/Yacc are commonly what are used to _build_ the scripting language grammar, so they probably are hiding around somewhere anyways :-). Furthermore, what I'm trying to have as an underlying "theme" in the "music" is that it might very well be easier to build a Lex/Yacc grammar using C and link it in than to fight your way through designing the XML-based system. There may be more "elegant" options than Lex/Yacc; the underlying theme is that that doesn't prevent the "design-the-grammar-from-scratch" approach from being more manageable than XML. -- (reverse (concatenate 'string "gro.gultn@" "enworbbc")) http://cbbrowne.com/info/spreadsheets.html Why are there flotation devices under plane seats instead of parachutes? From opengeometry at NOSPAM.yahoo.ca Fri Jul 19 04:02:37 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 19 Jul 2002 08:02:37 GMT Subject: Recursion References: Message-ID: Abhijit Soman wrote: > In the recursive function below i want to add the individual bits to a > string and return that string to the caller > Can anyone tell me how to do that > > > def showbits(x): > if x != 1: > showbits(x >> 1) > if x & 01: > print 1, > else: > print 0, You forgot to return string '1' or '0', and then append to output. Try def showbits(x): if x == 0: return '' if x & 1: return showbits(x>>1) + '1' else: return showbits(x>>1) + '0' -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From chris.lyon at spritenote.co.uk Tue Jul 2 05:51:49 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Tue, 2 Jul 2002 10:51:49 +0100 Subject: Simple Conceptual Pickling problems Message-ID: <3d217732$0$4276$afc38c87@news.easynet.co.uk> I am trying to pickle instances of a class stored in a dictionary with a MD5 hash used as the key of the dictionary. I can pickle them ok and when I examine the pickle file (I'm using the default ASCII mode) I can see the instance data in the pickle file. However when I try to load the pickle file After I have imported the module from which it was all derived I get:- SystemError: Failed to import class Programme from module __main__ now Programme is a top level class defined in the file I have imported before I have opened the pickle file. So why can't doesn't this work? I fell it's important I understand this as conceptually I've obviously got the wrong idea of what I'm doing. Chris From wdraxinger at darkstargames.de Tue Jul 16 12:50:35 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Tue, 16 Jul 2002 18:50:35 +0200 Subject: Being a bit confused after hacking Python References: <3D343DA7.6010309@darkstargames.de> <3D34499C.1040300@shinners.org> Message-ID: <3D344EDB.1080904@darkstargames.de> Pete Shinners wrote: > as for reloading sys resetting stdout, why do you ever need to reload > it? if you just want to reset the stdout variables, just set sys.stdout > to sys.__stdout__. the __stdout__ is the "original" stdout object. No, the reloas is not a real problem, since the engine internally redirects the stdlib file pointers stdin and stdout to a internal pipe, so I still get the output. I expected that behaviour and wondered if I could bypass it, so hacked the pythoncore sources and found that somehow PyImport_ReloadModule() is reloading sys somehow, but I didn't found out how it does this. It more a question out of interest. If I'd really need certain builtin modules in a specific state after a reload I'd just hook that to and watch for these modules reloaded to change them thereafter back to my engine's stuff. -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From phr-n2002b at NOSPAMnightsong.com Wed Jul 10 03:55:30 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 10 Jul 2002 00:55:30 -0700 Subject: try/finally question Message-ID: <7xd6twow3x.fsf_-_@ruckus.brouhaha.com> Is there a reasonable way to skip around a "finally" clause? E.g, suppose I have a simple "db" (database) object that supports these operations: db.begin() # begin a transaction (locks the database) db.do_action() # update some record or whatever db.commit() # commit the actions and close the transaction db.cancel() # discard the actions and close the transaction db.commit() and db.cancel() both release the lock of course. Also, doing db.cancel() with no transaction open is a no-op. So the obvious way to use it is: try: db.begin() x = db.do_action(first_thing) y = db.do_action(second_thing) db.commit() finally: db.cancel() The trouble is db.cancel() is an ordinary method call--it's not atomic in the interpreter. It can be interrupted and blast out of the finally block before finishing, and then control returns to some higher level with the database still locked. In a C program I'd use sigsetmask to turn off interrupts during the critical section, but Python doesn't have that. All I can think of are yet more try/finally blocks, which is ugly and which still might not close all the gaps. In particular, I don't know whether calling a method from a finally block is guaranteed to execute the first Python statement in the method, if an interrupt comes at that exact instant. What's the right way to handle this? Thanks. From jennifer.lee at nre.vic.gov.au Wed Jul 17 02:25:35 2002 From: jennifer.lee at nre.vic.gov.au (Jen) Date: 16 Jul 2002 23:25:35 -0700 Subject: Using search fields on websites Message-ID: Hi All, I'm trying to use python to do searches on a website by entering a string into a search field to search against the website's database. Currently I have a list of strings which I want to automate to enter each into a textfield on a website, select a different radio button from the default and submit for searching. Is there a way that I can do this easily? If anyone could suggest not only the modules to use but also any possible functions within the modules, that would be greatly appreciated. Thanks. Jen From cliechti at gmx.net Tue Jul 2 21:48:21 2002 From: cliechti at gmx.net (Chris Liechti) Date: 3 Jul 2002 03:48:21 +0200 Subject: GoTo considered missing References: Message-ID: "Harvey Frey" wrote in news:mailman.1025657644.14273.python-list at python.org: > OK. I'm a spaghetti-coder from way back, new to Python. > I didn't even realize there was no "goto" till I tried to rewrite a > big C program in Python. > > Breaks and Continues are fine for single loops, but: > What is the approved Python method for getting from the bottom of a > set of nested loops to the top? you can do that nicely with exceptions: class AbortLoop(Exception): pass try: while 1: for i in range(99): if i == 57: raise AbortLoop except AbortLoop: pass chris -- Chris From markus.vonehr at ipm.fhg.de Tue Jul 16 02:48:43 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 16 Jul 2002 08:48:43 +0200 Subject: Tkinter.create_dot() References: Message-ID: <3D33C1CB.8D35250D@ipm.fhg.de> -use the Python Imaging Library (PIL) to create an Image with all your dots and information you need -put the Image in the Tkinter canvas Markus imports you need: Image, ImageTk, Tkinter im = Image.new("I", (Width, Height)) # construct your Image like you want here photoimage = ImageTk.PhotoImage(im) canvas.create_image(0, 0, anchor=NW, image=photoimage) Justin Shaw schrieb: > > I'm using a Tkinter.Canvas to create a picture of thousands of dots. I am > using > Tkinter.Canvas.create_line() > with a line of length one for each dot which really seems to bog down the > computer. > > Is there a better way? > > Thanks, > Justin Shaw From tdelaney at avaya.com Thu Jul 25 23:10:47 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 26 Jul 2002 13:10:47 +1000 Subject: str() inconsistency Message-ID: > From: Mike Rovner [mailto:mike at bindkey.com] > > Why it's not a bug: > > >>> 4.4 > 4.4000000000000004 > >>> `4.4` > '4.4000000000000004' > >>> str(4.4) > '4.4' > >>> str([4.4]) > '[4.4000000000000004]' > > IMHO, str() shall call str, not repr on complex objects. http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp Tim Delaney From unlearned at DELETETHIS.learn2think.org Mon Jul 29 15:39:46 2002 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Mon, 29 Jul 2002 13:39:46 -0600 Subject: decoding XML-ified special chars such as " References: Message-ID: <3d459a01$1_2@hpb10302.boi.hp.com> Does the entitydefs dict in the standard htmlentitydefs module help you out? -- Daniel Fackrell (unlearned at learn2think.org) When we attempt the impossible, we can experience true growth. > "Gabe Newcomb" wrote in message news:mailman.1027968580.20805.python-list at python.org... > > Is there a module to take strings such as ", & and turn them into the characters they normally represent (', &)? From eddie at holyrood.ed.ac.uk Wed Jul 24 11:09:48 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 24 Jul 2002 15:09:48 +0000 (UTC) Subject: GUI toolkits References: Message-ID: Stefano Vedovelli writes: >Hello all >in my spare time I am writing a tool in python, with the intention of >deliver it under GPL. >I am now starting to approach the GUI part. I have read a lot about Tkinter, >PyQT and wxWindows, but I am now actually even more confused. >As the interface will be "quite" rich, I'd like to know the opinions of >people who already faced this decision, which tool they have chosen and >why. Being a bit of a perfectionist, when I was looking at GUI toolkits I spent quite some time comparing them. My end conclusion was that not only does Qt offer better widgets than all the others it offers a much better architecture too. This gives you more flexibility in what you can actually achieve. The learning curve is steeper though, especially if you want to understand _all_ the things it can do. I have the 'Programming Qt' book which is quite good even though it's based on C++ and the supplied manual is excellent (once you get the hang of it all). I don't have the Python Qt book yet because it hasn't arrived in any of the many bookshops I frequent, from the online version I think it doesn't go into as much depth as I would like. Eddie From whisper at oz.net Fri Jul 5 16:42:45 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 5 Jul 2002 13:42:45 -0700 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 In-Reply-To: <3D24FF3A.4010205@something.invalid> Message-ID: Making pyrexc use native (Visual C) compiler: GCC_BIN_DIR = 'd:/visstudio/vc98/bin' PYREX_DIR = 'j:/python22/apps/Pyrex0.3.3' PYTHON_VERSION = 'python22' PYTHON_DIR = 'j:/' + PYTHON_VERSION . . . def compile(name): print '\ncompile' cmd('cl -I%s/include -c %s.c -o %s.o' % (PYTHON_DIR, name, name)) . . . def wrap(name): print '\nwrap' cmd('link /DLL /SUBSYSTEM:console /DEF:%s.def /OUT:%s.pyd /LIBPATH:%s/libs %s.lib %s.obj' % (name, name, PYTHON_DIR, PYTHON_VERSION, name)) Obviously, you'll need to change the path definitions to suit your particular installation. I did not encounter the initializer problem described by Greg Fawcett. This may differ if you do more then compile the supplied demos, which is all i've done so far. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Greg Ewing > Sent: Thursday, July 04, 2002 19:07 > To: python-list at python.org > Subject: Re: A hack to let Pyrex 0.3.x users build extension classes on > Win32 > > > Graham Fawcett wrote: > > > I ran into a hitch when trying to build an extension class on > > my Win32 machine: the compiler complained with "initializer not a > > constant" errors. This is a known issue in Python; see the FAQ at > > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp . > > > Thanks for pointing this problem out. I'll see if I can > do something about this in a future release. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > > -- > http://mail.python.org/mailman/listinfo/python-list From whisper at oz.net Sat Jul 27 13:28:14 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 27 Jul 2002 10:28:14 -0700 Subject: Two RE proposals In-Reply-To: Message-ID: > > David LeBlanc wrote: > > 1. Add a substitution operator - in the example below it's "!<..>" > > > > word = r"\w*" > > punct = r"[,.;?]" > > wordpunct = re.compile(r"!!") > > > > The re compiler sees r"\w*[,.;?]" > > Trivial example, but for fancier patterns it would be great IMO. > > A substitution pass should be done over the substituted text > for nesting: > > python already has string substitution. if it needs better string > substitution, that should be solved outside the RE engine. why? I'm not suggesting a general solution. I thought about suggesting it, but I figured there where probably more ! characters in general strings then in re strings. And, there is ample precedent for characters that have no special meaning outside of re strings. Oh yeah - and i'm not suggesting a modification to Python, i'm suggesting a modification to re-language. > besides, having library modules peek in your local namespace is > really bad style. Damn - there goes inspect! I wonder what else displays bad style? Introspection/reflection considered harmful? > and your proposal will break existing code. Unsubstantiated. How can you make that assertion? Aside from which, has no Python enhancement ever broken existing code? > ::: > > the following approach works in all existing versions of Python, > gives you syntax highlighting in all existing Python editors, etc: > > def i(*args): > return string.join(map(str, args)) > > word = r"\w*" > punct = r"[,.;?]" > wordpunct = re.compile(i(word, punct)) > > if = r"if" > term = r"something" > num = r"\d*" > op = r"[-+*/]" > factor = i(num, "\s*", op, "\s*", num) > expr = i(term, factor) > if_stmt = re.compile(i(if, "\s*\(?\s*", expr, "\s*\)?\s*:")) Wow, you make Skip's example seem positively eloquent in contrast. > if you're doing lots of RE stuff, you can trivially extend this to > support RE-oriented operations: > > if = literal("if") > op = set("-+*/") > factor = seq(num, ws, op, ws, num) > > (google for "rxb" for a complete implementation of that idea) looked - not impressed. Might be of interest to XSchema or Relax-NG people. Not very re-like. > > 2. Make r"(a|b)*" mean any number of a's or b's. > > it does mean any number of a's or b's. but no more than a > single a or b will end up in the group. Huh? Actually, re rejects the pattern, or if you try hard enough, goes into an infinite loop. > > This doesn't work, at least in some situations with the current > > re compiler - the "any" op "*" doesn't seem to span over a parened > > group > > for i in range(20): > s = file.read(1) > > doesn't give you a 20 character string either (nor a 20 item list) > > fixing the read statement is of course trivial. How hard would it be to make this example make sense? ;-) > fixing the RE is done in a similar fashion: make sure the group > matches everything you want to put in the group: > > r"((?:(a|b)*)" > > if you want lists of matching things, use findall. So hard to embed findall into an re pattern - what's your secret? > > What do I do if I want a better Python? Do we wait for specific people to make suggestions or can anyone join in? David LeBlanc Seattle, WA USA From gugabbe at hotmail.com Tue Jul 23 15:45:58 2002 From: gugabbe at hotmail.com (Mack) Date: Tue, 23 Jul 2002 21:45:58 +0200 Subject: NEWBIE: for statement in "dive into python" gives syntax error. Message-ID: Hi I need some pointers. I've been reading the "Dive into python" tutorial and tried some statements on my machine. Redhat 7.1 with python 1.5.2 >>> li = [1, 9, 8, 4] >>> li [1, 9, 8, 4] >>> [elem*2 for elem in li] File "", line 1 [elem*2 for elem in li] ^ is what i'm getting. Is my python too old? Is something else wrong? I've just cut and pasted from the tutorial into python ide. Mack From pyth at devel.trillke.net Fri Jul 5 07:36:25 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 5 Jul 2002 13:36:25 +0200 Subject: Why self? In-Reply-To: ; from jolsen@mailme.dk on Fri, Jul 05, 2002 at 02:36:25AM -0700 References: Message-ID: <20020705133625.S10625@prim.han.de> Jesper Olsen wrote: > Why is it necessary to use a "self" argument to class methods in python? > > To me it seems a bit like doing object oriented programming in C... There is some truth in this. Python integrates well with C. But of course, the language wouldn't need to have you using 'self' to point to an object's instance. > Why not make it implicit like "this" in C++? Did you know that for larger projects people like to use "this->name" or prefix the member variables with 'm_' to introduce expliciteness into c++? > I do not find it usefull that I can give it my own name. which, in fact, hardly anybody ever does. It's really all about the credo "explicit is better than implicit". To find out more about python's design principles, have a look at http://www.python.org/dev/culture.html cheers, holger From jerf at jerf.org Wed Jul 24 17:56:49 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 24 Jul 2002 21:56:49 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: On Wed, 24 Jul 2002 05:54:33 -0500, Alex Martelli wrote: > ...would you please share your uses for metaclasses? I can use all the > good examples I learn about -- it's hard to teach people how to use > metaclasses without actual motivation, and the more real-life examples I > can collect and quote, the more likely I can help people achieve that > motivation! I'm currently working on a hobby project which with luck will actually be released someday. It's a type of editor that will be easy to extend, and will be able to knowledgably manipulate many kinds of files. As a result, this thing will requre lots of modules. In theory, it could end up importing hundreds of modules, just for the user to jot down a couple of notes and close the program again. This will quickly become unacceptable performance, so I will need to dynamically load the modules as they become necessary. (In fact I'm not 100% certain how to accomplish this perfectly correctly and as I get closer to the problem I may post some more questions on the newsgroup. I know it's possible because I've got some 75% solutions, but I don't like them. That's not today's issue.) In conjunction with this, I have a module I've developed that I'm using for cheap and easy persistence, enclosed at the end of this message. It uses the pickle module. One of the things I'm sticking in this persistence space is bindings between keypresses and Command objects (an extension of the Command pattern). One problem with that approach is that pickling a refernce to the actual class of the Command will cause Python to import the module containing that class when the reference is unpickled. This is a Good Thing, but it means that the act of unpickling the keymap could invoke the aforementioned Bad Behavior of loading tens or even hundreds of unnecessary modules. The solution to every problem is another layer of indirection, right? I can store the name of the Command class (or module name + class name, which is what I do) in the keymap. When the user presses a key, I can retrieve the name and go get the class to instantiate, right? So I do this in my dispatcher module: str2obj = {} class ClassId(type): def __init__(cls, name, bases, dict): super(ClassId, cls).__init__(name, bases, dict) cls.classId = dict["__module__"] + "." + name str2obj[cls.classId] = cls and in my command base class, there's a __metaclass__ = dispatcher.ClassId Now I get a nice dict which I can index off of the .classId of the command objects, unpickling the strings does not load the modules, and life is good, with just a few lines. Why not use the module name and class name directly with sys.modules? I had a reason last night but I've forgotten it now. I guess please just take it on faith that that's not a sufficient answer in the *larger context of my complete program*. I'm certainly not suggesting this would be good for everybody in all cases. One thing I do remember is that I'm concentrating a lot of (untested) try: cls = sys.modules[commandCls.__class__.__module__][commandCls.__class__.__name__] else: handle class not being loaded code into this one place, and I'll trade a small metaclass for several instances of the above any day. It's not the greatest of uses. What really rocked my world was how easy it was, once I understood the concept. ------- registry.py It's not necessarily done and people may not like the __getattr__ and __setattr__ trick. Just know this: It's used in a controlled environment and does what I want. ;-) ------- """There was a nice docstring here, but I tossed it because it largely didn't apply to the newsgroup posting. Basically, this is a dict that knows how to dump itself to disk, reload itself, create a place for somebody else to store data (initSubkey) like a registry, and while you may not like it, allow access through dot notation rather then [], which makes better semantic sense in the context this is being used in. It's not a general dict replacement, it's a focused extension that works for me. """ from cPickle import dump, load from types import * from gzip import GzipFile class Table(dict): def __init__(self): dict.__init__(self) # You may find the following two functions morally repugnant. If # so, remove them and please don't give grief. ;-) def __getattr__(self, name): # For pickling correctly if not self.has_key(str(name)): raise AttributeError(str(name) + " does not exist.") return self[name] def __setattr__(self, name, value): self[name] = value def __getitem__(self, name): # force to string return dict.__getitem__(self, str(name)) def __setitem__(self, name, value): if value == {}: dict.__setitem__(self, str(name), Table()) else: dict.__setitem__(self, str(name), value) def saveToFile(self, filename = None): if filename == None and self.__dict__.has_key("file"): filename = self.__dict__["file"] elif filename == None: raise TypeError("Need filename in second arg.") f = GzipFile(filename, "w") dump(self, f, 1) f.close() self.__dict__["file"] = filename def loadFromFile(self, filename): self.clear() f = GzipFile(filename) tmp = load(f) f.close() self.__dict__["file"] = filename self.update(tmp) def initSubkey(self, subkeyStr, initDict): keys = subkeyStr.split(".") current = self # get to the given subkey for key in keys: if not current.has_key(key): current[key] = Table() current = current[key] # load up the initial values, if they don't exist for key in initDict: if not current.has_key(key): current[key] = initDict[key] return current _root = Table() try: _root.loadFromFile("your file here") except: _root.saveToFile("your file here") # in case I change this to a class or something someday def registry(): return _root class RegistryUser: """RegistryUser is a mixin class that provides easy registry initialization for a registry user. To provide default values for the registry entries, provide them as keyword arguments on the __init__ call, or prepare a dict in advance and use ** notation. The registry will be located at self.reg for the class.""" def __init__(self, reg_key, **kwds): reg = registry() self.reg = reg.initSubkey(reg_key, kwds) From whisper at oz.net Sun Jul 7 20:50:03 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 7 Jul 2002 17:50:03 -0700 Subject: procmail replacement in Python In-Reply-To: Message-ID: The python scripts in the tarball don't have .py extensions, but they're there. You can add the .py extension for use under windows or just "python name" will work. I think only the pycmail file is python: i.e. it's all in that one file. You should note that this has a dependency on Unix features. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Sheila King > Sent: Sunday, July 07, 2002 12:29 > To: python-list at python.org > Subject: Re: procmail replacement in Python > > > On 07 Jul 2002 09:05:33 -0400, pinard at iro.umontreal.ca (Fran?ois Pinard) > wrote in comp.lang.python in article > : > > > [Fran?ois Pinard] > > > > > Here is a copy of my copy: > > > > Oops, sorry! > > > > I should not have Cc:ed python-list with the full archive. On the other > > hand, as it is rather small, I think I will nevertheless sleep > tonight :-). > > In a word, I apologise, and will try paying more attention in > the future. > > Francois, > > Thanks or the copy I received in email. However, that tarball > that you sent > seems to be incomplete and doesn't have any .py source files. Seems mostly > to have .pycmailrc and other types of config files, .doc type files and > install files. > > The README files make it look very intriguing. I'd sure like to get my > hands on the Python source. > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > -- > http://mail.python.org/mailman/listinfo/python-list From solrac at us.ibm.com Thu Jul 4 09:45:24 2002 From: solrac at us.ibm.com (Frank) Date: 4 Jul 2002 06:45:24 -0700 Subject: Python and XML development using the open source 4Suite toolkit Message-ID: <64ebecf3.0207040545.a5dbbad@posting.google.com> Python and XML development using the open source 4Suite toolkit 4Suite is an open source, comprehensive library and toolkit for XML processing in Python. 4Suite implements various open standards related to XML. This series of tutorials introduces 4Suite and gives practical examples of XML development using 4Suite and Python. Part 1: PyXml There are various DOM implementations, in varying computer languages. Here, we will be introducing PyXml. This particular implementation is written in Python. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/28BEDEE3E7219EB386256AE300743B69?Open&t=gr,lnxn28,p=PyXml Part 2: 4XPath and 4XSLT This tutorial introduces 4XPath and 4XSLT . If you plan to use Python in association with XML processing, these are useful tools to get to know. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/BE1A7E60838F9F7686256AF400523C58?Open&t=gr,lnxn28,p=4XPath4XSLT Part 3: 4RDF This tutorial will go into detail on RDF, with hands-on examples of how to use the various RDF facilities available with Python. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/8A1EA5A2CF4621C386256BBB006F4CEC?Open&t=gr,lnxn28,p=4RDF >>---> POD From nas at python.ca Mon Jul 8 15:45:40 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 8 Jul 2002 12:45:40 -0700 Subject: stackless python In-Reply-To: ; from pinard@iro.umontreal.ca on Mon, Jul 08, 2002 at 03:24:42PM -0400 References: <20020708102618.A4681@glacier.arctrix.com> Message-ID: <20020708124540.A5014@glacier.arctrix.com> Fran?ois Pinard wrote: > (My main question, maybe already answered in there -- I did not check yet > -- is how one proceeds to `yield' from within a nest of function calls, > and to later kludge resuming the function nesting sequence on `.next()'.) You can't since only one stack frame is saved per generator. That's why one of the reasons they are called simple generators (two others being ease of implementation and of understanding). You probably want to look at stackless Python if you haven't already. > P.S. - Smiley mode on. I read "tow" in the quote above and surely, this > is a typo. But I wonder if it is a typo of "two" or a typo of "toy". :-) Either correction works fine. Neil From brueckd at tbye.com Tue Jul 30 19:20:00 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 30 Jul 2002 16:20:00 -0700 (PDT) Subject: global interpreter lock not working as it should In-Reply-To: <7xofcoopfs.fsf@ruckus.brouhaha.com> Message-ID: On 30 Jul 2002, Paul Rubin wrote: > brueckd at tbye.com writes: > > When you get right down to it, there's really *little* difference between > > Python threads and C threads, so the above statement doesn't make too much > > sense to me. Sure the GIL makes sure that Python object internals are > > fiddled with one thread at a time, but if you have only 1 CPU, there's > > only one thread running at a time anyway, regardless of whether your > > program is in C or Python. IOW, the GIL has no real effect on the > > applicability or usefulness of threads (assuming a single CPU). > > But that is precisely the gripe about the GIL. If you have multiple > CPU's, you can use them with C threads but not with Python threads. Oh, I don't disagree with you one bit, Paul. I _am_ disagreeing with the notion that on the OP's single CPU system the GIL is causing him problems. -Dave From renzo.tomaselli at tecnotp.it Mon Jul 8 11:02:19 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 8 Jul 2002 08:02:19 -0700 Subject: adding methods on the fly References: Message-ID: <878dc260.0207080702.2be7ba9f@posting.google.com> Alex Martelli wrote in message news:... > Renzo Tomaselli wrote: > > 1. Can we add new (Python) methods to a C object wrapper, e.g. after it > > has been instantiated with a normal (C) method table ? > > What happens when you try to add attributes to a C-coded object depends > on how that C-coded object has defined its setattro slot (or its setattr > slot, but that's an older and less general way to do things). And > similarly for the getattro that implicitly happens when the attribute > is "gotten" prior to calling it. > > So, it all depends on how you code your C extension. Ok, I will investigate further about slots. > > 2. if not: can we add a new method to an already imported Python class ? > > If yes, how can we do it, assuming to start from a method statement hosted > > by a string ? > > Given a Python class object, whether classic or new-style, setattr works > just fine. Not sure what is "a method statement hosted by a string". I mean a function declaration in a string. In short, what I miss is a way to transform it into a callable object to be added to a class. Whether such class is just a wrapper on my C++ object or a Python derived class depends on issue below. I'm lost here between PyRun_String and PyCompile_String, which seem the only places where I can start from code strings to add methods on the fly. > > I understand that the latest version (2.2.1) allows for defining a class > > which inherits from a C type, so that we can define some Python methods on > > it, while retaining the capability of inherited C methods. > > Yes, as long as that C-coded type IS specifically coded as to support > being inherited from. Once again, it all depends on how you code at > the C level. Could you please explain this topic a little further ? How do we enable a C type to be inherited from by a Python class ? > One way to avoid depending on how the C-level code is written is to > use wrapping and automatic delegation in your Python class -- that > also works in 2.1 and earlier, not quite as fast as inheritance but > the difference may not be dramatic. For an example, see > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 > (or, better, the expanded and clarified version in the printed > Python Cookbook, ed. Martelli and Ascher, but that's only due out > in 3 weeks, so, meanwhile, the original online version will do:-). > > > Alex Ok, got it. The overall issue is dealt with in the opposite way I'm interested in: almost all involved discussions on this list handle about estending Python by C/C++ while I need to extend C++ by Python. And possibly by adding just functions (methods), no extra class stuff or modules. Thanks for any suggestion, Renzo Tomaselli --------------------------------------------------------------------------- TecnoTP s.n.c. Special Information System Design Maso Pelauchi I38050 Ronchi Valsugana, Trento TN ITALY e-mail: renzo.tomaselli at tecnotp.it --------------------------------------------------------------------------- From cce at clarkevans.com Sat Jul 27 13:06:19 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Sat, 27 Jul 2002 13:06:19 -0400 Subject: Python and XML help In-Reply-To: ; from mathieu@nouvelempire.net on Fri, Jul 26, 2002 at 10:03:43AM -0700 References: Message-ID: <20020727130619.A41471@doublegemini.com> On Fri, Jul 26, 2002 at 10:03:43AM -0700, Mathieu wrote: | | | | | | | | | | | | For a simple properties list like this you could use YAML instead of python... it'd be alot easier. This way you don't have to mess with DOM or SAX. $ wget http://yaml.org/python/PyYaml_25jul2002.tgz $ tar xvfz PyYaml_25jul2002.tgz $ cd PyYaml $ python setup.py install $ python ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import yaml >>> x = yaml.load(""" ... properties: spam ... prop: ... first: ... - foo ... - foo2 ... second: ... - bar ... - bar2 ... """).next() >>> print x # with slight formatting for readability... {'properties': 'spam', 'prop': {'second': ['bar', 'bar2'], 'first': ['foo', 'foo2']}} >>> x["prop"]["first"][0] 'foo' >>> print yaml.dump(x) --- prop: first: - foo - foo2 second: - bar - bar2 properties: spam >>> ^Z Best, Clark From gerhard.haering at gmx.de Mon Jul 29 12:25:02 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 29 Jul 2002 18:25:02 +0200 Subject: [ZOPE] Zope, Python, Win2k and Mysql In-Reply-To: References: <4a4akukkfg92po76t3svc7flen29s3stui@4ax.com> Message-ID: <20020729162502.GB602@lilith.my-fqdn.de> * Rhymes [2002-07-29 17:24 +0200]: > On Mon, 29 Jul 2002 12:27:37 +0200, "Gillou" > wrote: > > >You should... > > > >1/ Install Python 2.1.3 from www.python.org (even if you lalready got the > >one provided with Zope) > > > >2/ Install mysqdb from sourceforge on top of this new python installation > > > >3/ change the "start.bat" file to run zope from that python.exe (tipycally > >c:\python2.1\python.exe) > > > >This does the job for me. > > I don't want another Python distribution... I have the 2.2.1 one > Could I follow only your third tip? No, Zope _requires_ Python 2.1.x. Maybe you'll find the installers for the MySQL DA and the mxExtensions from my homepage useful (see signature). Then, you won't need to install an additional Python 2.1.3. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From howard at eegsoftware.com Thu Jul 18 16:13:33 2002 From: howard at eegsoftware.com (Howard Lightstone) Date: Thu, 18 Jul 2002 20:13:33 GMT Subject: embedding problem with dictionary Message-ID: I am using a mixed C(++)/Python program to process some real-time data. The Python part (2.0 in my case) handles the GUI, operator selections, etc., and the C part does the real-time (at least as good as W-ants-to-do-whatever -it-wants-INDOWS will let it). I build a dictionary in my C code which contains some other dictionaries and pass it from an embedded Python extension to a C routine (which actually runs the real-time part). I am able to use all the parts of this dictionary (getdict). However, I now need to pass back some values to the Python code (through the dictionary) using putdict(). I seem to be getting intermittent results here. Sometimes the values are unchanged from passed-in values and sometimes they work. Am I not doing what I think I am? Interface routines: (idict is the dictionary object passed in from Python to C++) static int getdictstring(char *basename,char *key,char *dest,int destlen,int forceabort) { char *d=basename,dn[200],*buffer; PyObject *pnr,*pnd,*pnt; int slen; if (!basename) d=""; // find correct "dict" pnd=idict; if (*d) // is the the base dictionary or a dictionary object { pnd=PyDict_GetItemString(idict,basename); // borrowed reference if (!pnd) { if (forceabort) { sprintf(dn,"bad subdict : %.50s",basename); raise_fatal_error(dn); } else return 1; } } pnr=PyDict_GetItemString (pnd, key); // borrowed reference if (!pnr) { if (forceabort) { sprintf(dn,"bad key name %.50s : %.50s",basename ? basename:"",key); raise_fatal_error(dn); } else return 2; } pnt=PyObject_Str(pnr); // new ref if (PyString_AsStringAndSize (pnt, &buffer, &slen) < 0) { raise_fatal_error("asStringAndSize"); } if (slen >= destlen) slen=destlen-1; memcpy(dest,buffer,slen); dest[slen]=0; Py_DECREF(pnt); // remove "new" ref return 0; } #if 1 int putdict(char *basename,char *key,char *value) { char *d=basename; PyObject *pnd,*pnt; if (!basename) d=""; // find correct "dict" pnd=idict; if (*d) // is it the base dictionary or an object in it { pnd=PyDict_GetItemString(idict,basename); // borrowed reference if (!pnd) { // must "create" such a subdictionary pnd=PyDict_New(); // new reference // add reference into main dict PyDict_SetItemString(idict,basename,pnd); // always leave with valid pnd } } // create the 'string' object pnt=PyString_FromString(value); // new reference ...leave it around PyDict_SetItemString(pnd,key,pnt); // if this replaces something (as is usual) // python handles ref counts return 0; } #endif From fredrik at pythonware.com Wed Jul 3 09:50:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jul 2002 13:50:13 GMT Subject: Useful RE patterns (was: Variable Interpolation - status of PEP215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> <3D229458.719D4A7B@vip.fi> Message-ID: Pekka Niiranen wrote: > Please make also example of recursive decent > parser, for example LL(k) regular expressions and parsers are two different things. you can use regexps to implement the scanner part of a parser (see e.g. http://effbot.org/guides/xml-scanner.htm), but they quickly break down if you try to do something more sophisticated. From wurmy at earthlink.net Wed Jul 10 00:17:43 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Wed, 10 Jul 2002 04:17:43 GMT Subject: Learning how to program... but what's the best way? Message-ID: <3D2BB54C.90500@earthlink.net> Hi, I know a 14-year-old who wants to learn programming. Of course I'd recommend Python, and I also know the way to all the tutorials, non-programmers introductions, etc. But... The problem is, I don't expect my student to swoon over "hello world", or to get excited about doing basic mathemathical computations. Nor will standard computer science stuff about bits, bytes, hexadecimal numbers etc be appealing. Sure, those concepts are important, and will be dealt with in due time, but what I'm looking for right now is a way to capture people's interest-- to do something funny, or cool, or useful even for someone who doesn't know programming. To give an idea of what I have in mind: A good start could be, for example, some kind of game that can be scripted in Python, and therefore extended at will. The "student" could say, "I want the game to do this-and-that", then proceed to implement it. Unfortunately, I know of no such game, and have no time to write it <0.3 wink>. Besides this, does anyone have ideas about what would be a good starting point here? TIA, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From stephen at theboulets.net Mon Jul 29 00:50:38 2002 From: stephen at theboulets.net (Stephen Boulet) Date: Sun, 28 Jul 2002 23:50:38 -0500 Subject: Base classes or global functions References: <3D3F37E0.2000209@onsitetech.com> Message-ID: Thanks for the additional responses. The types of functions I was talking about are just some utility functions for working with strings and lists. Here are a couple: def findUntil(str, f): """ Return the firstline in a file containing 'str' """ while(1): line = f.readline() if line == '': print "Ran all the way through the file", print "without finding '" + str + "'" return -1 if line.find(str) != -1: break return line def rremove(aList, item): """ Remove from a list all occurences of 'item' """ while(1): try: aList.remove(item) except ValueError: break I did implement Alex Martelli's suggestion (put them in utilityFuncs.py, and do an "import utilityFuncs". This has the advantage of making my namespace cleaner. Is that way of doing it better or worse than: class BaseClass: def __init__(self): pass def findUntil(self,str, f): """ Return the firstline in a file containing 'str' """ while(1): line = f.readline() if line == '': print "Ran all the way through the file", print "without finding '" + str + "'" return -1 if line.find(str) != -1: break return line def rremove(self,aList, item): """ Remove from a list all occurences of 'item' """ while(1): try: aList.remove(item) except ValueError: break class Class1(BaseClass): ... etc... Both ways work. Oh no, does that mean there is more than one way to do it? ;) -- Stephen Robb Shecter wrote: > Stephen Boulet wrote: >> I have two classes, Class1 and Class2. Class1 contains a list of Class2 >> objects, but no inheritance is involved >> >> Both classes use some functions I wrote. What's the best way of making >> the functions available to the classes? >> > > Good questions. To answer it, we'd have to know what the functions do - > what information they manipulate. Depending on your answer, any of the > following scenarios are possible: > > 1. The functions become methods of Class1. > 2. The functions become methods of Class2. > 3. The functions become methods of a new, as yet unwritten class. > 3a. This new class would be used by Class1 and Class2 > 3b. This new class would be subclassed by either Class1 or Class2. > > Robb From steve.menard at polyester.com Fri Jul 19 19:32:54 2002 From: steve.menard at polyester.com (Steve Menard) Date: Fri, 19 Jul 2002 19:32:54 -0400 Subject: [Q] wxPython - layout & placement References: Message-ID: "Rolf Marvin B?e Lindgren" wrote in message news:lbzznwnpu98.fsf at aqualene.uio.no... > I'm trying to place a button in a dialog window. this works: > > dlg = wxDialog(parent,-1,FileName,size=(400,400)) > > wxButton (parent=dlg, > id = -1, > label = 'This is a button', > pos=(10,10)) > > dlg.ShowModal() > > but I'd like to use layout controls. I've figured out how to do it > with wxPanel, but wxDialog doesn't seem to work the same way. the > example on > > b = wxButton(self.panelA, 100, ' Panel A ') > lc = wxLayoutConstraints() > lc.centreX.SameAs (self.panelA, wxCentreX) > lc.centreY.SameAs (self.panelA, wxCentreY) > lc.height.AsIs () > lc.width.PercentOf (self.panelA, wxWidth, 50) > b.SetConstraints(lc) > > does not work if the parent object is a wxDialog. > > any clues? > > > -- > Rolf Lindgren http://www.roffe.com/ > roffe at tag.uio.no One easy solution is to us a wxPanel to do you layout, then put that panel in the wxDialog. It should not be too hard to make sure the wxPanel fill out the entire dialog ... Steve steve.menard at videotron.ca From shagshag13 at yahoo.fr Tue Jul 9 09:14:33 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 15:14:33 +0200 Subject: sorting many arrays from one... References: Message-ID: "Alex Martelli" a ?crit dans le message de news: nYAW8.59639$vm5.2174555 at news2.tin.it... > aux_list = zip(drive, other1, other2, other3) > aux_list.sort() > > for i in range(len(drive)): > drive[i], other1[i], other2[i], other3[i] = aux_list[i] > thanks ! it's quite impressive and even works with array (i didn't even knew this "zip" built-in function nor thought that sorting was possible on tuples). I think that if you don't use "map" to replace the "for loop", it's because it's impossible, so i don't need to try ;o) i have another question, i need a way to have a one to one mapping from string to integer to save storage : in fact having an id key associated with strings (like in a database). By now i use the code below (which was inspired by seqDict package). But you told me that to save memory and time i should better use 2 dicts, did i understood well ? or is is a better "efficient" way ? and again great thanks for all your advices / replies... s13. ---- def test_Keys(): k = Keys() t = ('Un', 'Deux', 'Trois', 'Quatre', 'Cinq', 'Six') for i in range(len(t)): k.add(t[i]) print "longueur = [%s]" % len(k) print "element 2 = [%s]" % k[2] print "position de [%s] = [%s]" % (t[2], k.index(t[2])) class Keys: def __init__(self): self._size = 0 self._elements = {} # dictionary element -> int key - ex: {a : 0, b : 2, c : 1} self._seqKeys = [] # list containing elements, int key -> element - ex: [a, c, b] def __str__(self): # Missing code to check for empty !!! s = 'Keys (' + "\n" s += str(self._elements) + "\n" s += str(self._seqKeys) + "\n" s += str(self._size) + ' # size' + "\n" s += ')' + "\n" return s def __len__(self): return self._size def __getitem__(self, pos): return self._seqKeys[pos] def reset(self): del self._size del self._elements del self._seqKeys self._size = 0 self._elements = {} # element -> int key - ex: {a : 0, b : 2, c : 1} self._seqKeys = [] # contains elements, int key -> element - ex: [a, c, b] def get_item(self, pos): return self._seqKeys[pos] def index(self, element): return self._elements[element] def get(self, key): if type(key) == types.IntType: return key elif type(key) == types.StringType: return self._elements[key] def keys(self): return self._seqKeys def get_size(self): return self._size def add(self, element): if self._elements.has_key(element): return self._elements[element] self._seqKeys.append(element) self._elements[element] = self._size self._size += 1 return (self._size - 1) From matt at mondoinfo.com Sun Jul 14 22:54:44 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Mon, 15 Jul 2002 02:54:44 GMT Subject: maaxlength in Entry() / Tkinter References: Message-ID: On Mon, 15 Jul 2002 03:21:40 +0200, Joaquin Romero wrote: Dear Joaquin, > I can set an maxlength (max number of characters) in a Entry() in > Tkinter? Yes, you can though it's a bit of a nuisance. You need to bind a routine to the KeyPress event and allow or disallow the character depending on the number of characters already there. I'll append a small example. Regards, Matt from Tkinter import * class mainWin: def __init__(self,root): self.root=root self.entryMaxLen=6 self.createWidgets() return None def createWidgets(self): self.e=Entry(self.root) self.e.pack() self.e.bind("",self.checkContentsLength) return None def checkContentsLength(self,event): # Allow some characters even if the field is full. # There are probably others that should be allowed # that I'm not thinking of right now. Allowing # control-h is more complex and outside the scope # of this news post . if event.keysym in ("BackSpace","Delete","Tab","Left","Right"): return None if len(self.e.get())==self.entryMaxLen: # Don't allow further processing of this event # by Tkinter return "break" else: # Further processing OK return None def main(): root=Tk() mainWin(root) root.mainloop() return None if __name__=="__main__": main() From shalehperry at attbi.com Fri Jul 5 17:29:29 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 05 Jul 2002 14:29:29 -0700 (PDT) Subject: how to disable maximize button? In-Reply-To: Message-ID: On 05-Jul-2002 Alex Martelli wrote: > jubafre at zipmail.com.br wrote: > >> how i can disable de maximise button in tkinter, i don?t want the user >> modific the size of the window, i want a real size of window, how can i do >> it??? > > You can remove all decorations: > > import Tkinter > root = Tkinter.Tk() > root.overrideredirect(1) > override_redirect means "I can handle myself, leave me alone". The window manager will not touch your window. It will be up to you to handle moving it, showing a title, etc. > Apart from this, you may choose to fix the size: > > import Tkinter > root = Tkinter.Tk() > root.resizable(0,0) > > > I know of no way to affect the maximize button ONLY, without also > affecting other ways to resize the window, but then from your post's > text I don't see why you should ONLY want to affect said button. > > > Alex > > > -- > http://mail.python.org/mailman/listinfo/python-list From spam at ob_scure.dk Sat Jul 6 18:13:21 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 00:13:21 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> Message-ID: <3D276B81.9090003@ob_scure.dk> Alex Martelli wrote: [snip] > With Python, you can exploit multiple CPUs only by multi-*processing* -- > and here, it's possible that Windows' multi-processing inefficiencies > may byte you (with Unix-like systems, often multiple processes or > multiple threads in one process have quite comparable performance). Ok, thanks. The actual job is easily parallelisable (is that a word? :-) in that it can be broken into a number (about 500) of calls to a function that takes one integer as input, ie. calcUnit(unitnum) (This assumes that a database connection is available through a class or global variable to the function). I was planning on spawning one single-threaded XMLRPC-server per CPU per machine and then having a control process on one of the machines with a thread per process. These threads would fetch unit numbers from a Queue object and call the XMLRPC server using xmlrpclib. Am I correct in beliving that this would utilize all CPUs? (Windows issues aside). -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From johnroth at ameritech.net Thu Jul 25 19:35:59 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 25 Jul 2002 19:35:59 -0400 Subject: DOS-Shell hangs up, python/Tkinter References: <3D3FBF1A.C1531FB3@ipm.fhg.de> Message-ID: "Howard Lightstone" wrote in message news:Xns925661F9F4709howardeegsoftwarecom at 66.75.162.198... > Markus von Ehr wrote in > news:3D3FBF1A.C1531FB3 at ipm.fhg.de: > > > Hi, > > > > when I start my python/Tkinter apps out of a MS-DOS shell > > and kill the app, very often the DOS-prompt doesn't come back, > > the Shell hangs-up. > > This is a "known" bug in Tk. > > http://sourceforge.net/tracker/?func=detail&atid=105470&aid=216289& > group_id=5470 > > The workaround: > use pythonw for now........ I've been patiently waiting for AnyGUI in the hopes that it would provide the ability to use a working graphics library under each environment. Unfortunately, I haven't seen any progress posted on AnyGUI in a while. That may mean they just aren't keeping their projected next release date updated (I hope). John Roth > From BPettersen at NAREX.com Tue Jul 2 00:36:49 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 1 Jul 2002 22:36:49 -0600 Subject: Teaching programming -- circular data structures Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192F1AA6D@admin56.narex.com> > From: Roy Smith [mailto:roy at panix.com] [snip: how Roy came to create a circular data structure] > Is this a common thing? I, as an experienced programmer, found the > circular references perfectly reasonable, but it seemed to blow his > mind. Have people teaching programming (or, more precisely, data > structures) see this before; that people have problems understanding > circular data structures the first time they're exposed to > the concept? We had the same problem teaching recursion to first year CS students, so I think it's pretty common. Once they got used to inductive proofs most of them seemed to "get it" however, so my current theory is that some sound CS theory makes for a better programmer You could always show him a fundamental data structures text that covers AVL or Red-Black trees . -- bjorn From Gabe.Newcomb at noetix.com Tue Jul 23 14:58:38 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Tue, 23 Jul 2002 11:58:38 -0700 Subject: good books -- Python Essential Reference by David Beazley Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6121@NOXMAIL.noetixad.com> Yeppers, me too. I keep the Essential Reference and the O'Reilly Pocket Reference by my side at work. Priceless as far as I'm concerned. -----Original Message----- From: DIG [mailto:dig.list at telkel.net] Sent: Tuesday, July 23, 2002 11:33 AM To: python-list at python.org Subject: Re: good books -- Python Essential Reference by David Beazley Hi, John Hunter ! On Tue, Jul 23, 2002 at 09:12:05AM -0500, John Hunter wrote: > If you want a book with a long shelf life, many including myself, > recommend Python Essential Reference by David Beazley. I agree with that. Best regards, -- DIG (Dmitri I GOULIAEV) -- http://mail.python.org/mailman/listinfo/python-list From aleax at aleax.it Sat Jul 13 17:12:06 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 21:12:06 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308c96_8@news.newsgroups.com> Message-ID: JB wrote: ... > bigger. I thought that when f is slow, then at least the > merging should be as fast as possible. Wrong attitude. If f is slow enough, all that matters is minimizing the numbers of calls to f -- everything else is secondary and might as well be optimized for clarity and simplicity instead. > I thought that as have many entries, O(n) should mean "as > fast as possible". As N goes to infinity, yes. For real cases, maybe, and maybe not. If f(x) selects few enough x's, my first suggestion may be generally preferable -- even though its WORST CASE (that's what big-O notation is generally about...!) is O(N log N) rather than O(N). How often is the worst case encountered, and what are the multiplicative constants in play...? Alex From gerhard.haering at gmx.de Thu Jul 4 14:11:11 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 4 Jul 2002 18:11:11 GMT Subject: Embedding: how to extend a C++ instance by Python methods References: Message-ID: Renzo Tomaselli wrote in comp.lang.python: > Hi all, > my current goal is to extend a C++ instance behavior by a Python > method, A C++ class that's exposed to Python, with one method delegating to a Python method defined in a .py file? > so that an explicit "execute(scriptName, args)" method on such > instance will end up into running a Python method defined by > scriptName. Which execute() function is this? I found the rest of your post pretty confusing. If all you want is call a Python callable (function/method/...), you can use PyObject_CallObject for this. Else could you please try to rephrase your question a little? Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cliechti at gmx.net Fri Jul 19 15:01:51 2002 From: cliechti at gmx.net (Chris Liechti) Date: 19 Jul 2002 21:01:51 +0200 Subject: importing custom modules References: Message-ID: xeon at dacreations.cjb.net (xeon) wrote in news:c21a43ff.0207191038.4f115531 at posting.google.com: > I'm new at python. I'm under the impression that 'import' searches the > lib directory as defined in PYTHONPATH env. variable. almost. it searches the directories in sys.path. PYTHONPATH is used to add direcories to that list. > Is there any way > to load my own modules located outside the lib directory, but leaving > the lib modules access intact (without changing the env. variables), > from inside the intepreter? e.g. to add the parent directory: sys.path.append(os.path.abspath("..")) chris -- Chris From cliechti at gmx.net Thu Jul 25 14:38:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jul 2002 20:38:11 +0200 Subject: python class question References: Message-ID: Axel Bock wrote in news:ahpcfo$uor7e$1 at ID-138381.news.dfncis.de: > Hi folks, > > I need an explanation of a piece of code *urgently* usualy you'll get prompt answers here, even if you don't mention it. :-) >, to understand an > error message generated by Zope Python (a pure Python error, I think > ...). > > Well: I have a class xrml, which wants to access a ZMySQLDA database > connection (all this happens under Zope, but I think my question is > pure Python nonetheless). For this I stole code from another module > (ZSQLMethods :-), and the result looks like this: > > class xrml(SimpleItem.SimpleItem): > def init_db(self): > try: > dbc = getattr(self, connection) why not: dbc = self.connection > except: one should only catch specific exceptions, otherwise you'll make you life harder (by difficult to debug problems) better would be: except AttributeError: > return 'error' > DB = dbc() that just binds the result of a call or constructor to the variable DB. > > Now I tried to modify the last line as follows: > self.DB = dbc() > and getting a very strange error (Error Type: UnpickleableError > Error Value: Cannot pickle objects). don't know Zope but it look like that it uses pickle to store your instaces and the DB object cannot be picked. thats probably because the connection to a database cannot be stored, it must be terminated and rebuild, but thats doesn't seem to be supported by the db object. > Now my question is: what the hell am I doing here? Especially what is > DB?? connection seems to be equally important, how can I find out what > type of thing this is? A "return self.connection" delivers a > "MySQL_database_connection". Is this a string, or an object? that's an object. it just that the opjects __str__ or __repr__ method returns a string for display purposes. > The code works well (queries and all else) if I use DB instead of > self.DB, but this makes me unable to use DB from other member > functions, doesn't it? (I'm quite a Python newbie i fear ... :-)) simplest thing will be when you pass around the DB object as argument if you need to call other methods. maybe someone else can say how DB connections and pickle behave within Zope... chris -- Chris From gerhard.haering at gmx.de Thu Jul 18 15:57:05 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 21:57:05 +0200 Subject: HTML DOM parser? In-Reply-To: <7xwursj0a4.fsf@ruckus.brouhaha.com> References: <7xwursj0a4.fsf@ruckus.brouhaha.com> Message-ID: <20020718195704.GB2955@lilith.my-fqdn.de> * Paul Rubin [2002-07-18 12:36 -0700]: > Anyone know of a Python-callable HTML DOM parser? I mean a serious > one that tries to understand the crappy malformed out there in the > real-world Web, the way a browser does. I see two options: - use mxTidy (http://www.lemburg.com/files/python/mxTidy.html), then operate with a normal HTML parser on the output - extract the parsing code from a real browser, like Mozilla or Konqueror. If it is win32 only, it might be possible to get to the DOM with interfacing Internet Exploder via COM, too > If it can interpret Javascript that's even better. You'll need a browser engine for that. Or use one of the other Javascript engines and feed them your DOM. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From bokr at oz.net Thu Jul 25 18:17:02 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 22:17:02 GMT Subject: random 64-bit int References: Message-ID: On Thu, 25 Jul 2002 17:07:21 -0400, "Tim Peters" wrote: >[Jeff Davis] >> ... >> random() isn't really all that random either, since it is only zero to >> one and a conversion to a float loses a lot of information (I think... >> let me know if I'm mistaken). > >A Python float is a C double, which on most boxes has 53 bits of precision. >That means, e.g., that there are 2**53 distinct Python floats in the range >[0.5, 1.0) alone. Also 2**53 distinct Python floats in the range [0.25, >0.5) alone; etc. That's a lot of floats. Python's Wichmann-Hill generator It's a lot of floats, but I think your number should be 52, for bits representing the fraction bits below the single implicit bit that represents 0.5 or 0.25 etc. >has only about 45 bits of internal state, and no information is lost in >representing one of those states as a Python float. > >A direct and quicker pure-Python method of generating random N-bit ints can >be found here: > > http://www.faqts.com/knowledge_base/view.phtml/aid/4406 > > Regards, Bengt Richter From tdelaney at avaya.com Wed Jul 24 20:00:05 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 25 Jul 2002 10:00:05 +1000 Subject: how to count lines in a file ? Message-ID: Damn - what happened there? Somehow I got a paragraph in the wrong place, and an extra .sig ... > From: Delaney, Timothy [mailto:tdelaney at avaya.com] > > > From: Richard Jones [mailto:rjones at ekit-inc.com] > > > > On Thu, 25 Jul 2002 8:31 am, Delaney, Timothy wrote: > > > > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt] > > > > > > > > print len(open('/etc/passwd').readlines()) > > > > Sorry, I'm coming in to this thread halfway through, but I > > need to know why > > that code is broken? Is it the > > "open('/etc/passwd').readlines()"? That's a > > very common pattern, as you note, because people think it is > > perfectly > > legitemate. What about it is broken? Why isn't it pointed out > > more often that > > it _is_ broken? > > We had this discussion just recently, but yes, that is > precisely what is > broken. > > What is broken? The file is never explicitly closed. > > Why is it broken? There are no guarantees that the file will be closed > either: > > 1. Immediately (the assumption in code that uses the above construct); > > 2. In a timely manner; > > 3. Before the interpreter exits; > > 4. Before the computer is turned off. > > You can usually gather a guarantee of 4 from the OS (all > files opened by a > process are closed when that process exits) but you then have another > problem: > > open(filename).write(string) > > Now you not only have no guarantees that the file is closed, > but also no > guarantees that is the file is closed, it is flushed before > closing. The > most likely case where this occurs is at program exit - all files are > closed, but not flushed. > > To date, many people have relied in (non-) guarantee #1 - > that the file will > be closed (and flushed) immediately. > > This in currently not true in Jython, and would not have been > true with the > proposed patch. Luckily for such people, there is a strong > desire not to > break "working" code, even if such code really is broken anyway. What > happens if I try to use a module containing such code under Jython? > > It is explicitly documented that yo may not rely on reference-counting > semantics for such things (Paul Rubin - take note please). > > Tim Delaney > > -- > http://mail.python.org/mailman/listinfo/python-list > From opengeometry at NOSPAM.yahoo.ca Sun Jul 7 18:47:14 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 7 Jul 2002 22:47:14 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> <3D282FF8.6040602@ob_scure.dk> <7x3cuvsnc7.fsf@ruckus.brouhaha.com> <3D2864DE.6030608@ob_scure.dk> Message-ID: Thomas Jensen wrote: > We already have 2 DB Servers, a master replicating changes to a slave. > Our analysis shows that most database operations are/will be SELECTs. > Adding more DB servers is trivial, especially if we migrate to MySQL > (well, cheaper at least :-) As I and others have said, deal with algorithm issues first. Especially, since you already have something that is working. It may be that you are getting killed by overheads. For example, if your situation goes something like Given table of (a, b, x, y, z), select a=1, b=1; then do something with x, y, z; insert it back. select a=1, b=2; then do something with x, y, z; insert it back. ... select a=2, b=1; then do something with x, y, z; insert it back. select a=2, b=2; then do something with x, y, z; insert it back. ... (1 million lines) Then, you have 1e6 x 2 x (connect time, search time, load time, disconnect time) Can you dump the whole thing as text file in one-shot, do whatever with (a,b,x,y,z), and load it back in one-shot? -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From duncan at NOSPAMrcp.co.uk Tue Jul 9 04:16:01 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 08:16:01 +0000 (UTC) Subject: COM client and exceptions References: <01c226c5$ac44d480$d708cb83@hallb.irl.cri.nz> Message-ID: "Blair Hall" wrote in news:01c226c5$ac44d480$d708cb83 at hallb.irl.cri.nz: > For example, using the class defined below, I can write > >>>> xl = Excel('test') > > and then to provoke the problem type > >>>> xl.problem() > > After which Excel does not operate properly. So for example, typing > >>>> xl = Excel("test2") > > does not open Excel properly: only part of the Excel toolbar on screen. > > I am using win95 with the latest version of Python and the windows > extensions. > > What should I be doing to keep Excel happy? > Indeed, where should I be looking (documentation?) > to find out how to write more stable Com-Python code? I haven't tested any of this out with live code, so I could be wrong, but here is what I think is happening: First you create your object and assign it to xl. xl.app holds the COM pointer. When you call problem, a traceback object is created which includes a reference to the xl object. This means that when you overwrite xl with another object, there is still a reference to the original which will not be released (i.e. __del__ is not called) at least until another exception is raised. Even without the exception, by the time __del__ is called, ActiveWorkbook probably refers to the wrong workbook. The most obvious thing to try doing is to stop depending on the implicit call to __del__. I would rewrite your class to have an explicit close method and make sure you call that explicitly whenever you think you have finished with the object. The other thing you might consider would be to hold onto the wb reference so that you can support overlapping lifetimes. class Excel: def __init__(self,filename,visible=1): ... self.wb = wb ... def __del__(self): self.close() def close(self): if sel.app: try: self.wb.Save() del self.wb self.app.Quit() finally: self.app = None And then try: xl = Excel('test') try: xl.problem() finally: xl.close() xl = Excel("test2") -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From nextronix at yahoo.de Wed Jul 31 08:51:26 2002 From: nextronix at yahoo.de (oberon) Date: Wed, 31 Jul 2002 14:51:26 +0200 Subject: small tkinter problem Message-ID: I am quite new to python and especially Tkinter ,i am really stuck on a problem i cannot figure out with this simple seeming interface . I really would apreciate some help ,most likely it is some really stupid mistake ...lol here the full error : Traceback (most recent call last): File "E:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "D:\projects\oberon\mdbapp.py", line 27, in ? root.mainloop() File "D:\projects\oberon\mdbapp.py", line 21, in __init__ self.results = Listbox(frame, yscrollcommand=self.rescroll.set).grid(row=4,column=0,sticky=W+E,columnspan=2) AttributeError: 'NoneType' object has no attribute 'set' ------------------------------------------------------------- #!/usr/bin/env python from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.about = Label(frame,text="something...").grid(row=0,sticky=W+E,columnspan=2) self.title = Entry(frame).grid(row=1,sticky=W+E,columnspan=2,pady=5) self.query_b = Button(frame,text="whatever").grid(row=2,column=0,sticky=W+E,pady=5) self.clear_b = Button(frame,text="Clear results").grid(row=2,column=1,sticky=W+E) self.reslabel = Label(frame,text="Query Results",fg="#009000").grid(row=3,column=0,sticky=W+E,columnspan=2) self.rescroll = Scrollbar(frame).grid(row=4,column=2) self.results = Listbox(frame,yscrollcommand=self.rescroll.set).grid(row=4,column=0,sticky=W+E,columnspan=2) self.rescroll.config(command=self.results.yview) root = Tk() app = App(root) root.mainloop() From cliechti at gmx.net Tue Jul 30 21:06:45 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 03:06:45 +0200 Subject: Newbie question: unexpected diagnostic when subclassing References: <3d472b34$1@news.rivernet.com.au> Message-ID: "Jeff Melvaine" wrote in news:3d472b34$1 at news.rivernet.com.au: > I think I must be doing something basically wrong, but ... ??? > > I'm running Python 2.1 on Windows 98. I create a file x.py in which I > declare > > class x: > ... > > The basic operations of this class work OK. > > I then create a file y.py in which I declare > > class y(x): > ... thats a confusing naming scheme.. usual are words starting with a capital letter for class names. > When I try to create an instance of y, I get the diagnostic > > TypeError: base is not a class instance > > referenced to the definition of class y. In this context, does x really > have to be a variable whose value is an instance of class x? no it should be a class or type (on 2.2). class A: """base class""" class B(A): """subclassing from A""" b = B() #instantiate B if you place them in separate files, you have to import it: import a #load a.py class B(a.A): ... if you use python 2.2, taking built in types as base class it works too (well type names are all lower case, but still name the user class with capitals): class MyFancyList(list): def append(self, item): """a stringifying append""" list.append(self, str(item)) def toString(self, delim = ''): """make a string out of it""" return delim.join(self) ml = MyFancyList() ml.append("hello") ml.append(1) ml.append(2) ml.append(3) print ml.toString() chris -- Chris From BPettersen at NAREX.com Mon Jul 15 13:50:29 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 15 Jul 2002 11:50:29 -0600 Subject: Anyone used WSH for remote scripting on WinXP? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192F1AD90@admin56.narex.com> I've been trying to use Windows Script Host to execute a script on a remote WinXP machine (from a WinXP machine too if that matters). I'd eventually like to run Python scripts but currently I can't get any traction. I can't even get the code at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script5 6/html/wsconrunningscriptsremotelyrunningscriptovertherefromhere.asp to run (even on the local machine). It fails with an error "ActiveX component can't create object" if using VB and an un-named COMException if using Python. I can't figure out which object it is trying to create. MSDN (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script 56/html/vserractivexcomponentcantcreateobject.asp) doesn't seem to give any hint as to how to problem-solve this either... Questions: 1 - Has anyone gotten this to work? 2 - Is there an easier way to execute a script remotely? (security is not an issue this time). 3 - I've got ActivePython 2.2.1 build 222. Do I need to execute win32comext\axscript\client\pyscript_rexec.py (or pyscript.py) on the target machine? I've done so (both of them) on my test systems, but I'm wondering what to tell the sysadmins. This has gotten me quite frustrated, so any help would be greatly appreciated. -- bjorn From email at vtc.ru Tue Jul 2 04:02:09 2002 From: email at vtc.ru (Andrey Koubychev) Date: Tue, 2 Jul 2002 10:02:09 +0200 Subject: Where python especially good ? Message-ID: Hello everyone, What do you think, at what tasks pythons shows great benefits comparing to other script languages ? -- Best regards, Andrey Koubychev From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 09:02:16 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 06:02:16 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> <3D282FF8.6040602@ob_scure.dk> Message-ID: <7x3cuvsnc7.fsf@ruckus.brouhaha.com> Thomas Jensen writes: > Please read my original post again. I merely said, that one of the > design goals was scalability. > The current job takes about 5 hours to complete! Is 5 hours acceptable, if your data doesn't get any bigger? It not, what's the maximum you can accept? > I am absolutely certain that I would be able to write a new job in > any language whatsoever (be it Python, C++ or even *shiver* Basic) > that would complete the job in less than 30 minutes, given the right > DB optimizations and program design. It could be written entirely in > SQL for that matter (which would probably perform rather well!). OK, you're certain you can do it in 30 minutes. Are you certain you CAN'T do it in 5 minutes? If you can do it in 5 minutes, maybe you can stop worrying about scaling. > "Spend your time trying to understand your problem better rather than > throwing fancy technology at it" > > This is exactly what I'm trying to do. Distributed computing is far > from the number one priority in this project! > However, since noone known excactly how much data we will be handling > in a year or two, I have been asked to make sure the job is written in > a scalable manner. In another post you said you wanted to handle 10 times as much data as you currently handle. Now you say it's not known exactly--do you have an idea or not? If it's acceptable for the program to need 3 hours, and you can handle the current data size in 10 minutes, then you can handle 10x the data size with plenty of speed to spare (assuming no seriously-worse-than-linear-time processes). > Once the algoritms and database design has been optimized, there is > still an upper bound as to how much data one CPU can handle, don't you > agree? I think the bottleneck is going to be the database. You might not get better throughput with multiple client CPU's than with just one. If you do, maybe your client application needs more optimization. > I expect it to be much easier to build the job around a distributed > core now, rather than adding support later. First gather some evidence that a distributed client will be better than a single one for large datasets. It could well be that you'll never have reason to add distributed support. What is the application? What is the data and what do you REALLY need to do with it? How much is there ever REALLY likely to be? Is an SQL database even really the best way to store and access it? If there's not multiple processes updating it, maybe you don't need its overhead. Could a 1960's mainframe programmer deal with your problem, and if s/he could deal with it at all, why do you need multiple CPU's when each one is 1000 times faster than the 1960's computer? Inside most complicated programs there's a simple program struggling to get out. From brian at sweetapp.com Mon Jul 8 17:22:10 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 8 Jul 2002 14:22:10 -0700 Subject: Why self? In-Reply-To: <080720021650379803%pecora@anvil.nrl.navy.mil> Message-ID: <001301c226c5$855e7c90$bd5d4540@Dell2> Louis M. Pecora wrote: > > If the explicit self argument were removed, what would you add to the > > language to differentiate between local and instance variables? > > > > Here's a stab. > > (1) All self variables have to be initialized in __init__. That's just > good practice anyway. They are labeled with self in __init__ otherwise > they are local. This would be ugly and slow. The slowness would come from the fact that locally scoped variables could not be identified during compilation. Cheers, Brian From nas at python.ca Tue Jul 16 17:31:25 2002 From: nas at python.ca (Neil Schemenauer) Date: Tue, 16 Jul 2002 14:31:25 -0700 Subject: Dictionaries In-Reply-To: <5.1.1.6.0.20020716180826.00a08690@imap.datacraft.com.br>; from m.laranjeira@datacraft.com.br on Tue, Jul 16, 2002 at 06:15:34PM -0300 References: <20020716085041.A11455@glacier.arctrix.com> <5.1.1.6.0.20020716180826.00a08690@imap.datacraft.com.br> Message-ID: <20020716143125.C12635@glacier.arctrix.com> Marcus Vinicius Laranjeira wrote: > How can I change the order of the items in a dictionary !?!?!? Dictionaries are implemented as hash tables. They do not store entries in sorted order. Maybe you want to use the .sort() method. Eg. >>> d = {'a': 1, 'b': 2, 'c': 3} >>> d.keys() ['a', 'c', 'b'] >>> keys = d.keys() >>> keys.sort() >>> keys ['a', 'b', 'c'] > Thanks a lot, No problem. Neil From gerhard.haering at gmx.de Tue Jul 9 09:13:09 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 15:13:09 +0200 Subject: Converting a hex string to a number In-Reply-To: <0017278C.C22236@smiths-aerospace.com> References: <0017278C.C22236@smiths-aerospace.com> Message-ID: <20020709131309.GC17095@lilith.my-fqdn.de> * Simon.Foster at smiths-aerospace.com [2002-07-09 13:43 +0100]: > > Tal said: > > >Hello, > > I am trying to convert a hex string (for example: "0x12345678") to a > >number (0x12345678 or just 12345678). > > Can you help me please? > >Thanks, Tal. > > eval! > > C:\WINNT\Profiles\syf\Desktop>python > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> string = '0x12345678' string = 'os.unlink(r"c:\boot.ini")' > >>> eval( string ) > 305419896 > >>> Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From rs at onsitetech.com Thu Jul 25 19:24:49 2002 From: rs at onsitetech.com (Robb Shecter) Date: 25 Jul 2002 23:24:49 GMT Subject: Base classes or global functions References: <3D3F37E0.2000209@onsitetech.com> <3D3FC04E.EA6916B6@millfilm.co.uk> Message-ID: <3D4088C0.9040008@onsitetech.com> Eric Texier wrote: > In case of scenari #3, I like personnally the use of staticmethod > > class utilHelper: > ''' some initialization code and variable can happen here when the module > is loaded > ''' > def somefunction(params): > .... > > somefunction = staticmethod(somefunction) > Hmmm... but first I feel like we have to know what the function is about. It'd be easy to put all the functions into a Util class as static methods, but it may not be object oriented. I'm wondering if these functions are part of an actual Class that has as yet not been 'discovered' through analysis. From mcfletch at rogers.com Fri Jul 26 13:32:48 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 26 Jul 2002 13:32:48 -0400 Subject: Years in programming (was Re: __call__ bad style? (was Re: Callable modules?)) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: <3D4187C0.8010706@rogers.com> 20 years, >2/3rds, but 16 of those years I was distracted by growing up. Most heartening comparison: years programming Python : years to do the same work in another language :) Enjoy, Mike Jonathan Hogg wrote: > On 26/7/2002 12:33, in article Ora09.122577$Jj7.2838699 at news1.tin.it, "Alex > Martelli" wrote: > > >>(BTW, I've been programming for over _25_ years now -- more than >>half of my life...). > > > Hmmm... over 18 years, about 2/3rds of my life. Never thought of it that way > before. > > I don't recall ever intending to be a computer programmer... > > Jonathan > -- _______________________________________ Mike C. Fletcher Why, yes, I am looking for a job... http://members.rogers.com/mcfletch/ From Chris.Barker at noaa.gov Mon Jul 1 14:23:31 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Mon, 01 Jul 2002 11:23:31 -0700 Subject: Why the colon? References: <4.3.2.7.2.20020628190712.02450328@mail.gte.net> Message-ID: <3D209E22.22AA6991@noaa.gov> Carel Fellinger wrote: > > Then what am I to make of the colons at the end of lines 1 and > > 2? "Yoo-hoo, interpreter! I'm about to start indenting now!" Hmmm.... > So it's there for the most > Pythonic of all Pythonic virtues: readability. It also makes it easier to write auto-indenting editors, though I'm not sure that's a good excuse. -CHB -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From shalehperry at attbi.com Tue Jul 23 16:28:13 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 13:28:13 -0700 (PDT) Subject: NEWBIE: for statement in "dive into python" gives syntax err In-Reply-To: Message-ID: > > Thanks. I just checked out the doc Whats new in 2.0 and found it. I > didn't think my redhat 7.1 was that old. I'll just upgrade then. RedHat ships tools built with python and they had not moved up to 2.x when 7.1 was released. From spam at ob_scure.dk Sun Jul 7 12:00:34 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 18:00:34 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <3D282413.1010801@ob_scure.dk> Message-ID: <3D2865A2.4010307@ob_scure.dk> Alex Martelli wrote: > It's indeed a wonderful tool for computations on large arrays, vastly > extending Python's applicability to scientific applications. I can't wait to dive into it! > to vote until July 17. If you find Numeric the best thing since > sliced bread, visiting the site and voting for Paul might be a nice > way to signal your appreciation. I will! -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From BPettersen at NAREX.com Fri Jul 12 18:11:09 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 12 Jul 2002 16:11:09 -0600 Subject: Automating MSDEV studio build process Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192F1AD6C@admin56.narex.com> > From: Trent Mick [mailto:trentm at ActiveState.com] > > [Bjorn Pettersen wrote] > > Does anyone have any experience automating a nightly build process > > using Python in combination with MSDevStudio? I remember some > > discussion here about it a while ago, but I couldn't find any > > reference to it through Google... > > You don't need to bother with generating makefiles and > calling nmake. You can just call 'msdev' directly on your > .dsw or .dsp files to build them. > > > H:\>msdev /? [snip] Well, I'll be darned. Who'd have thought ms would have useful command line tools . Thanks for the tip! -- bjorn From duncan at NOSPAMrcp.co.uk Mon Jul 15 04:34:03 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 15 Jul 2002 08:34:03 +0000 (UTC) Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: ppcdev at hotmail.com (ppcdev) wrote in news:2fa5f3a9.0207140808.e4d7d38 at posting.google.com: > i was working on an old pentium II and wanted to send a very long > string in the USER parameter but it made my computer bug.. is it > normal??? > > str='a'; r=range(1024); > for x in r[:]: > str=str+str > > but it even bugs with a value of 512 and 256 for r=range(..) You are doubling the length of the string each time, so with a range of 1024 you are attempting to create a string that is 179769313486231590772930519078902473361797697894230657273430081157732675805 500963132708477322407536021120113879871393357658789768814416622492847430639 474124377767893424865485276302219601246094119453082952085005768838150682342 462881473913110540827237163350510684586298239947245938479716304835356329624 224137216 characters long. Are you sure you have that much memory available? To get a not so long string, just try something like: myString = 'a' * 1024 N.B. It isn't a good idea to call a variable 'str' as you will be hiding the builtin type 'str' which you might also want to use. N.N.B. There wasn't any need to copy the range 'r[:]' before using it in the for loop. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From roy at panix.com Sun Jul 7 23:46:09 2002 From: roy at panix.com (Roy Smith) Date: Sun, 07 Jul 2002 23:46:09 -0400 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> Message-ID: Peter Hansen wrote: > Rename the runTest() > method to start with the text "test", and then change the __main__ > content to be simply 'unittest.main()' instead of the dictEntries.run > that you have. OK, that seemed to work, even though I'm still not sure I understand all the subtleties of what's going on, and what role all the various classes (TestCase, TestSuite, TestResult, TestLoader, etc) play. After writing just a few test cases, I've come to the conclusion that the names of the individual test methods are meaningless, except to dictate what order the tests run in. I've taken to just naming them test101, test102, etc (leaving plenty of room in the numbering system to insert additional tests). The doc strings seem to be the place to get creative, since those are what's printed. I don't see it mentioned in the documentation, but it seems that if you make multiple subclasses of unittest.TestCase, the names of those classes get sorted and run in order as well. So, I'm inclined to adopt the same scheme of just naming the classes class101, etc. From edream at tds.net Wed Jul 10 11:04:02 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 10 Jul 2002 15:04:02 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> Message-ID: <3D2C4CE1.C4E85A07@tds.net> > My suggestion: > > def makeCallback(self, val): > def callback(self=self, val=val): return self.myCallback(val) > return callback > > and then: > > b = Tk.Button(..., command=self.makeCallback(val) ) > > You don't need the default-values trick in Python 2.2 -- so, if > that's what you're using, it would be better to use, instead: > > def makeCallback(self, val): > def callback(): return self.myCallback(val) > return callback I tried this, and indeed this does work on 2.2. Really. Thanks very much. > If you're insistent on using lambda (only sensible reason being that > you made a bet about lambda being used here), you _can_, e.g. in 2.2: > > def makeCallback(self, val): > return lambda: self.myCallback(val) > > but I think the nested-function approach is more readable. This also works on 2.2. This "extra" level of indirection is needed. The following does not work: for val in vals: callback=lambda: self.myCallback(val) # or (val=val) b = Tk.Button(..., command=callback) All the callbacks get bound to a function with the last val in vals. I have no idea why. Maybe you could explain? BTW, the reason I really like Python is that someone like me with limited knowledge can actually produce some real work. Anyway, thanks again for your help! Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From brueckd at tbye.com Sun Jul 21 23:24:26 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sun, 21 Jul 2002 20:24:26 -0700 (PDT) Subject: A better self In-Reply-To: <210720020954312190%pecora@anvil.nrl.navy.mil> Message-ID: On Sun, 21 Jul 2002, Louis M. Pecora wrote: > Yep, did that. I use "_" in place of self. > > >The benefit doesn't depend on your > > coding style that much. If readability is your gripe, change the syntax > > highlighting to make 'self.' be lighter (so it doesn't jump out as much). > > Can't do that on the current IDE. No syntax highlighting. Aha! The real problem comes to light! ;-) A good syntax highlighting editor (IDE or not) will give a bigger boost to code readability than any change the to Python language, but oh well... -Dave From maxm at mxm.dk Thu Jul 18 18:28:25 2002 From: maxm at mxm.dk (Max M) Date: Fri, 19 Jul 2002 00:28:25 +0200 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> Message-ID: <3D374109.1040202@mxm.dk> Tom Loredo wrote: > But the one thing that continues to irk me about the language is "self," > for just the reasons Huaiyu describes. I think non-numerical programmers > are likely not in a position to appreciate the awkwardness of "self..." > in numerical settings, where in a many-variable expression it serves > to hinder understanding (by making the expression very long, often > broken across multiple lines) rather than to enhance it. Yet I think the > general arguments for "self" are strong and valid. Though I often wish there > were something like a "with" statement in such contexts, Huaiyu's > suggestion seems like a reasonable middle ground. I don't especially like "self" myself. But wouldn't it be easy enough to just: class ProjectScheduler: pi = 3.14 def setEstimatedTime(hours): self.estimatedTime = hours def calculateRealisticTime(estimatedTime): # rebinding vars to make the calculation easier on the eye pi = self.pi estimatedTime = self.estimatedTime # the formula realisticTime = estimatedTime * pi # return result return realisticTime regards Max M From david.levy at xrce.xerox.com Mon Jul 22 10:01:49 2002 From: david.levy at xrce.xerox.com (David Levy) Date: Mon, 22 Jul 2002 16:01:49 +0200 Subject: Python UDDI implementation Message-ID: <3D3C104D.1EDB2D48@xrce.xerox.com> I am looking for a Python UDDI implementation. I am willing to collaborate with someone to provide a Python UDDI implementation if none exists. Any information would be appreciated. _____________________________________________________________ David Levy Xerox Research Centre Europe 6, ch. de Maupertuis F - 38240 Meylan Email david.levy at xrce.xerox.com http://www.xrce.xerox.com From emile at fenx.com Thu Jul 4 09:07:55 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 13:07:55 GMT Subject: Meta Line information in Python? References: Message-ID: Tan Woon Kiong > Is there a way to specify meta line information in Python? > > For instance, in C language, this can be done by writing the statement > #line "" > > For example, the following line in a file "el2h.py" > #line 79 "el2h.nw" > means that the next statement comes from line 79 of the file > "el2h.nw". There is no meta (nor macro) ability built into the language, but if you'd really rather have this than using import for library content, it would be straight forward to write one up in python. -- Emile van Sebille emile at fenx.com --------- From ods at fep.ru Mon Jul 15 08:37:58 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Mon, 15 Jul 2002 16:37:58 +0400 (MSD) Subject: objects in a list ... In-Reply-To: Message-ID: On Mon, 15 Jul 2002, Ingo St?cker wrote: IS> I want to create many Objects of a class designed by my own IS> and these objects should be IS> stored/append in/on a list. Is this possible and how can I IS> realize it? Thanx & Sorry for my bas IS> englisch :-) Any object in Python can be stored in list. There is no restriction. -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From aleax at aleax.it Sun Jul 21 13:51:07 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Jul 2002 17:51:07 GMT Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3ACE59.1060004@lmco.com> <3D3AEDD6.78B39D70@engcorp.com> Message-ID: Peter Hansen wrote: ... > When you create an object ("instantiate a class") you > must bind it to a name ("assign it to a variable"). If Normally, yes, but not always. For example, class dispatcher in module asyncore of the standard Python library does not follow this usage mode. Rather, each instance of dispatcher (or a subclass) registers itself in the "socket map", from which asyncore's event loop later decides which callbacks to make as network events happen. Therefore, you often don't bind instances of dispatcher (or rather subclasses thereof) to any name at the time you instantiate them. You just instantiate them and rely on them to enregister so they'll stay alive exactly as long as they need to (such instances remove themselves from the map when they're closed). > the name you use is local to the function, then when > the function exits the binding is removed and the object, > if no other names are by now bound to it, is destroyed. Yes, except that 'names' must be used in a very wide sense here -- e.g., async.dispatcher instances are kept alive by references to them in the socket_map dict, which are "names" only in a very wide sense. More generally: the idiom of a class whose instances automatically enregister themselves somewhere (so the registration itself will keep them alive) is quite important. Tkinter widgets do that, too. Just making sure the _usual_ case (which is the one you describe) isn't confused (by some newbie reader -- I'm sure you don't personally need this reminder, Peter!) with a law of nature:-). Alex From aleax at aleax.it Mon Jul 15 04:28:56 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 15 Jul 2002 10:28:56 +0200 Subject: sorting many arrays from one... In-Reply-To: References: Message-ID: On Monday 15 July 2002 09:47 am, Tim Peters wrote: > [Alex Martelli, on list.sort() special cases] > > > Right. The only extra case I've often wished it handled (defining > > "often" as "more than once":-) is when the FIRST element is out of > > order and all the rest are OK. That happens in mergesorting huge > > streams, > > Is the number of streams also large? Just curious. That strictly depends on the ratio between the size of the "huge" stream, and the amount of physical memory that you can devote to sorting it. It's not easy to pin that down, since it may depend on what else you might like to be doing with the physical memory actually available on your machine! If you're sorting a stream of 4 GB, and would like to avoid taking up more than roughly 16MB to prepare each sorted sub-stream, that's 256 streams, for example. Of course, you could cut the number of streams being merged at one time down to any arbitrary number >= 2, by doing a multipass merge. The "output" stream at any given time is rewinded and becomes an input stream for the next pass; a classic and rather elegant solution. However, single-pass IS substantially faster and simpler, if you can afford it. In real life, it's been quite a while since I had a _substantial_ number of streams being merged in a straight mergesort. However, the same merge logic comes in handy when the pre-sorted streams are generated otherwise, not by splitting-and-sorting an initial huge stream as in real mergesort. > > in the core merge loop: > > > > while streams: > > yield streams[0][0] > > try: > > streams[0][0] = streams[0][2]() > > except StopIteration: > > del streams[0] > > else: > > streams.sort() # this is the first-maybe-OOO sort > > Understood, and that's reasonable. I expect the best a general sort method > can do with this is worst-case N+log2(N) comparisons, give or take 1 or 2, > where N=len(streams), the bulk of that because it has to establish that > only one is out of order (it takes N-1 comparisons just to establish that > an already-sorted list is already sorted). I have in mind a simple way to > achieve that, so hold your breath . Yes, I see your point. I *do* know that streams[1:] IS sorted, while the sort method needs to re-establish this fact each and every time. > By arranging the streams in a min-heap yourself, you can guarantee > worst-case log2(N) comparisons. If the number of streams can be large, > that's a monster-big improvement; it's already a factor-of-3 improvement > over N+log2(N) for N as small as 7. Yes, but the "del streams[0]" ensures I can't do better than O(N) anyway -- for the *general* case of a leg of this loop. However, it's true that the del happens very rarely -- only when a stream finishes, and these streams tend to be quite large. Hmmm... yes, it's probably well worth using a heap. > > The "streams" auxiliary list is originally built from the sequence X > > of already-sorted streams as: > > > > streams = [ [X[i].next(), i, X[i].next] for i in range(len(X)) ] > > Ooh! In 2.3 you'll be able to say > > streams = [[s.next(), i, s.next] for (i, s) in enumerate(X)] > > It grows on you. As I helped Raymond implement the first cut of enumerate (even though I hear that Guido later had to half-redo it:-), I'm reasonably familiar with it -- and it's one of the things I'd love to backport to 2.2.Tie one day:-). But of course I'd never use the redundant parentheses in the for clause of the list comprehension!-) > > Normally N==len(streams) isn't all that big, and I COULD make each > > leg of the "while streams:" loop O(N) anyway by using knowledge > > about _which_ special cases method sort is so good at -- changing > > the else clause into: > > > > else: > > streams.append(streams.pop(0)) > > streams.sort() # the maybe-OOO item is now *LAST*... > > > > but that's not all that pleasant -- I'd do it only in emergencies... > > That would indeed get you out with N+log2(N) comparisons, N of which you > know aren't needed, but which list.sort() can't know aren't needed. If it > is an emergency someday , I'd try > > else: > s = streams.pop(0) > bisect.insort(streams, s) > > instead. The smallest N for which that pays depends on how expensive > element comparisons are, but the crossover point is generally small. The Yep. A "maintain-heap" primitive might be even preferable, if we had it... > main loop can also be recoded naturally with less fiddly chained indexing > then: > > insert = bisect.insort > while streams: > value, i, fetch = streams.pop(0) > yield value > try: > value = fetch() > except StopIteration: > pass > else: > insert(streams, [value, i, fetch]) > > This kind of thing goes faster if streams is made a list of 3-tuples > instead of 3-lists, if you're concerned about micro-optimization here. I wonder (in the micro-optimization hypothesis). All of these tuple packings and unpackings... one thing I've tried is still using indexing, via lists (so I can rebind the value), but via symbols: VALUE, I, FETCH = range(3) while streams: triple = streams.pop(0) yield triple[VALUE] try: triple[VALUE] = triple[FETCH]() &c. Oh well, guess I should measure rather than wondering...:-). Alex From oliver.eichler at dspsolutions.de Wed Jul 17 11:35:35 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Wed, 17 Jul 2002 17:35:35 +0200 Subject: get a list printed in hexadecimal notation In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C8D@hendrix.empolisuk.com> References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C8D@hendrix.empolisuk.com> Message-ID: <200207171735.35328.oliver.eichler@dspsolutions.de> On Wednesday 17 July 2002 14:57, Harvey Thomas wrote: > Oliver Eichler wrote: > > Sent: 17 July 2002 11:08 > > To: python-list at python.org > > Subject: get a list printed in hexadecimal notation > > > > > > Hi > > > > Is it possible to print a mixed list with strings and numbers > > and having the > > numbers printed as hexadecimal notation? > > > > something like: > > >>>l = ('spam',10,15,'more spam') > > >>>print l > > > > ('spam',0xA,0xF,'more spam') > > > > or similar... > > > > The only way I could think of is to write my own print > > function. Is there an > > easy way? > > > > Oliver > > print [type(x) == type(1) and hex(x) or x for x in l] > Groovy, this work! However it will take me the whole afternoon to figure out how ;) Thanks Oliver -- Ingenieure Kellermann, Voigt, Hoepfl, Eichler, Weidner und Klinger DSP Solutions http://www.dspsolutions.de From tismer at tismer.com Mon Jul 1 10:02:22 2002 From: tismer at tismer.com (Christian Tismer) Date: Mon, 01 Jul 2002 16:02:22 +0200 Subject: Ann: Stackless 2.2.1 on PowerPC Message-ID: <3D2060EE.7090101@tismer.com> Announcement: Stackless Python Works on PowerPC. The PPC support was much simpler to implement than expected. It was helpful to look into the PPC switch implementation of the ICON language. Thanks to Just van Rossum for giving me access to his machine. Thanks to Armin Rigo for showing me the tricks for x86-unix. There is still no installer available, this is at alpha level. In case you want to build your own Stackless, check out the module stackless from :pserver:anonymous at tismer.com:/home/cvs Updated news can be found at http://www.stackless.com/ have fun - 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 irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 4 18:11:07 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Fri, 05 Jul 2002 00:11:07 +0200 Subject: sending a file through sockets References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> Message-ID: <3D24C7FB.1090705@NOSPAMREMOVETHISxs4all.nl> Bo M. Maryniuck wrote: > On Thursday 04 July 2002 16:20, Guyon Mor? wrote: > >>------- >>encode some_file.jpg to basecode64 makes: SsDfgFVSFgfsaSZFASasfgAS >>in send it through the socket and decode it back and write it to a file. >>------- >>right? > > > Yup! > Nope. That is totally unnecessary. You can send any string over a socket connection, also the open('somefile').read() string, without having to encode/decode it to some ASCII form. See the other posting in this thread (by brueckd at tbye.com) for more info... Irmen From aleax at aleax.it Fri Jul 26 10:36:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 14:36:58 GMT Subject: Guide to the python interp. source? References: Message-ID: Tim Gahnstr?m /Bladerman wrote: > Hi > <> > Is there a guide or a recomended way to "get to know" the source code to > the python interpreter? Assuming you're familiar with Python's C API (the online docs are good, and you can complement them with e.g. my tutorial on the Europython site, my articles in the "Py" zine, examples on the Cookbook, Bradley's appendix in his "Essential Reference" book, etc, etc), it's not that big a deal. Counting in each case empty and comment lines too, 90k lines are in Modules/*.c -- 90 or so modules with a median of about 600 lines, mostly nice and easy; 39k lines in Objects/*.c, 30 or so objects with a median of about 740 lines, nothing terrible; 3600 in Parser/*c, admittedly nastier but the modules ARE small, median is 153 lines; 26K lines in Python/*.c (net of the dynload* stuff), 42 modules of median 150 lines. There are a few tough places, some of which (e.g. the RE module) you can probably skip, some (Python/compile.c, Python/ceval.c ...) not. Once you ARE familiar with the C API, and thus with the object implementations that after all do follow it, I suggest that for the rest of the core you take a "flow" approach -- how is Python source transformed into execution. I.e., compilation into bytecode, and interpretation of bytecode. Those are nasty, particularly (as of 2.2.1) the compilation. Then you can look at other more marginal nasties such as garbage collection &c. > <> > I am creating a new language and an IDE intended for beginners. This is my > CS master thesis. I plan to use Python as primary language and the Python > interpreter as my interpreter. I will probably need to make quite a few > changes to the the interpreter to make the language behave the way I want, > and I will need to monitor the state of the interperter for debugging > purposes Instrumenting the interpreter to understand what exactly is going on is not hard and does not require complete understanding, indeed doing and examining such instrumentation will HELP you further your understanding. Modification is of course another kettle of fish:-). > <> > Python is, I think, a verry intuitive language for beginners, with some > modifications it can be even better. Especially with a good IDE. That is Two mostly separate issues, I think -- the really good IDE is pretty uncontroversial (if really good:-), the mods WILL get you flames:-). > what I have set out to create. I have designed the language I want to > creat and I have made the first draft of the IDE using Tkinter but I have > a big problem with the python source. It is quite extensive and I am not > one of those people that can have a look at a million lines of code and se It's nowhere like a million lines! 264k overall including ALL the platform-dependent goo you don't AT ALL care about. Given that Modules and Objects are separable, modular and clear, the hard core is just 30k lines or so in Python/*.c and Parser/*.c. > Things I want to change is for example, everything should be "call by > refferense", it shall not by case sensitive, redirect output, better > errormesages, etc, etc. Better error messages would of course be a welcome contribution to Python itself:-). "redirect output" is a mystery -- Python's own output is highly redirectable, what more is needed? Case insensitivity is what gets my personal applause: it's the ONE feature of the language I truly, deeply dislike (just as I dislike it in Unix, XML, C, ...). You're in for substantial work with the *libraries*, I think (not the C-coded ones -- the Python-coded ones). "Call by reference" I gotta see. Just for fun, do it like good old Fortran used to: def inc(x): x = x + 1 inc(2) print 2 should of course print '3'. Anyway, I think that to implement call by reference you will have to touch just about every one of 300 source files. I suggest you consider "value/copy-return" as an alternative: newbies can't tell the difference (except for the performance hit, but in Python, as you'd be copying references, that should be slight) and you could handle it with 1/10th the hassle of pass-by-reference. Basically, you can widen the information in a frame about the arguments, to record the 'sources, thus destinations' of each argument (that's the hard part of course, since you need to make some tough decisions, but still, doable); when you're about to dismantle the frame on exit, copy back the changed value of arguments (selectively, so you don't change the "2", but that's easy). The hard part comes in determining what you want to happen on e.g.: f(x, x.y, x.y.z, x.y.z.t) when f changes its 2nd argument, should that in turn change the 3rd and 4th appropriately and implicitly too? What if some of attributes y, z and t are obtained by __getattr__ or its equivalent? And similar questions for items vs attributes. Algol 60 specified "call by name" -- easiest to explain, hellish to implement when you consider such issues as items, e.g. i = 0 print f("ciao"[i], i) with def f(c, i) i = i + 1 return c should print "i" according to call-by-name semantics. Call by value/copy-return is much easier to implement. Call by reference is a sort of compromise that's more or less inevitable for performance reasons when a language has value (rather than reference) semantics, and indeed that's what Fortran mostly did -- but having reference semantics trying to perch call by reference on top of it seems really precarious. Alex From pete at shinners.org Tue Jul 16 12:27:29 2002 From: pete at shinners.org (Pete Shinners) Date: Tue, 16 Jul 2002 16:27:29 GMT Subject: Being a bit confused after hacking Python References: <3D343DA7.6010309@darkstargames.de> Message-ID: <3D34499C.1040300@shinners.org> Wolfgang Draxinger wrote: > 1st: > It'd be interessting to know, how to prevent scripts to delete > imported modules. My engines load some standard modules into the > interpreter by default. It's not bad when the modules are unloaded and > reloaded, but this means for some modules a huge performance hit. Thats > a bit disturbing in a realtime engine. modules are only imported once. there is always a reference to it in sys.modules. any further calls to import that module just make another reference to the one already imported. even if you "del" the module and reimport it, you are getting the same one back. (i noticed even if you "reload(sys)" you still keep all the modules) > 2nd: > Is there anybody who knows, how to *import* a source module, that may be > compiled already, from contents in memory? My problem is that my engine > has a virtual file system that packs data compresed into packages, to > minimize bandwidth when loading from removeable media. The modules are > contained within such a package and thus cannot be accesed by a normal > operating system file. you'll need to get into the "import hooks". this allows your own code to be called instead of the normal importer. i believe what you do is read the file data in (from your archive), then pass that along to the normal import code. i've never done this though, i don't believe it's hard, but who knows? > 3rd: > There are a few modules, like os or posix, which allow low level access > to the system. Since my engine has network support and the server > provides a remote console that works in python interactive mode, it > would be good to remove some of the builtin modules after Py_Initialize, > that were initialized via _PyImport_Inittab. It would be even possible > to write a virus that distributes within a multiplayer game, if that > access isn't restricted and a new type of virus is definitely what the > targeted users not want. > There must be a official way to remove specific module entries, I think > of the things that rexec can do, but I didn't get out how it does, what > it does. I could of course create a own _PyImport_Inittab and thus just > not initialize the dangerous stuff. Is that a good solution? with rexec you can keep the user from doing many things. you can also replace calls like "open" to map to your own virtual filesystem (which might be useful). there's some pretty good docs on it, but i'm not sure how you would set one up from the "c api". as far as code security goes, i'm not sure how far you'll want to go? if you are running your own code only, perhaps some sort of signatures or checksums to hinder tampering? if you are running 3rd party scripts, there's always a chance someone could do something like "while 1:pass" or try to allocate millions of objects. as for reloading sys resetting stdout, why do you ever need to reload it? if you just want to reset the stdout variables, just set sys.stdout to sys.__stdout__. the __stdout__ is the "original" stdout object. From phr-n2002b at NOSPAMnightsong.com Wed Jul 24 19:46:49 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 24 Jul 2002 16:46:49 -0700 Subject: how to count lines in a file ? References: Message-ID: <7xd6tcn0ye.fsf@ruckus.brouhaha.com> "Delaney, Timothy" writes: > > print len(open('/etc/passwd').readlines()) > > There is currently discussion on python-dev of the file object possibly > becoming collectable by GC (and hence not going away immediately the last > reference you know about disappears). > > Whilst is it *extremely* unlikely that this would be allowed (due to the > preponderance of broken code such as the above) it does point out that such > code is indeed broken. Unfortunately, it's apparently a documented feature that the above is supposed to work, so really it's a unfortunate specification in Python rather than broken code. There's probably no way to fix it now. From loewis at informatik.hu-berlin.de Tue Jul 16 04:30:31 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 16 Jul 2002 10:30:31 +0200 Subject: namespaces in python References: Message-ID: Jeff Davis writes: > Is there a way to put functions and variables in a different namespace > without putting it in a seperate file or instantiating a new object? Certainly. Just bind the function in that other namespace. > Is there a way to have static methods that don't require > instantiating the object first? In Python 2.2, there is the "staticmethod" builtin. For earlier Python versions, it is common to put the static methods next to the class, instead of inside the class. Regards, Martin From mwh at python.net Thu Jul 4 09:24:19 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Jul 2002 13:24:19 GMT Subject: Threads, signals, and fork References: Message-ID: Mark Mitchell writes: > Python 2.2 blocks signals in new threads: > > /* Mask all signals in the current thread before creating the new > * thread. This causes the new thread to start with all signals > * blocked. > */ > sigfillset(&newmask); > SET_THREAD_SIGMASK(SIG_BLOCK, &newmask, &oldmask); > > That means that if the thread calls fork(), all signals are blocked in > the child process. Not if you call fork() from the main thread, I think. > This is not necessarily what the programmer wanted. > > The blocking of signals for new threads is justified in the > documentation for the signal module with the argument that since some > systems do not allow you to send signals to individual threads, Python > doesn't let you do it on any system. I think it's also to get signal handlers to run in the main thread, something Python promises. > That argument is fine as far as it goes -- but since Python doesn't > provide sigprocmask, there's no way to re-enable signals -- even for > child processes. I wrote and checked in a patch that exposed sigprocmask & friends. It behaved bizarrely on *so many* platforms that I disabled the configure check that activates the new code until I work out how to proceed. It's the fact that Python is linked as a multi-threaded program that causes the problems, it seems. See the python-dev archives for me complaining about this quite a bit. Interestingly, the behaviour on FreeBSD was deemed to be a bug in their libc_r, but this only helps people who are running versions of FreeBSD that haven't been released yet... > Thoughts? Signals + threads = pain. Seriously, I think you can get unmasked children by calling fork() in the main thread, but I'm not sure. Maybe you could try that? Cheers, M. -- Need to Know is usually an interesting UK digest of things that happened last week or might happen next week. [...] This week, nothing happened, and we don't care. -- NTK Know, 2000-12-29, http://www.ntk.net/ From gerhard.haering at gmx.de Tue Jul 9 19:04:05 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 9 Jul 2002 23:04:05 GMT Subject: Which OS? References: Message-ID: Tom Harris wrote in comp.lang.python: > Greetings, > > How do I tell which OS is running from within Python? The usual answer is sys.platform, though I wish there was a better one. > [...] This email may contain confidential information. If you have > received this email in error, please delete it immediately, [...] Done. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From shagshag13 at yahoo.fr Thu Jul 25 10:48:00 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 25 Jul 2002 16:48:00 +0200 Subject: how to get a return value from an exception ? References: Message-ID: "Chris Liechti" "Alex Martelli" thanks !!! s13. From markus.vonehr at ipm.fhg.de Fri Jul 26 05:32:11 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Fri, 26 Jul 2002 11:32:11 +0200 Subject: DOS-Shell hangs up, python/Tkinter References: <3D3FBF1A.C1531FB3@ipm.fhg.de> Message-ID: <3D41171B.1F977845@ipm.fhg.de> The problem is that with pythonw I don't get the Debug "prints". Markus Howard Lightstone schrieb: > > Markus von Ehr wrote in > news:3D3FBF1A.C1531FB3 at ipm.fhg.de: > > > Hi, > > > > when I start my python/Tkinter apps out of a MS-DOS shell > > and kill the app, very often the DOS-prompt doesn't come back, > > the Shell hangs-up. > > This is a "known" bug in Tk. > > http://sourceforge.net/tracker/?func=detail&atid=105470&aid=216289& > group_id=5470 > > The workaround: > use pythonw for now........ > From ianb at colorstudy.com Mon Jul 15 17:09:43 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 15 Jul 2002 16:09:43 -0500 Subject: Python's Lisp heritage In-Reply-To: References: Message-ID: <1026767383.703.298.camel@lothlorien.colorstudy.net> On Mon, 2002-07-15 at 15:35, Christopher Browne wrote: > If a new Emacs mode requires adding in a bunch of additional > parameters, dynamic scope lets them be visible throughout the scope > during which they are "live" as opposed to just within the environment > in which they were defined. [snip] > If all you have is lexical scoping, parameters have to get explicitly > passed down the chain in order to get from function A to function C. > That means introducing additional parameters to function B, which > didn't actually care about those extra values. Interesting argument. I think that you can achieve similar results with big state-holding objects (for better or worse). With a web framework, that might be the request object. Or in an editor in might be a buffer object. If you have an object that persists for about the same scope as you need this extended information, you just set an attribute on that new object (or use a mix-in or some other technique). Then, in your extensible application, this object gets passed around (perhaps indirectly) to most functions and methods that would be extensible. This does kind of defeat lexical scoping, though it avoids use of globals. While function signatures don't change, it's at the sacrifice of object interfaces. OTOH, it seems to work okay. -- Ian Bicking Colorstudy Web Development ianb at colorstudy.com http://www.colorstudy.com 4869 N Talman Ave, Chicago, IL 60625 / (773) 275-7241 From rajarshi at presidency.com Thu Jul 4 13:02:29 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Thu, 04 Jul 2002 17:02:29 GMT Subject: testing a sequence for 'identicalness' References: Message-ID: On Thu, 04 Jul 2002 12:43:23 -0400, Emile van Sebille wrote: > Rajarshi Guha >> does anybody knwo how I can check a sequence for 'identical ness', > ie >> given a sequence: >> >> [1,1,1,1,1,1,1,1,1,1] >> >> it would be classified as 100% identical >> >> and >> >> [1,1,1,1,1,1,1,1,1,2] >> >> would be classified as 90% identical. > > >>>> import difflib >>>> l1 = [1,1,1,1,1,1,1,1,1,1] >>>> l2 = [1,1,1,1,1,1,1,1,1,2] >>>> s = difflib.SequenceMatcher(None, l1, l2) s.ratio() > 0.90000000000000002 Thanks! Did'nt know about this module. OK - what if I allow numbers like 1.1 and 1 to be equal (that is numbers which are close are also consdiered to be identical) I'm not really clear on how to set this up in difflib - maybe the bagging idea is a better choice for this problem? TIA, From whisper at oz.net Fri Jul 19 18:44:42 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 19 Jul 2002 15:44:42 -0700 Subject: Python 2.3 In-Reply-To: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: True Division? Darn it, i'm used to false division! Where is "to __past__ deport ..."? ;-) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Rhymes > Sent: Friday, July 19, 2002 14:45 > To: python-list at python.org > Subject: Python 2.3 > > > > When Python 2.3 will be released? > > I've read the "what's new" and i'm waiting generators and true > division :-) > > -- > Rhymes > rhymes at myself.com > " ride or die " > -- > http://mail.python.org/mailman/listinfo/python-list From mnations at airmail.net Tue Jul 23 17:47:28 2002 From: mnations at airmail.net (Marc) Date: 23 Jul 2002 14:47:28 -0700 Subject: Problems with after_cancel() Message-ID: <4378fa6f.0207231347.22cf7e14@posting.google.com> !Sorry if this is a repost. I'm not sure if the original one made it! I have what I think is a very simple after() call and after_cancel combo: ... def check(): print "in check" if globals.stop.isSet(): globals.status.clear() globals.stop.clear() print "Application is stopped" return globals.master.after(100, check) def function(gui): gui.print("do something") id2 = check() print id2 globals.master.after_cancel(id2) print "Should be stopped" ... Check is called to begin the process and returns id2, which should be the id for the after command. When I print the value of id2, I get something like "after#25". But when I do the after_cancel command, it doesn't stop. As far as I can tell, this is the right way to do it, but it's not working. Could someone please tell me what the problem is? Thanks, Marc From comcol at ukmail.com Sun Jul 7 16:20:36 2002 From: comcol at ukmail.com (Comcol) Date: 7 Jul 2002 13:20:36 -0700 Subject: sqlite-python-0.2.0.win32-py2.2.exe fails References: <1b8c5fe1.0207060550.72952217@posting.google.com> <1b8c5fe1.0207070212.679882af@posting.google.com> Message-ID: <1b8c5fe1.0207071220.4d2444ac@posting.google.com> > > installation program. If the distribution had been available as a zip > > file then I would probably be able to install it. > > Nothing's easier that that. > > http://sourceforge.net/project/showfiles.php?group_id=54058 > "c:\python22\python setup.py install" on a command prompt. We have liftoff! Many thanks. From mark.charsley at REMOVE_THIS.radioscape.com Fri Jul 19 12:54:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Fri, 19 Jul 2002 17:54 +0100 (BST) Subject: Dpulicating "class Foo:" in C References: Message-ID: In article , mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote: OK got a little further. The following seems to work fine PyObject* newModule = PyImport_ImportModule("new"); PyObject* new_classobj = PyObject_GetAttrString(newModule,"classobj"); PyObject* args = Py_BuildValue("s(){}","Configure"); PyObject* ConfigClass = PyEval_CallObject(new_classobj,args); However the following crashes nastily whenever I try to do anything with ConfigClass... PyObject* types = PyImport_ImportModule("types"); PyObject* classType = PyObject_GetAttrString(types,"ClassType"); PyObject* ConfigClass = _PyObject_New((PyTypeObject*)classType); Is there any way to create a new Class Object from C without having to call into new.classobj? -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From raimo-news at mail.com Wed Jul 31 08:54:37 2002 From: raimo-news at mail.com (Raimo Tuisku) Date: Wed, 31 Jul 2002 15:54:37 +0300 Subject: Window does not resize it's components Message-ID: I have a couple of widgets in a window(Text and Entry widgets). But their size remain even if the user resizes the window which is not what I want. How can I make them fit precisely in the window borders even if the window is resized? Do I have to fiddle with the signals or what? -- Raimo Tuisku From cjensen at bioeng.ucsd.edu Tue Jul 30 10:11:12 2002 From: cjensen at bioeng.ucsd.edu (Curtis Jensen) Date: Tue, 30 Jul 2002 07:11:12 -0700 Subject: problem recursively removing directories on an NFS mount References: <3D17579F.9030905@bioeng.ucsd.edu> Message-ID: <3D469E80.3000405@bioeng.ucsd.edu> Dr. Marco wrote: > On Mon, 24 Jun 2002 10:32:15 -0700, > Curtis Jensen wrote : > > >>fine. However, sometimes nfs files of the form ".nfs07D7761" get >>created. This causes the os.rmdir( full_name ) command to throw an > > > Such files appear when you remove a remote file that is still opened > by another program. They should disappear when the file is closed. A > solution could be to move them to another directory but I confess I > don't know if this can be done safely. > Thanks for the reply. Unfortunatly, the .nfs files don't appear until after the script starts to remove files. To remove the .nfs file I'd have to loop over the directory listing again in an exception handler. A fix I found was to use "shutil.rmtree" instead of "os.remove" I haven't had any problems with shutil. -- Curtis Jensen cjensen at bioeng.ucsd.edu http://www-bioeng.ucsd.edu/~cjensen/ FAX (425) 740-1451 From tdelaney at avaya.com Tue Jul 23 01:28:35 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 23 Jul 2002 15:28:35 +1000 Subject: distutils cygwin bdist_wininst Message-ID: > From: Delaney, Timothy [mailto:tdelaney at avaya.com] > > python setup.py build --compiler-mingw32 python setup.py build --compiler=mingw32 Tim Delaney From andreas at kostyrka.priv.at Thu Jul 25 09:00:34 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 25 Jul 2002 15:00:34 +0200 Subject: Renting CPU time for a Python script In-Reply-To: <25c15ddd.0207201216.46eddd73@posting.google.com> References: <25c15ddd.0207190852.2aecc26c@posting.google.com> <25c15ddd.0207201216.46eddd73@posting.google.com> Message-ID: <1027602031.8774.89.camel@vaio2> Am Sam, 2002-07-20 um 22.16 schrieb Zachary Bortolot: > Hi Fernando, > > Thanks for your very informative post! Unfortunately the bottleneck > in my program lies with the PIL extension since I have to perform a > lot of putpixel and getpixel operations, which are quite expensive in Well, there are certain Python optimizations you could try: instead of an inner loop like this: for i in xrange(100): img.putpixel((i,i),1) use this: pp=img.putpixel for i in xrange(100): pp((i,i),1) Basically python function calls are painful slow for things like putpixel. Try to move more data per call. Either get your data into python with img.getdata (if I recall correctly) split it up into a list and manipulate it in python, or manipulate the data directly in C. Best regards, Andreas Kostyrka From printers at sendme.cz Mon Jul 29 08:11:28 2002 From: printers at sendme.cz (A) Date: Mon, 29 Jul 2002 14:11:28 +0200 Subject: How to redirect output to browser - second request for help Message-ID: <3D454D10.11064.218373@localhost> Hi, Is it possible to send output continuously to a web browser?. For example I have the following code >>> import httplib >>> h = httplib.HTTP('www.cwi.nl') >>> h.putrequest('GET', '/index.html') >>> h.putheader('Accept', 'text/html') >>> h.putheader('Accept', 'text/plain') >>> h.endheaders() I would like to send coming bytes ( here coming bytes of /index.html file) directly to web browser in the same way as I use a web browser on my computer to open a webpage where I can see a progress how webpage is being opened. In other words I do NOT want to wait for downloading the whole file and only after that open that downloaded file in a web browser. Thank you for help Ladislav From b.maryniuk at forbis.lt Tue Jul 9 09:34:21 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 15:34:21 +0200 Subject: Table Widget (without Installation) In-Reply-To: <3D2AE4D9.3060104@thomas-guettler.de> References: <3D2A9948.5090304@thomas-guettler.de> <3D2AE4D9.3060104@thomas-guettler.de> Message-ID: <200207091534.21993.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 15:27, Thomas Guettler wrote: > wxPython is very nice on win32. I tried once to build the latest > version for linux, but failed. Since I use _German_ SuSE Pro Linux (suitable for you especially), it *really* works. Trust me. -- Sincerely yours, Bogdan M. Maryniuck "sic transit discus mundi" (From the System Administrator's Guide, by Lars Wirzenius) From whisper at oz.net Fri Jul 26 17:50:27 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Jul 2002 14:50:27 -0700 Subject: Two RE proposals In-Reply-To: <15681.49362.442164.660697@12-248-11-90.client.attbi.com> Message-ID: > David> 1. Add a substitution operator - in the example below > it's "!<..>" > > David> word = r"\w*" > David> punct = r"[,.;?]" > David> wordpunct = re.compile(r"!!") > > How about > > word = r"\w*" > punct = r"[,.;?]" > wordpunct = re.compile(r"%(word)s%(punct)s" % locals()) > > which you can do today? (I'd also argue that a word would be "\w+".) I considered something like this, but it's too verbose, not to mention confusing - what's inherently wrong with my idea? I don't think it's counter-pythonic. I also considered the (?P!) construct, but it's on the verbose side too. (I actually need to go read up on this if it's possible to find doc for it - I am not familiar with the idiom of "locals()".) > David> 2. Make r"(a|b)*" mean any number of a's or b's. This doesn't > David> work, at least in some situations with the current > re compiler > David> - the "any" op "*" doesn't seem to span over a parened > David> group. > > The * doesn't (and shouldn't) operate over grouping parens. You're asking > it to supply you with a variable number of groups, which it can't do. You're right - it doesn't operate over grouping parens, but why _shouldn't_ it? IIRC, _some_ regex pacakges could do this... > Besides, what's wrong with r"([ab]*)"? Nothing - unless a or b are more then single charachters or literal strings. Dave LeBlanc From replyonnewsgroup at doit.com Sat Jul 13 00:15:33 2002 From: replyonnewsgroup at doit.com (destr0) Date: Sat, 13 Jul 2002 04:15:33 GMT Subject: hiding command line input Message-ID: <3D2FA84F.7080002@doit.com> Hello, I'm in the habit of using raw_input() for user interaction on the command line. I now have a situation where I need to prompt the user for input on the command line, but I need to get a password from them, so I'd like to hide the display of the letters on the screen. Is there another python function that will get input in the manner raw_input() does, but mask the input from the user, or am I going to have to roll my own function. Thanks!! From b.maryniuk at forbis.lt Tue Jul 23 04:02:51 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 23 Jul 2002 10:02:51 +0200 Subject: ssh and Python In-Reply-To: References: Message-ID: <200207231002.51206.b.maryniuk@forbis.lt> On Monday 22 July 2002 14:28, Erno Kuusela wrote: > unless the administrator has disabled rsa keys That's what I'm talking about. -- Sincerely yours, Bogdan M. Maryniuck A Linux machine! because a 486 is a terrible thing to waste! (By jjs at wintermute.ucr.edu, Joe Sloan) From parker at gol.com Wed Jul 10 05:34:43 2002 From: parker at gol.com (Ian Parker) Date: Wed, 10 Jul 2002 18:34:43 +0900 Subject: How can I retrieve the ID of the last record I added? References: Message-ID: In article , Brian writes >Oops. I just realized you're accessing both MySQL as well as MSSQL. >My comment about @@IDENTITY applies to MSSQL. I haven't been exposed >to MySQL yet. :) On MySQL there's a function LAST_INSERT_ID([expr]) to return the value of the last auto-increment field on that connection. Regards -- Ian Parker From dcinege at psychosis.com Mon Jul 29 10:24:21 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Mon, 29 Jul 2002 10:24:21 -0400 Subject: TAB completion In-Reply-To: References: Message-ID: <200207291024.21112.dcinege@psychosis.com> On Monday 29 July 2002 10:10, Stefan Heimann wrote: > > Ah, ok thanks! I am developing with python 2.1 and this feature of the > cmd class is not available in that version. Hmmm...I don't know. I've only been playing with cmd the last few days, and only with Python2.2. Ahh yes...I'm looking at both now and as of 2.2: 7. If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, endidx. text is string we are matching against, all returned matches must begin with it. line is the current input line (lstripped), begidx and endidx are the beginning and end indexes of the text being matched, which could be used to provide different completion depending upon which position the argument is in. > Is it corrrect, that readline's default filename completion is applied > when the function set with set_completer(completionFun) returns > `None'? You got me. Wrapping readline in python, then in a another class (cmd) is a bit confusing, especially if you're not readline savy (I'm not and don't want to be : >) I'd say get a hold of Python 2.2 and begin reviewing the cmd module itself. -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From markus.vonehr at ipm.fhg.de Thu Jul 4 10:44:13 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 04 Jul 2002 16:44:13 +0200 Subject: sending a file through sockets References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> Message-ID: <3D245F3D.AE5F8E3C@ipm.fhg.de> why not use ftp? "Guyon Mor?e" schrieb: > Who knows how to send and receive a file(binary data) through sockets? > > thanx, > Guyon From pajer at iname.com Wed Jul 24 23:00:06 2002 From: pajer at iname.com (Gary Pajer) Date: Thu, 25 Jul 2002 03:00:06 GMT Subject: Python 2.2.1 Idle can't find _sre (Win98) References: Message-ID: "Tim Peters" wrote in message news:mailman.1027562256.6293.python-list at python.org... > [Gary Pajer] > > I tried to follow the instructions in http://www.python.org/2.2.1/ > > What instructions ? [...] > > crashed with the same error. I found a file called _SED.PYD in the new > > installation, > > There is no such file. Do you mean _SRE.PYD? Even that would be peculiar. > That's the name Wise uses internally for the file, but it should have > changed it to lowercase while installing it. Right. _SRE, not _SED. Just making sure you're paying attention :) But it did unpack in all caps. > if I were you I'd > blow away my Python22 directory and start over from scratch. Or install > 2.2.1 into a different folder. Easy enough. I copied (for safety) a directory of homemade utilities. Then I did an uninstall "custom" and blew away most files and registry entries. Then reinstall, and everything works fine. Thanks very much. From pecora at anvil.nrl.navy.mil Mon Jul 8 14:58:06 2002 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 08 Jul 2002 14:58:06 -0400 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> Message-ID: <080720021458067296%pecora@anvil.nrl.navy.mil> In article <3D29CE9D.4000802 at onsitetech.com>, Robb Shecter wrote: > I completely agree, but I think the situation's even worse than you > described: A'typical' case of standard OO programming is made the most > tedious to write: References to instance variables from methods: > > self.__velocity = self.__factor1 * self.__factor2 > > etc. I find this totally unreadable (7 extra characters per referenced > instance variable). You know, as much as I LOVE Python I got to agree this one bugs me, too. I wish the scoping rules could be changed to default to self first, then local and the rest of the order _without_ the "self." part. Solution? Sometimes I just use the underscore "_" as the self object reference. That shortens the name. You don't have to use the word "self." viz., # Within the object definition, x and z are object variables ... def func(_): y=_.x * _.z return y Not the best solution, but saves typing. From wdraxinger at darkstargames.de Tue Jul 16 11:37:11 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Tue, 16 Jul 2002 17:37:11 +0200 Subject: Being a bit confused after hacking Python Message-ID: <3D343DA7.6010309@darkstargames.de> Within my 3D engine project I decided to choose python for all scripting purposes. It's fast, flexible, you know what I mean. So I embedded it the normal way. It's clear, that I've to redirect a few parts of the builtin module stuff, e.g. sys.stdin/out/err. So I did e.g. PySys_SetObject("stdout", engine_py_stdout); etc. just after PyInitialize(); It works all well until a reload(sys) which is of course the defined behaviour, and restores sys. Since this is not what I want, I hacked a bit the Python sources and found out the following, beginning at void Py_Initialize(void) { /*snipped interpreter initialisation*/ /*Ok here are the Builtin ...*/ bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize __builtin__"); interp->builtins = PyModule_GetDict(bimod); Py_INCREF(interp->builtins); /*... and Sys module initialized, all well so long*/ sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); Py_INCREF(interp->sysdict); _PyImport_FixupExtension("sys", "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); _PyImport_Init(); /*and the rest snipped*/ } It seems at first to me, that PySys and PyBuiltin only get initialized once. Now to the reload process, no wait, the _PyImport_Inittab first: struct _inittab _PyImport_Inittab[] = { /*snipped the obvious stuff*/ /* These entries are here for sys.builtin_module_names */ {"__main__", NULL}, {"__builtin__", NULL}, {"sys", NULL}, {"exceptions", NULL}, /* Sentinel */ {0, 0} }; As we can see, initfunc of the "always there" builtin functions are NULL, hmmm.... now what does reload? It's the function that screws up my config: PyObject * PyImport_ReloadModule(PyObject *m) { /*stuff to find out, if module is loaded already, to reload parent modules and so on, right, snipped */ buf[0] = '\0'; fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp); Py_XDECREF(path); if (fdp == NULL) return NULL; m = load_module(name, fp, buf, fdp->type); if (fp) fclose(fp); return m; } Ok, it just calls load_module, for a builtin with type C_BUILTIN, what does load_module: static PyObject * load_module(char *name, FILE *fp, char *buf, int type) { PyObject *modules; PyObject *m; int err; /*for the moment just the builtin stuff matters*/ case C_BUILTIN: case PY_FROZEN: if (buf != NULL && buf[0] != '\0') name = buf; if (type == C_BUILTIN) err = init_builtin(name); /*here comes error checking not of interesst now*/ } return m; } Ahm, for a builtin it just calls init_builtin(), more hmmm... Have a look at init_builtin(): static int init_builtin(char *name) { struct _inittab *p; if (_PyImport_FindExtension(name, name) != NULL) return 1; for (p = PyImport_Inittab; p->name != NULL; p++) { if (strcmp(name, p->name) == 0) { if (p->initfunc == NULL) { PyErr_Format(PyExc_ImportError, "Cannot re-init internal module %.200s", name); return -1; } if (Py_VerboseFlag) PySys_WriteStderr("import %s # builtin\n", name); (*p->initfunc)(); if (PyErr_Occurred()) return -1; if (_PyImport_FixupExtension(name, name) == NULL) return -1; return 1; } } return 0; } Alright, now is the confusion perfect: If I look at _PyImport_Inittab I see, that sys doesn't define a init function. Other builtins do, and all is clear to me, no problem at all, great. *BUT* what/where the hell is the function that reload sys and invalids my changes I made juat after Py_Initialize, when there is no initfunc that can be called ??? I must have missed something. And now a few other questions: 1st: It'd be interessting to know, how to prevent scripts to delete imported modules. My engines load some standard modules into the interpreter by default. It's not bad when the modules are unloaded and reloaded, but this means for some modules a huge performance hit. Thats a bit disturbing in a realtime engine. 2nd: Is there anybody who knows, how to *import* a source module, that may be compiled already, from contents in memory? My problem is that my engine has a virtual file system that packs data compresed into packages, to minimize bandwidth when loading from removeable media. The modules are contained within such a package and thus cannot be accesed by a normal operating system file. 3rd: There are a few modules, like os or posix, which allow low level access to the system. Since my engine has network support and the server provides a remote console that works in python interactive mode, it would be good to remove some of the builtin modules after Py_Initialize, that were initialized via _PyImport_Inittab. It would be even possible to write a virus that distributes within a multiplayer game, if that access isn't restricted and a new type of virus is definitely what the targeted users not want. There must be a official way to remove specific module entries, I think of the things that rexec can do, but I didn't get out how it does, what it does. I could of course create a own _PyImport_Inittab and thus just not initialize the dangerous stuff. Is that a good solution? Ok, that was now a huge amount of questions, but I hope, that you will find a bit time for them. Thanks in advance -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From markus.vonehr at ipm.fhg.de Mon Jul 22 10:04:13 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 22 Jul 2002 16:04:13 +0200 Subject: set Pmw.EntryField ? Message-ID: <3D3C10DD.A6D472E9@ipm.fhg.de> Hi, in the program (not on init) I want to assign another value to the Pmw.EntryField. How can I do it? Thanks for any comments, Markus From mwh at python.net Wed Jul 17 12:28:10 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 17 Jul 2002 16:28:10 GMT Subject: map del efficiency python2.2 and 2.1 References: Message-ID: John Hunter writes: > Now where do I go to get a deep understanding of my platform's (glibc > 2.2.2) implementation of free and why it behaves so badly? I believe 2.3 will be better here. Not a lot of help, no... Cheers, M. -- The Programmer's Quick Guide To Python (Time Machine version): You try to shoot yourself in the foot, only to realize that there's no need, since Guido thoughtfully shot you in the foot years ago. -- Nick Mathewson, comp.lang.python From jknapka at earthlink.net Mon Jul 8 16:57:52 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Mon, 08 Jul 2002 20:57:52 GMT Subject: Multi-threading on Multi-CPU machines References: Message-ID: <3D29FC43.C239BD5F@earthlink.net> Garry Taylor wrote: > > Hello, > I am attempting to make a multi-threading function in one of my > programs in an effort to gain a speed increase, but I'm getting quite > the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten > me as to why, Yes. CPython threads cannot utilize multiple CPUs, due to the Global Interpreter Lock, which may only be acquired by one thread at a time. Apparently Jython threads do not have this limitation, as the GIL doesn't exist in Jython, or so I'm told. So if you simply ran your program under Jython you might see an improvement. Cheers, -- Joe From whisper at oz.net Mon Jul 29 13:51:35 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 29 Jul 2002 10:51:35 -0700 Subject: Win32 Registry Manipulation w/PythonWin? In-Reply-To: Message-ID: You know you don't need PythonWin to manipulate the registry? You can use the standard Python module __winreg. That module has the following function: DeleteValue(key, value) Removes a named value from a registry key. key is an already open key, or one of the predefined HKEY_* constants. value is a string that identifies the value to remove. Re the constants: probably grep the source Luke :-> David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Tim Daneliuk > Sent: Monday, July 29, 2002 0:10 > To: python-list at python.org > Subject: Re: Win32 Registry Manipulation w/PythonWin? > > > Tim Daneliuk wrote: > > Tim Daneliuk wrote: > > > This is where I run into a problem. I am having a dickens of a time > > figuring > > out how to remove just a single value within a key. I cannot > seem to find > > the magic that allows editing of the lowest level leaf nodes of > a registry > > entry on an individual basis. If I try to treat them as *key* Python > > grumbles > > something to the effect that it cannot find that file at the > OpenKey call. > > If I try to use DeleteValue, I get permission denied even though I am > > running > > with Administrator privileges on a Win2K machine. > > > Never Mind ;-( I just figured out that I was not setting the access > control properly when I opened the key which is what was causing the > access denied error. > > On a related note, where in the docs are values for KEY_READ, KEY_WRITE, > and so forth, defined? I cannot seem to find these... > > > -- > ------------------------------------------------------------------ > ------------ > Tim Daneliuk > tundra at tundraware.com > > -- > http://mail.python.org/mailman/listinfo/python-list From eric.brunel at pragmadev.com Thu Jul 4 04:04:23 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 4 Jul 2002 08:04:23 +0000 Subject: Newbie question on Tkinter References: <2259b0e2.0207030947.4a13834a@posting.google.com> Message-ID: Michele Simionato wrote: > I have found a confusing (to me) behavior of Tkinter in displaying GIF > images. > Consider the following four programs (assuming you have a GIF image > called 'picture.gif' in the current directory): > > #Program 1: works > import Tkinter > root=Tkinter.Tk() > img=Tkinter.PhotoImage(file='picture.gif') > lbl=Tkinter.Label(root,image=img) > lbl.pack() > Tkinter.mainloop() > > #Program 2: doesn't work > import Tkinter > root=Tkinter.Tk() > lbl=Tkinter.Label(root,image=Tkinter.PhotoImage(file='picture.gif')) > lbl.pack() > Tkinter.mainloop() > > #Program 3: doesn't work > import Tkinter > def DisplayPicture(root,picture): > img=Tkinter.PhotoImage(file='picture.gif') > lbl=Tkinter.Label(root,image=img) > lbl.pack() > root=Tkinter.Tk() > DisplayPicture(root,'picture.gif') > Tkinter.mainloop() > > #Program 4: works > import Tkinter > def DisplayPicture(root,picture): > global img > img=Tkinter.PhotoImage(file='picture.gif') > lbl=Tkinter.Label(root,image=img) > lbl.pack() > root=Tkinter.Tk() > DisplayPicture(root,'picture.gif') > Tkinter.mainloop() > > The second program should give the same output of the first one, > however > the first one works, the second one gives a transparent picture! Why > ?? > The only difference is that there is no explicit name for the > PhotoImage object. > Moreover: program 3 has an explicit name for the PhotoImage, but the > picture is still > transparent ! Why ?? By trials, I discovered that it is possible to > fix the problem > at the price of making the PhotoImage name a global variable (see > program 4). You just encountered the weirdest "feature" of Tkinter: it doesn't keep references on images, even if they are used. If you're unfamiliar with the concept of references in Python, you may at first read the corresponding chapter in the reference manual ( http://www.python.org/doc/current/ref/objects.html ). Anyway, here is the explanation of the behaviour you've seen: - your program #1 works because when you start Tkinter mainloop, there is still an explicit reference to your image (the variable "img") - your program #2 does not work because: lbl=Tkinter.Label(root,image=Tkinter.PhotoImage(file='picture.gif')) does *not* keep a reference on the created image. Therefore, just after this statement, the created instance is deleted and can't be used - your program #3 does not work because the only reference you created in your DisplayPicture function (img) was local to the function, so it was discarded at the function return. Since: lbl=Tkinter.Label(root,image=img) does *not* add a reference to the image, again, the picture was deleted at the end of your DisplayPicture function - your program #4 works because since the variable "img" is global, it still exists when Tkinter's mainloop is called, so the image is still referenced and can be used. You may think it's a bug (and I'm personally not convinced that it isn't one...), but it is not considered as a bug by Tkinter designers (see Python FAQ, entry 4.69 at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.069.htp ) > How can I avoid that ? To keep things simple, I'd try to create a sub-class of Tkinter.PhotoImage that remembers its instances: import Tkinter class MyPhotoImage(Tkinter.PhotoImage): instances = [] def __init__(self, *args, **options): apply(Tkinter.PhotoImage.__init__, (self,) + args, options) MyPhotoImage.instances.append(self) Then try: root=Tkinter.Tk() lbl=Tkinter.Label(root,image=MyPhotoImage(file='picture.gif')) lbl.pack() Tkinter.mainloop() and it should work the way you expect. But note that all images you'll create with this class will be remembered, even unused ones. It may eat up memory quite fast if you have lots of images (and/or big ones...). The other solution is to explicitely keep a reference on every image you use, taking care of deleting the reference when the image is not used anymore. > P.S. BTW, how to display jpeg images ? I think PIL can do that, but I'm not sure. See http://www.pythonware.com/products/pil/ HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From matt at mondoinfo.com Wed Jul 17 17:02:41 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Wed, 17 Jul 2002 21:02:41 GMT Subject: hide mouse pointer in Tkinter References: Message-ID: On Wed, 17 Jul 2002 20:41:40 GMT, Douglas Zongker wrote: > How can I hide the mouse pointer in a Tkinter window? The Tk docs > say that cursor "no" is an empty image, but on my system it's a > slash-and-circle icon. I tried using Tk_GetCursorFromData to create > an empty cursor, but this function always fails on Win32. Dear Douglas, The only way I've found is to write the xbm data for a "blank" cursor to a file and set the widget to use that file as a cursor. I'll append a small example. Regards, Matt #!/usr/local/bin/python from Tkinter import * import os kNullCursorData=""" #define t_cur_width 1 #define t_cur_height 1 #define t_cur_x_hot 0 #define t_cur_y_hot 0 static unsigned char t_cur_bits[] = { 0x00}; """ class mainWin: def __init__(self,root): self.root=root # Should clean this up on quit os.umask(0177) # octal f=open("testcursor","w") f.write(kNullCursorData) f.close() self.createWidgets() return None def createWidgets(self): self.t=Text(self.root,bg="white",cursor="@testcursor white") self.t.pack() return None def main(): root=Tk() mainWin(root) root.mainloop() return None if __name__=="__main__": main() From ajs at ix.netcom.com Sun Jul 7 19:48:11 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Sun, 7 Jul 2002 19:48:11 -0400 Subject: Properties - when and why Message-ID: <001d01c22610$f0919480$0334fea9@carol> Learning something about properties - as usual the hard way. Beginning to conclude that they, as I recently learned with __slots__, are more "special case" than I first understood. Say self.W and self.U are each 3 element vectors referenced on initialization, with attributes x,y, z. V is a calculated vector. V=W-U def get_V(self): return self.W-self.U V=properties(get_V) But occasionally I need to access V's attributes individually. def V_homogenous(self): return array((V.x,V.y,V.z,1.)) Have I not just made three calls to the vector subtraction of the get_V method? Not good. Could have done: def get_V(self): self._V = self.W - self.V return self._V def V_homogenous(self): return array((self._V.x,self._V.y,self._V.z,1.)) But now the use of the properties facility seems superfluous and redundant. As a practical matter its self._V, the old style attribute I will be referencing, not self.V, the new style property. Is the when and why of using properties something that can be explained in few enough words? Art From jtk at yahoo.com Tue Jul 30 12:20:48 2002 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Tue, 30 Jul 2002 12:20:48 -0400 Subject: Inheriting module-level attributes, methods in derived module Message-ID: I need to make a product that derives from Formulator (MyFormulator), but allows me to selectively override certain methods. For example, the only thing I need to change in FieldRegistry is the initializeFieldForm() method. The FieldRegistry singleton should be distinct from the original Formulator's one, so I can register a different set of fields. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/formulator/Formulator/ Products\Formulator\FieldRegistry.py ----------------------------------------------- (...) class FieldRegistry: """A registry of fields, maintaining a dictionary with the meta_type of the field classes as key and the field class as values. Updates the Form as necessary as well. """ def __init__(self): """Initializer of FieldRegistry. """ self._fields = {} (...) # initialize registry as a singleton FieldRegistry = FieldRegistry() def initializeFieldForm(field_class): """Initialize the properties (fields and values) on a particular field class. Also add the tales and override methods. (...) ---------------------------------------------- How would be set up? I'm new to all this, and formulator is a complicated heirarchy to begin with. Do I need to derive a new FieldRegistry to modify a module-level method, or to ensure that I have a distinct singleton instance? Products\MyFormulator\FieldRegistry.py ---------------------------------------------- from Products.Formulator.FieldRegistry import FieldRegistry as BaseFieldRegistry class FieldRegistry(BaseFieldRegistry): pass # initialize registry as a singleton - Do I need this? FieldRegistry = FieldRegistry() def initializeFieldForm(field_class): """My new Doc string""" PossiblyCallBaseInitializeFieldForm(() # How do I? Namespace refs this FieldRegistry singleton? (write my own follow-on or complete replacement code here) --------------------------------------------- Gives me errors like: File C:\(...)\Products\MyFormulator\FieldRegistry.py, line 3, in ? TypeError: __init__() takes exactly 1 argument (4 given) Or, an alternate way I was thinking it might need to be: ---------------------------------------------- from Products.Formulator.FieldRegistry import FieldRegistry as BaseFieldRegistry # initialize registry as a singleton FieldRegistry = BaseFieldRegistry.FieldRegistry() def initializeFieldForm(field_class): """Initialize the properties (fields and values) on a particular field class. Also add the tales and override methods. ---------------------------------------------- File C:\(...)\Products\Formulator3\FieldRegistry.py, line 4, in ? AttributeError: FieldRegistry instance has no attribute 'FieldRegistry' I guess I just don't grok module imports yet. Thanks for any advice, I just need to have a few key concepts spelled out for me, and I'll be off and running here. A couple more questions to follow... From dvanpope at bookworm.suffolk.lib.ny.us Tue Jul 9 13:31:32 2002 From: dvanpope at bookworm.suffolk.lib.ny.us (VanPopering) Date: Tue, 09 Jul 2002 17:31:32 GMT Subject: fonts too small Message-ID: I have slackware 8.1 installed and WindowMaker. When I start idle.py the fonts are very small. using rxvt, Xterm, or Nedit the fonts are fine. How can I change the fonts in idle? -- # David # Running Linux I am extraordinarily patient provided I get my own way in the end. From claird at starbase.neosoft.com Thu Jul 11 10:08:50 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 11 Jul 2002 09:08:50 -0500 Subject: Python in the enterprise: Pros and cons References: <3D2D4008.7050207@kyborg.dk> Message-ID: <05FD60A0743FA4C6.2F369710FE5C7A44.D84C92ECE3F9291A@lp.airnews.net> In article , Laura Creighton wrote: >Kim Petersen: > >> >> Learning Python is straight forward, and doesn't scare of a COBOL >> programmer in the way that C++ or Java would. >> > >Is getting a float when they wanted a fixed-decimal a problem? > >Laura Creighton > > It definitely is for many, I can report, and you're quite right to ask. C++, Java, and Python can all define BCD classes, of course. I'd rather not start now with a comparison of how their respective overloading syntaxes make Cobolists (un)comfortable. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From logiplexsoftware at earthlink.net Wed Jul 3 16:16:07 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 13:16:07 -0700 Subject: HT clear some wxPython fram? In-Reply-To: <64SOKICUR2V2X08TPZYOI1ZLF41B6IF.3d234e1c@FRITZweb> References: <20020703114714.47419520.logiplexsoftware@earthlink.net> <64SOKICUR2V2X08TPZYOI1ZLF41B6IF.3d234e1c@FRITZweb> Message-ID: <20020703131607.6b154210.logiplexsoftware@earthlink.net> On Wed, 03 Jul 2002 21:18:52 +0200 Klaus Reinhardt wrote: > Am 03.07.02 20:47:14, schrieb Cliff Wells : > > > >class MyPanel(wxPanel): > > def __init__(self, parent, fontsize = 12): > > wxPanel.__init__(self, parent, -1) > > self.SetBackgroundColour(wxWHITE) > > self.text = [] > > self.fontsize = fontsize > > EVT_PAINT(self, self.OnPaint) > > > > def draw(self, dc): > > dc.Clear() > > font = wxFont(self.fontsize, wxMODERN, wxNORMAL, wxNORMAL) > > dc.SetFont(font) > > y = 0 > > for t in self.text: > > dc.DrawText(t, 0, y) > > y += self.fontsize + 2 > > > --------------------------------------------------------------------- > Hi > > OK! Well done. > > A further problem: The frame is 'renewed' after 14 rows, so the > netstat-output is in the beginning (more than) doubled. Is some sort of - > excuse me - GOTOXY? Or is this another buffer(?)problem? If you look at MyPanel.draw(), you'll see a line like: dc.DrawText(t, x, y) where x, y are the screen coordinates relative to the top-left corner. You could also add a MyPanel.clear() method: class MyPanel(...) ... def clear(self): dc = wxClientDC(self) dc.Clear() It also occurs to me (somewhat belatedly) that wxPython has wxLog that might do what you want without a lot of programming (see the demo - it uses it extensively). Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From talsit at talsit.org Sun Jul 7 01:34:56 2002 From: talsit at talsit.org (tALSit) Date: Sun, 7 Jul 2002 15:34:56 +1000 Subject: Total python embedding in a c/c++ app Message-ID: <3d27c9f9@dnews.tpgi.com.au> Hi, I'm trying to turn python into a full embedded scripting system for my games engine, and I'm looking a different approaches to do it. One such approach would be to expose the full c++ to python (well, the important things), and have a class such as cMain which starts up everything, and have a python script that generates calls that. Another approach would be to startup the python system with in my program and have it call whatever scripts necesarry. I like this approach better, but it requires the use of the functions PyRun_* which take a FILE* of the console and I don't know how to obtain that. Any help on this would be appreciated. Damm... I'm just reading this email, and I realise that it makes very little sense. Anyway, anyone that has totally embedded python into their system, I would be extreemly gratefull to know how they went about doing it, thanks! From mhammond at skippinet.com.au Thu Jul 18 18:40:27 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 18 Jul 2002 22:40:27 GMT Subject: Help with win32ui.CreateFileDialog References: <3D36C23D.A487E18A@gmx.de> Message-ID: <3D3743DB.2080109@skippinet.com.au> Dr. Thomas H?bner wrote: > Hi, > > I am running into a problem with win32ui.CreateFileDialog during the > selection of multiple files. I am successful in selecting files only up > to a certain number. The number depends on the length of the path, e.g. > selecting files from "E:\Dokumente und Einstellungen\thomas\Eigene > Dateien\GP\kunden\tracker\" works up to 7 file, doing the same for > "E:\temp" doesn't break until 10+ files. Unfortunately, your code looks fine. I checked the win32ui code and it is not making any size assumptions, so I fear the limitation is in MFC itself. I don't really have the time to check this out, but as the complete source code is available to win32ui and MFC itself, it should not be too hard to track down. Mark. From chris.gonnerman at newcenturycomputers.net Tue Jul 30 11:37:59 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 30 Jul 2002 10:37:59 CDT Subject: Check undefined variable In-Reply-To: <3d46afca$1_2@hpb10302.boi.hp.com> Message-ID: <200207301623.LAA26439@paris.k12.mo.us> On Tue, 30 Jul 2002 09:24:57 -0600, Daniel Fackrell wrote: > "Michael Grabietz" wrote in message > news:3D46AD2E.709 at img-online.de... > > how is it possible to check whether a variable 'a' is undefined or not. > > > > e.g.: > > > > if a==NULL : # something like that > > print 'a is undefined !' > > else > > print 'a already undefined !' > > try: > type(A) > print 'A exists' > except NameError: > print 'A doesn't exist' Actually this works: try: A print "A exists" except NameError: print "A doesn't exist" in other words, just call out the name and see if it answers :-) From tdelaney at avaya.com Sun Jul 14 19:48:46 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 15 Jul 2002 09:48:46 +1000 Subject: isA function? Message-ID: > From: Roy Smith [mailto:roy at panix.com] > > Still, I think it's a reasonable thing to do in a unit test > environment. What would be more useful though is to simply try to use the functionality. If it works, why is there a need for it to be a particular type? If an attribute is missing, the unit test will fail. If the semantics are wrong, and it passes, the unit test needs an additional case added. I actually think that (in Python at least) asserting that something is a particular type in a unit test is probably the *worst* place to do it. If you just rely on behaviour in the unit test, you can point to the test and say "anything that passes this (fulfils the contract) is acceptable". Tim Delaney From mwh at python.net Tue Jul 30 05:25:53 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 09:25:53 GMT Subject: [ZOPE] Zope, Python, Win2k and Mysql References: <4a4akukkfg92po76t3svc7flen29s3stui@4ax.com> Message-ID: Gerhard H?ring writes: > No, Zope _requires_ Python 2.1.x. I think the latest release unofficially works on 221. Not sure, though. Cheers, M. -- Clue: You've got the appropriate amount of hostility for the Monastery, however you are metaphorically getting out of the safari jeep and kicking the lions. -- coonec -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From aleax at aleax.it Fri Jul 12 17:51:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 21:51:58 GMT Subject: switch recipe? References: Message-ID: <2cIX8.74333$vm5.2697823@news2.tin.it> Mark McEahern wrote: >> or possibly: >> >> def make_switch(*args): >> """Return a generator that loops through args.""" >> if not args: >> raise RuntimeError("Missing parameter: args.") >> def switch(): >> while True: >> for a in args: >> yield a >> return switch > > Holy cow, that's much nicer! Wouldn't you get exactly the same observable effect from the simpler function: def make_switch(*args): """Return an iterator that loops through args.""" if not args: raise RuntimeError("Missing parameter: args.") return iter(args) ...? Alex From tim.one at comcast.net Thu Jul 25 22:14:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 25 Jul 2002 22:14:12 -0400 Subject: Speed up Python by up to 5% ? In-Reply-To: <15Y%8.25161$fH5.25088525@kent.svc.tds.net> Message-ID: [Edward K. Ream] > ... > Among other things, this has saved me the trouble of suggesting that > SET_LINENO opcodes be "optimized." As was mentioned, it *would* be a worthwhile optimization to get rid of SET_LINENO completely. The "periodic checks" code is a heartbreaking little drag on performance, but nobody yet has dreamed up an acceptable (bulletproof, and portable across OSes & C compilers) way to get that test + taken-branch off the eval loop's critical path. From bokr at oz.net Mon Jul 15 15:55:09 2002 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2002 19:55:09 GMT Subject: Write \x1a to binary file References: Message-ID: On Mon, 15 Jul 2002 16:37:07 +0200, "Harald Schneider" wrote: >Hi, > >I've got a problem with writing "\x1A" to a binary file on Win32 platform. >I think due tue an issue wiht popen() this terminates the output stream. Is >there any solution for this ? > Why are you using popen? Why not Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f=file('x1a_test.txt','wb') >>> f.write('The character in square brackets should be \\x1A: [\x1A]\r\n') >>> f.close() We can verify the result. >>> f=file('x1a_test.txt','rb') >>> s=f.read() >>> s 'The character in square brackets should be \\x1A: [\x1a]\r\n' >>> print s The character in square brackets should be \x1A: [?] >>> s.find('[') 49 >>> s[50] '\x1a' (On the console window (NT4) the character in square brackets above renders as a right arrow. Pasted into my newsreader is shows as a question mark). Note the 'b' in the mode, necessary for windows. Otherwise, if we read the file we just wrote, we get : >>> f=file('x1a_test.txt','r') >>> s=f.read() >>> s 'The character in square brackets should be \\x1A: [' >>> print s The character in square brackets should be \x1A: [ >>> s.find('[') 49 >>> s[50] Traceback (most recent call last): File "", line 1, in ? IndexError: string index out of range I.e., '\x1a' is Ctrl-Z which is EOF in windows text mode. Just to complete the picture, note what happens if we write without the 'b' and read its binary data with 'rb': >>> f=file('x1a_test.txt','w') >>> f.write('The character in square brackets should be \\x1A: [\x1A]\r\n') >>> f.close() >>> f=file('x1a_test.txt','rb') >>> s=f.read() >>> s 'The character in square brackets should be \\x1A: [\x1a]\r\r\n' >>> print s The character in square brackets should be \x1A: [?] >>> s.find('[') 49 >>> s[50] '\x1a' It looks like the only cooking that was done was to change \n to \r\n for windows (thus getting the \r\r\n, since \r was alrady there), but the \x1a was apparently ignored and passed though in writing the output. Regards, Bengt Richter From bokr at oz.net Thu Jul 25 17:52:08 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 21:52:08 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: On Thu, 25 Jul 2002 08:52:53 GMT, Alex Martelli wrote: [...] > >f.readline(N) may return a partial, incomplete line if >that's the best it can do without exceedinng N bytes. > >Docs for f.readlines(N) are not quite as clear on this >point, but it seems that readlines is NOT allowed to >return incomplete lines -- rather it should return more >than N bytes (as it's explicitly allowed to) if needed. > That bothers me. ISTM it should return as many lines as will fit in N bytes, but no more. Otherwise you have no memory use protection against a single monster line, and isn't capping memory use what N is about? Otherwise N should be lines, not bytes. I don't think it should be an insurmountable problem to do the requisite buffering of starts of last lines not fitting in N and feed them to the next readlines(). >That's definitely what the current implementation does. > Boo ;-) >Module xreadlines (and thus f.xreadlines, which is >explicitly documented as being equivalent to a call to >xreadlines.xreadlines(f)) uses f.readlines(N) (both by >the docs, and by the implementation). > Booboo, ISTM ;-) Regards, Bengt Richter From b.maryniuk at forbis.lt Tue Jul 30 03:54:50 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 30 Jul 2002 09:54:50 +0200 Subject: Python script that writes to an Excel file In-Reply-To: References: <67f6bbe5.0207270544.696f6076@posting.google.com> <3D45894A.2090406@motorola.com> Message-ID: <200207300954.50594.b.maryniuk@forbis.lt> On Tuesday 30 July 2002 01:17, Neil Hodgson wrote: > Recent versions of Excel can use an XML based file format. Yes, Microshaft all the time borrows good things from the OpenSource and claims theirs own property. Hopefully they will change Excel's XML format in second Excel release as they always doing such things... :-) -- Sincerely yours, Bogdan M. Maryniuck Linux is obsolete (Andrew Tanenbaum) From mhammond at skippinet.com.au Sat Jul 27 22:04:27 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 28 Jul 2002 02:04:27 GMT Subject: global param to exec (on win32) References: <1027710735.14561.0.nnrp-07.3e314eb6@news.demon.co.uk> Message-ID: <3D43514E.1030609@skippinet.com.au> david evans wrote: > I'm using win32 and I can't work out how "globals()" and the global param to > "exec" relate to each other > > I'll be really grateful if anybody takes time to read to the end of this > rather long description of my problem ... > (thanks again if you got this far!) IT is a little too long. Try posting the smallest complete code sample that demonstrates the problem, including any tracebacks etc seem. Thanks, Mark. From max at alcyone.com Mon Jul 22 01:14:25 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 21 Jul 2002 22:14:25 -0700 Subject: ANN: cage 1.1 -- Cellular automata engine in Python Message-ID: <3D3B94B1.F12E4A9C@alcyone.com> A new version of CAGE is available: http://www.alcyone.com/pyos/cage/ Summary CAGE is a fairy generic and complete cellular automaton simulation engine in Python. It supports both 1D and 2D automata, a variety of prepackaged rules, and the concept of "agents" which can move about independently on the map for implementing agent behavior. CAGE comes with numerous examples of fully-functional CA systems, including Conway's Game of Life, Langton's self-reproducing automaton, Langton's "vants," and 1D automata rule explorers. It also comes with simple displayers (including a curses interface for 2D automata). Also included is a unique implementation of a finite state machine (ant.py). Note that CAGE is implemented entirely in Python, and due to its very generalized nature, is not designed for speed. It is sufficient to update a 80x24 Conway's Game of Life grid at a few times per second on a modern machine. CAGE is intended primarily as an education toolkit, rather than an industrial-strength CA simulator. Getting the software The software is available in a tarball here: http://www.alcyone.com/pyos/cage/cage-1.1.tar.gz. The official URL for this Web site is http://www.alcyone.com/pyos/cage/. What's new - 1.1; 2002 Jul 21. More examples, much better abstraction of dimensionality, PointInitializers, simple ImagePlayer (using PIL) and rule 110 example, concept of Rule mixins, 1D nontotalistic and totalistic rule examples, separation of concept of "icon" from Automaton classes. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From whisper at oz.net Wed Jul 10 13:55:07 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 10:55:07 -0700 Subject: Win32 Registry Manipulation w/PythonWin? In-Reply-To: Message-ID: Also (/pythondoc/lib/module--winreg.html): 22.2 _winreg - Windows registry access Availability: Windows. New in version 2.0. These functions expose the Windows registry API to Python. Instead of using an integer as the registry handle, a handle object is used to ensure that the handles are closed correctly, even if the programmer neglects to explicitly close them. What he wants are examples of how to muddle with the registry. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Matthias Huening > Sent: Wednesday, July 10, 2002 2:19 > To: python-list at python.org > Subject: Re: Win32 Registry Manipulation w/PythonWin? > > > Tim Daneliuk wrote in > news:qmqgga.g31.ln at eskimo.tundraware.com: > > > Does some kind soul out there happen to have a pointer to a > > tutorial/examples on fiddling with the Win32 registry from PythonWin? > > > > There is a module called pyRegistry. Can't find the url right now, but > you can get it from ActivState: > http://aspn.activestate.com/ASPN/Modules/Python/dist_html?dist_id=11218 > > Matthias > -- > http://mail.python.org/mailman/listinfo/python-list From aleax at aleax.it Fri Jul 26 15:26:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 19:26:21 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: Britt A. Green wrote: > So I know what lambda functions are, they're syntax and how they're used. > However I'm not sure *why* one would use a lambda function. What's the No idea, really. Maybe something to do with shocks in one's childhood. > advantage that they offer over a regular function? Well, they do look more mysterious and arcane, and therefore, maybe, make their proponents believe they're k00l. With a lambda you can keep a function anonymous, which must have something of the same attraction as writing anonymous letters. You can also squish a lot of them together in weird ways to take advantage of the fact that a lambda form is an expression. k00l, innit? Normal functions are clear, simple, understandable, and regular, therefore intolerably middle-class, ordinary, bourgeois, mundane. And they can take up a WHOLE extra line, or *more*!!!, which is obviously appalling waste of, well, of something or other, for sure. Alex From nika at kassube.de Sat Jul 20 13:52:39 2002 From: nika at kassube.de (Nils Kassube) Date: Sat, 20 Jul 2002 19:52:39 +0200 Subject: Setting the right border in PythonWin IDE Message-ID: <817kjqi8wo.fsf@darwin.lan.kassube.de> Guten Abend. How do I set the right text border/margin in the PythonWin IDE shell from ActivePython 2.2.1? If I try e.g. dir(sys) the resulting list is annoyingly displayed on a single line. I've tried playing with the settings like e.g. right edge mode in View/Options... but nothing seems to wrap text on a new line after a certain number of characters. Danke im voraus, Nils From curt at journyx.com Mon Jul 8 19:18:03 2002 From: curt at journyx.com (curt finch) Date: 8 Jul 2002 16:18:03 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) Message-ID: <96c7f32.0207081518.52ea644a@posting.google.com> Our free web timesheet app is written totally in Python. One of our competitors is saying the following things about python to our customers. Help me make them look stupid. Please? ps. enjoy our free stuff at http://pnk.com/wt3.html thanx for any comments you can provide -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Summary Python is often used as pseudocode to conduct rapid development. Its major users are web sites that do not reuse code and often conduct “throw away” development to meet internet development time tables. It is a very new language and has very little support compared to the Java development community. It is also not J2EE compliant. Platform Drawbacks As a new relatively untested development platform in the licensed software community, Python has certain deficiencies with which all users and developers should be aware. Issues and concerns ? No integrated GUI (Graphic user interface) support. ? No compiler to the native code. ? No automatic garbage collection. ? Does not have vast number of libraries as that of Java, Perl, C++; etc. ? Since Python is an interpreted language, it requires frequent run-time checks and thus does not provide the speed, performance and efficiency of compiled languages like Java, Perl and C++, which is a major issue. ? Python does not provide multiple ways to perform tasks as do most other languages. ? It takes a lot of time for Python to adjust to the indentation style of the structuring code. ? Since Python is relatively a new language, there are only a few resources available for information on its latest developments. ? Limited documentation- only two English language books exist which provide tutorials or a library reference for Python. ? The language is restricted to fewer code modules. ? Lacks native threading capabilities. ? Lacks basic tools such as integrated source level debuggers. ? No packaging methods for software distribution. ? Lacks tools to solve typographical and type mismatch classes of errors. ? Python cannot write docstrings in C++. ? Python is difficult to read. ? Dynamic loading is not available on all systems, requiring that a developer use static loading. Application Areas ? Prototyping and development ? Platform independent graphic user interface applications ? Internet scripting/applications ? Automated test harnesses ? System administration applications ? Shell scripting/OS Scripting ? Text processing ? Database Interfaces ? Application Extensions ? Distributed Programming Python users ? Yahoo ? Infoseek From aleax at aleax.it Tue Jul 16 09:43:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 16 Jul 2002 13:43:12 GMT Subject: switch recipe? References: Message-ID: Mark McEahern wrote: > [Alex Martelli] >> I'm not sure what an lcd is in this context, but I did mean to >> loop least-common-multiple(m, n) times, treating the two sets >> as equivalent. So I guess I had misunderstood the specs! > > I seem to have a penchant for maligning concepts. Thanks for the > correction > on denominator --> multiple. Would it make sense to say lcd (least common > denominator) is a conceptual subset of lcm (least common multiple)? If Hmmm, the lcd of minimal-terms fractions A and B is the lcm of A's denominator and B's denominator, right? Guess it IS a "conceptual subclass" in that you have to add the concepts of denominator and minimal-terms:-). Alex From michael.melchert at ntlworld.com Fri Jul 12 15:13:25 2002 From: michael.melchert at ntlworld.com (Michael Melchert) Date: Fri, 12 Jul 2002 20:13:25 +0100 Subject: Linking to Python 2.2 References: Message-ID: Nathan Cassano wrote: > gcc -g -O2 -o program main.o -Xlinker --export-dynamic -Wl,-E > -L/usr/lib/python2.2/config -lpython2.2 -ldl -lpthread -lutil > gcc -g -O2 -o program main.o -Xlinker --export-dynamic -Wl,-E -L/usr/lib/python2.2/config -lpython2.2 -ldl -lpthread -lutil -lm ;-) enjoy From mwh at python.net Mon Jul 29 07:00:50 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Jul 2002 11:00:50 GMT Subject: order of test References: Message-ID: Andrew McNamara writes: > >can we be sure of the order of a test expression ? > >i mean that > >t=["one","two"] > >x=10 > >if x<2 and t[x]=="oups": > > > >will never throw an exception if t[2] will be tested before x<2 > > It's called lazy evaluation, No it's not! Lazy evaluation is more like Haskell... > and python shares this trait with C. This much is true. Cheers, M. -- CLiki pages can be edited by anybody at any time. Imagine the most fearsomely comprehensive legal disclaimer you have ever seen, and double it -- http://ww.telent.net/cliki/index From wilk-spamout at flibuste.net Fri Jul 19 05:51:44 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Fri, 19 Jul 2002 11:51:44 +0200 Subject: Do GUIs for DBs exist? References: Message-ID: <20020719115144.52444c78.wilk-spamout@flibuste.net> Le Fri, 19 Jul 2002 11:01:01 +0100 "Fran?ois Lepoutrre" ?crivait: > > the other day, and I was thinking: hey, wouldn't it be > > great if it had a GUI like MSAccess > > Sure i'd like to hear about people delivering apps > such as the ones you can create with ms-access. > > My understanding is that python is a wonderfull clean > environment to deliver pretty server-side servlets and > calculation-intensive apps of all kinds. > > "Data-and-ui" -intensive apps are still very much of > a a win32 specialty with (not looking for flame here...) > vb6, vc, delphi, vfp and others. > > Python is possibly still missing the kind of data-driven > environment that you find in products such as ms access, > dbase, foxpro, paradox and other stuff. > > Being an occasionnal user of those products i doubt that > these products could be replicabled in a python world > as they imply an intimate coupling between > the db-engine (generally a local one), a set of native > data-aware components and a scripting environment. > > What would be welcome is some kind of generic model > for data-aware wxpython components including > dynamic data-grids, combos and others. > > Anyone working on this? Yes i do. I did something in java and php (finish and working) and now i rewrite it in python. My goal is to do thinks like that : a class RecordSet from an sql query contain a list of Row contain a list of Field. Each field can be a subclass of standard field to do special thinks when the value change etc... class Person(Row): ... person=Person() person.readId(5) print person.name.value() print person.telephon.value() After i can do this : FormField : a wxpython control for the field of the row FormRow : a wxpython frame with all the control of the row and button to record GridRecordSet : a wxpython frame with a grid and the same for printing in pdf with reportlab or export I also whant to use the same class for html form in cgi Ask me if you whant to know more about it, it's in early stage, but very promissing when i compare it to what i did in java. bye > > > > -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From cliechti at gmx.net Wed Jul 3 19:46:37 2002 From: cliechti at gmx.net (Chris Liechti) Date: 4 Jul 2002 01:46:37 +0200 Subject: PythonWin + other GUIs = CRASH! References: <3D232FEE.3010606@gmx.de> Message-ID: Chris Liechti wrote in news:Xns9240EF2F33EBcliechtigmxnet at 62.2.16.82: > Ingo Linkweiler wrote in > news:3D232FEE.3010606 at gmx.de: >> when using the PythonWin IDE with other GUI-Toolkits (Qt, wxPython, >> Pygame), the application crashes or freezes when running them with >> "file->run". >> >> Is it possible to avoid this? > > yes! with my PythonWin patch that runs the script in a separate process. > > watch this space for an annoucement, when i put it on my homepage. i have just put it here: http://www.geocities.com/chrisliechti/en/python/runext.html viel spass chris -- Chris From vvainio at tp.spt.fi Mon Jul 1 03:00:13 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 1 Jul 2002 00:00:13 -0700 Subject: pprinting generators References: Message-ID: "Steve Holden" wrote in message news:... > It wouldn't be very helpful of pprint to exhaust the generator so you > couldn't access the values, would it? What if the generator were infinite? The pattern I use pprint (in writing scrip/batch-oriented apps): 1. Write code to produce a huge data structure. 2. pprint the data structure, analyze, comment out pprint. 3. write code to act according to the data structure. So I didn't realize some people actually *leave* those pprints in place :). I understand consuming the data structure might be a slightly unwanted side effect for just printing it for viewing. Contraty to popular belief, I was not smoking crack at the time of original posting. -- Ville From trentm at ActiveState.com Fri Jul 5 04:47:03 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 5 Jul 2002 01:47:03 -0700 Subject: ANN: 'go' v0.6.3 - quick directory changing Message-ID: <20020705014703.A5086@ActiveState.com> Where? http://starship.python.net/~tmick/ What is 'go'? 'go' is a simple command line application to help you change directories in your shell session quickly. Generally you have a set of directories that you commonly visit. Typing these paths in full, even given tab completion, can be a pain. This script allows one to define a set of directory shortcuts to be able to quickly change to them. For example, I could define 'apy' to represent "D:\trentm\main\Apps\ActivePython", then C:\> go apy D:\trentm\main\Apps\ActivePython> and C:\> go apy/test D:\trentm\main\Apps\ActivePython\test> Some standard shortcuts, such as '~' for $HOME, are setup. What platforms? Windows and Linux. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From oren-py-l at hishome.net Sat Jul 6 00:00:00 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 6 Jul 2002 00:00:00 -0400 Subject: idiots guide to python In-Reply-To: <626290cd.0207051529.518f4ce7@posting.google.com> References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: <20020706040000.GA70921@hishome.net> On Fri, Jul 05, 2002 at 04:29:48PM -0700, Mike Johnson wrote: > I am starting an A-Level course in computing in september, and i will > need to learn how to use python. I have no previous experience of > programming, but could anyone point me in the direction of an "Idiots > Guide"? I see you already got a few answers. I was just wondering - who is giving this course? I believe Python is an excellent first language to learn and it's nice to see that beginner courses are using Python. Oren From tdelaney at avaya.com Mon Jul 1 03:01:13 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 1 Jul 2002 17:01:13 +1000 Subject: calling a java app from python Message-ID: > From: Anoop P B [mailto:anoop79 at myrealbox.com] > > is there no way of doing this cross-platform? > > Can someone please throw some light on possible solutions to this > problem. My ultimate aim is only to run the java program through my > python script. However, I cannot use os.system() since my > python program > gets blocked which is not acceptable. I need my python script to call > the java program and continue executing. > > note: the java class is in the same directory in which my > python script lies http://www.jython.org/ // TestJava.java public class TestJava { public static final void main (String[] args ) { System.out.println("TestClass.main()"); for (int i = 0; i < args.length; i++) { try { Thread.currentThread().sleep(0); } catch (InterruptedException ix ) { } System.out.println(" " + args[i]); } } } # TestPy.py import threading import time import TestJava t = threading.Thread(None, TestJava.main, None, (['1', '2', '3',],)) t.start() print 'TestPy' for c in 'abcdef': time.sleep(0) print ' %s' % (c,) t.join() Tim Delaney From jonathan at onegoodidea.com Wed Jul 24 12:03:38 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 24 Jul 2002 17:03:38 +0100 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3E9BCF.90806@mxm.dk> Message-ID: On 24/7/2002 13:29, in article R4x%8.131291$vm5.4322201 at news2.tin.it, "Alex Martelli" wrote: > It's because of a dislike of *language rules that don't carry their > own weight* in general. The more rules a language has, the more > complicated it is. Python is not complicated, but it could be > even simpler if it were possible to remove all of the deadwood, > and I include __call__ in that category. I'm not sure I'm with you here. I find this aspect of Python to be quite simple: everything is an object, and there is a mechanism supplied to redefine each of the behaviours of an object through a special method. To remove __call__ would invalidate that, such that there would be one behaviour of an object that is suddenly reserved and not redefinable. This would mean that implementing new callable types would only be possible through the C interface. I think Python would lose tremendously by such a move. A bound method is just one kind of callable object, along with functions, classes, metaclasses, classmethods and staticmethods. Without __call__ one would need to bend one of these existing objects to create a callable objects. But then you lose the ability to redefine other behaviours. For example, there is no way of redefining the 'repr' of a function, or the attribute interface. Without __call__ the closest I could come would be to define a metaclass that creates class objects with a __new__ method implementing the call interface - a truly monstrous idea. Jonathan From krissepu at vip.fi Tue Jul 2 09:51:13 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Tue, 02 Jul 2002 16:51:13 +0300 Subject: Useful RE patterns References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> Message-ID: <3D21AFD1.A204CADF@vip.fi> I would make the following changes to sre: 1) findall() does not return empty matches 2) function to return nested structures .ie. recursive decent parser. Have a look of egenix's mail list on June -pekka- Michael Hudson wrote: > Norman Shelley writes: > > > Fredrik Lundh wrote: > > > > > ... > > > If I were to add a dozen (or so) patterns to the (S)RE module, > > > what should I pick? What patterns do you find yourself using > > > over and over again? > > > > All kinds of numerics, e.g. scientific (1e-6, 2e6, ...) and engineering (1u, > > 2M and/or 2MEG, ...) notation. > > > > Python identifiers as previously mentioned. > > Well, *they're* already in the tokenize module. > > Cheers, > M. > > -- > That's why the smartest companies use Common Lisp, but lie about it > so all their competitors think Lisp is slow and C++ is fast. (This > rumor has, however, gotten a little out of hand. :) > -- Erik Naggum, comp.lang.lisp From vvainio at tp.spt.fi Fri Jul 5 02:29:51 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 4 Jul 2002 23:29:51 -0700 Subject: REPEAT... UNTIL ? References: Message-ID: vvainio at tp.spt.fi (Ville Vainio) wrote in message news:... > Strangely enough, while 1 - loop is quite often the most intuitive way ... And note that I'm not exceedingly thirsty for attention by triple-posting this thing. Blame google groups. From dswegen at software.plasmon.com Mon Jul 29 04:29:05 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Mon, 29 Jul 2002 09:29:05 +0100 Subject: Webmin-alike cgi script and security In-Reply-To: <1027783225.19639.44.camel@vaio2> References: <20020722133609.GB2610@software.plasmon> <20020722141318.GD2610@software.plasmon> <1027783225.19639.44.camel@vaio2> Message-ID: <20020729082905.GB14254@software.plasmon> On Sat, Jul 27, 2002 at 10:11:10PM +0200, Andreas Kostyrka wrote: > Am Mon, 2002-07-22 um 16.13 schrieb Dave Swegen: > > On Mon, Jul 22, 2002 at 06:08:26PM +0400, Denis S. Otkidach wrote: > > > Adding webserver default user to sudoers is a bad thing anyway. > > > It's better to use suexec with unique user, that will be used for > > > this script only. > > > > Thanks, this is exactly the sort of info I'm looking for. > Also, depending if "local-attackers" are a likely scenario, you might > think about using marshal: > + does not execute code upon load > - loads code objects > - supports only basic data structures. Experience shows that for this > kind a marshaled dictionary is usually ok. All I'll be passing around is quite simple data, so marshal should be sufficient. > > You should consider also if the filebased approach is best. > For example AF_UNIX sockets support authentication. > You could also pipe the data into the sudo process, and read the answer > back from it. The piped approach might actually be better, as it would leave the implementation language of the actual worker scripts open (not everyone here at work likes python - it's the indentation thing *sigh* ;) > > Should you go with the file based approach, you should check: > -) that the file is only writeable and readable by the "webuser". > (or somebody else might be tricking us into doing the wrong thing.) > -) that the file is in a directory only writeable by the "webuser". > (again, somebody might fool as with a symlink) > > Basically be as paranoid as you can be. Thanks all the advice. Not having done this before I certainly helps having pointers to what I should be aware of. Cheers Dave From curt at journyx.com Tue Jul 9 15:53:57 2002 From: curt at journyx.com (curt finch) Date: 9 Jul 2002 12:53:57 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: Message-ID: <96c7f32.0207091153.7b2484be@posting.google.com> "Opus" said > > On 8 Jul 2002 at 23:00, Matt Gerrans wrote: > > > Based on the following circumstantial evidence, I think the troll theory > > mentioned earlier may is worth considering: > > > > - The "competitor" was not named. Why? Where is their web site with this > > propaganda? There are two basically, one is clockware and the other is timewizard. I don't like to give them publicity at all, even bad publicity. > > - The preamble sounds salesy. > > - There is no "free stuff" at the web site listed. Product is free at http://www.journyx.com/products/timesheet/ > > - The rest of the nonsense listed is largely incorrect but invariably > > inflamatory -- trying to generate a large thread so that lots of people will > > go to the web site (or at least see the url). the audience is payroll ladies not developers. they don't necessarily know better and do fall for outrageous lies. Our rebuttal (based on some of your comments) is here: http://www.journyx.com/pdf/PythonAtAGlance.pdf > > > > --Opus-- From fredrik at pythonware.com Mon Jul 29 11:51:08 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Jul 2002 15:51:08 GMT Subject: Let's Talk About Lambda Functions! References: Message-ID: Tim Peters wrote: > I don't think so -- Guido isn't a fan of functional programming styles, and > plain doesn't like lambda. Except, of course, when he uses it, which is > always for trivial little function arguments, in accord with his > oft-repeated claim that the functional gimmicks were never intended to be > more than "minor conveniences" (which he later amended to "minor > annoyances", after people started clamoring for more of the same). It's not > that they don't work exactly the same way in Python as some people expect > them to my memories of who said what and when is starting to get mixed up, but I'm pretty sure I've seen and heard comments along those lines over the years, including this c.l.py comment from 1996: Opinions on ugliness can vary, but personally, I just wish I'd never given in to the pressure to add lambda in the first place. Nested functions are somewhat of an oddity, but once you say "lambda" you recall a whole complex of semantics for those who are used to it. but I might be wrong. > it's more that programming styles based on composition of higher-order functions > simply aren't in his vision of what programming in Python should be. that's true. but that doesn't explain why did we added nested scopes to 2.1? did you guys just fail to stop Jeremy from checking them in, or what happened? > > to fix the other "mistake", some needs to come up with a > > really great syntax (and get michael hudson to implement > > it for them ;-). ideas are welcome. (I think that should have been "greg ewing needs to come up with a really great syntax, and get michael hudson to implement it"... or maybe we could revive the old "frowning guido" design?) > Well, I can channel that one: not bloody likely. oh, I don't know about that. I definitely remember that the BDFL was rather positive to the idea when we discussed this back at SPAM8 (or whenever it was). iirc, Eric Raymond volunteered to come up with a "smalltalk block"-like design and a patch. hasn't happened yet... From pecora at anvil.nrl.navy.mil Mon Jul 22 18:03:05 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Mon, 22 Jul 2002 18:03:05 -0400 Subject: A better self References: Message-ID: <220720021803052686%pecora@anvil.nrl.navy.mil> In article , Michael Chermside wrote: > # WARNING: Untested code below > > def pretendFormula(x,y,z,t): > return sin(t) * x**y + sqrt(z) > > def MyClass: > def pretend(self): > return pretendFormula(self.x, self.y, self.z, self.t) > > Notice how this has an additional advantage... it allows you to use > short, simple names for the variables within the formula (the > traditional to write formula), while still allowing longer, more > descriptive names within the object What's the overhead of the function calls versus either (1) t, x, y, z=self.t, self.x, self.y, self.z or (2)t=self.t; x=self.x; y=self.y; z=self.z; ?? Seems like (1) and (2) have less overhead and someone in this thread said (1) creates and then destroys a tuple (unnecessarily so) and (2) is better (no intermediate tuple). I still prefer (1) -- most readable, but I like minimum overhead. -- Lou Pecora - My views are my own. From markus.vonehr at ipm.fhg.de Tue Jul 16 02:43:20 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 16 Jul 2002 08:43:20 +0200 Subject: Maximizing observations from Sparse matrices References: Message-ID: <3D33C088.9B4992DE@ipm.fhg.de> Hi, I didn't understand exactly what you wanna do but I would recommend you to use Numeric.py, too. I use the Numeric lib for Image operations, the Image is represented in a Matrix, I cut submatrices, process them, it's quite fast and easy to handle with Numeric.py. Markus PoulsenL at capanalysis.com schrieb: > > I am running a regression that gathers its data from a panel dataset > (cross-sectional time series). Because the dataset is sparse I must > sometimes either drop cross-sections or variables or some combination of the > two to avoid a singular matrix. A quick, extremely simplified example: > > obs region var1 var2 var3 Valid ob? > 1 1 1 4 7 3 > 2 1 7 NA 9 0 > 3 1 7 NA 9 0 > 4 1 5 NA 7 0 > 5 1 7 7 5 3 > > 1 2 7 NA 9 0 > 2 2 5 NA 6 0 > 3 2 7 4 5 3 > 4 2 9 8 NA 0 > 5 2 7 6 5 3 > > 1 3 NA 58 4 0 > 2 3 NA 98 25 0 > 3 3 63 85 NA 0 > 4 3 74 NA 78 0 > 5 3 97 54 NA 0 > > 1 4 NA 89 7 0 > 2 4 25 85 NA 0 > 3 4 5 NA 2 0 > 4 4 32 85 NA 0 > 5 4 45 12 3 3 > Sum of valid obs 15 > > In this example I have 4 regions and 3 variables. Region 3 has no valid > observations and therefore cannot be utilized unless corrected. I have two > choices: eliminate a variable or eliminate the region. > > If I eliminate the variable it will now run because I have valid obs across > all remaining regions: > > obs region var1 var2 var3 Valid ob? > 1 1 4 7 2 > 2 1 NA 9 0 > 3 1 NA 9 0 > 4 1 NA 7 0 > 5 1 7 5 2 > > 1 2 NA 9 0 > 2 2 NA 6 0 > 3 2 4 5 2 > 4 2 8 NA 0 > 5 2 6 5 2 > > 1 3 58 4 2 > 2 3 98 25 2 > 3 3 85 NA 0 > 4 3 NA 78 0 > 5 3 54 NA 0 > > 1 4 89 7 2 > 2 4 85 NA 0 > 3 4 NA 2 0 > 4 4 85 NA 0 > 5 4 12 3 2 > Sum of valid obs 16 > > Finally I can instead eliminate a region > > obs region var1 var2 var3 Valid ob? > 1 1 1 4 7 3 > 2 1 7 NA 9 0 > 3 1 7 NA 9 0 > 4 1 5 NA 7 0 > 5 1 7 7 5 3 > > 1 2 7 NA 9 0 > 2 2 5 NA 6 0 > 3 2 7 4 5 3 > 4 2 9 8 NA 0 > 5 2 7 6 5 3 > > 1 4 NA 89 7 0 > 2 4 25 85 NA 0 > 3 4 5 NA 2 0 > 4 4 32 85 NA 0 > 5 4 45 12 3 3 > Sum of valid obs 15 > > This quick example yields the same number of observations, but there are > configurations where this may lead to more obs than eliminating a variable. > The problem is I have hundreds of variables and about 50 regions. Is there > an efficient way to maximize the number of observations? > > Thanks for any help > > Loren From just at xs4all.nl Mon Jul 15 13:42:00 2002 From: just at xs4all.nl (Just) Date: Mon, 15 Jul 2002 19:42:00 +0200 Subject: Problem using py2exe References: Message-ID: In article , "Harvey Thomas" wrote: > I've got a program that works fine, when run using the Python interpreter, > but when I convert it to a Windows exe using py2exe, I get the following > traceback: > > File "", line 96, in ? > File "", line 77, in main > File "apex.pyc", line 219, in apexopen > File "codecs.pyc", line 499, in open > > Line 219 of apex.pyc is: > return codecs.open(fn, mde, 'utf8') > > I guess I need to force py2exe to read something it can't pick up > automatically, but I can't work out what the something is. > > Any help appreciated Most likely it's the encodings package that's missing. Fixable by doing this: python setup.py py2exe --packages encodings Just From sholden at holdenweb.com Mon Jul 1 10:45:36 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 10:45:36 -0400 Subject: How to find out DNS ? References: <3D1C79E8.22371.4709FB1@localhost> Message-ID: "Matthew Sherborne" wrote ... > There is a way but it's very hard. You take a list of root dns servers, > you get your local host name, (gethostbyaddr(youripaddress)), you remove > from it the computer name, so you've just got the domain name. Then > taking a list of "root" dns servers, you ask one of them, what's the dns > server for this domain? > > It'l l say "I don't know, ask server X" then you ask server X, which > will be a closer server to your host than the root server. You keep on > going until one of the servers says "yes, This is/I am your server" > then that's your dns server. > > You can do this with the code in http://pydns.sf.net. > > Is it an open-source project you're working on? I might take an interest :) > In actual fact you could usually get the same answer by going to *any* DNS server and asking "what is the DNS server from domain xxx.yyy.zzz" using a query for NS resource records. Let the DNS do the work like it's supposed to! Further, this technique will tell you which DNS server is serving the domain of which your workstation is a member, but that need not be "The primary or secondary DNS [server] I use when connecting to internet" as asked by the OP. For example, if you look up the DNS server for holdenweb.com, you will *not* find 10.0.0.1 as any kind of DNS server, even though that is the IP address that all machines behind my firewall use as their principal DNS server. Domains often "split" their DNS service, offering a private and complete domain description behind the firewall, and a limited public version containing only the hosts that are intended to be publicly available. Also I get the advantage of behind-the-firewall caching, so DNS traffic to external servers is minimized, retaining Internet bandwidth for more practical purposes. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ---------------------------------------------------------------------- From sandskyfly at hotmail.com Mon Jul 22 14:15:19 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 22 Jul 2002 11:15:19 -0700 Subject: Python to Excell References: <3d3bb483.250106359@news.skynet.be> Message-ID: pixie888 at hotmail.com wrote in message > I want to use Python to automate Excel...Can anybody help me further on this > one? One way to understand this topic better is to look at the examples in Mark Hammond's excellent Win32 Programming in Python book: http://examples.oreilly.com/pythonwin32/ This should get you started. Have fun, Sandy From tdelaney at avaya.com Thu Jul 25 23:06:28 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 26 Jul 2002 13:06:28 +1000 Subject: how to count lines in a file ? Message-ID: > From: Michael Gilfix [mailto:mgilfix at eecs.tufts.edu] > > Sorry, I'm a little unclear on this one. Do I actually gain anything > by creating this proxy class over using the regular file object? Does > the use of __del__ add anything? Meaning, will the file.close call > definitely be called at the "some later stage" or whenever the object > is freed? Do you gain anything? Decreased performance perhaps. Some flexibility if you want to intercept some method calls, etc. For the stated purpose though, no. Refcount system: Proxy object is created and assigned to a name proxy refcount incremented File object is assigned to field of proxy object file refcount incremented Proxy deleted proxy refcount decremented proxy collected file refcount decremented file collected (and closed) Non-refcount system: Proxy object is created and assigned to a name proxy is referenced File object is assigned to field of proxy object file is referenced Proxy is deleted proxy not referenced - candidate for collection Time passes Proxy is collected file is not referenced - candidate for collection Time passes File is collected In a refcount system (with no cycles), you have a reasonable guarantee that all the garbage will be collected (there are cases where it will not happen, but they are all due to abnormal termination). In a non-refcount system, garbage will hang around for an indeterminate period of time. If your program finishes before that garbage is collected, it may never be collected (and any code in the finaliser will not be run). CPython uses refcounts for everything, but if an object is involved in a cycle there is an indeterminate period of time before cycles are broken, meaning that they will not be collected when the last non-cyclic reference is removed. This did not affect files, because files could not become involved in cycles. There was a proposal which would have involved every file being in a cycle. Files would then have not gone away when people expected (luckily for people with such broken code, the devs care about them). In Jython (and JPython) it has always been the case that you can't rely on things going away immediately, since they use Java garbage collection. Now it's starting to become an issue in CPython. The only reason it *is* an issue in CPython is because many people don't clean up the resources they use when they're finished with them, counter to the strong recommendation in the Python documentation. Tim Delaney From andreas at kostyrka.priv.at Sun Jul 28 10:45:29 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 28 Jul 2002 16:45:29 +0200 Subject: Guide to the python interp. source? In-Reply-To: References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> <_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: <1027854395.20536.220.camel@vaio2> Am Sam, 2002-07-27 um 21.15 schrieb Tim Gahnstr?m /Bladerman: > This is not the comon way, I know that but I am inclined to say that it is > "undoubtley" more intuitive. Remember that this is a language for complete > beginners with no programming experience. Well, and how does it work with recursion? Just wondering. ;) [And recursion is such a fundamental pattern in programming, that you want your students to understand it quickly. Actually it's also needed for the maths.] > Ofcourse this is just the simplest case possible and ther vill be issues > further down the way but I intend to handle them later. right now I am > getting to no the python interpreter, and its interaction with C and the IDE > Maybe I have gotten the names wrong imutable/mutable/CBR/CBV etc etc. But my > intentions are as outlined above. Well, I've got the strong impression, that you have not yet the feeling for the Python datamodel. While it can probably somehow done, you are in myriad of troubles. (And I suspect that you will not be able to work it out in a semester. Perhaps even two semesters ;) ) The fundamental facts about mutable/immutable objects are at the core of Python. So is the datamodel without "variables", just name bindings. (In some way, the fundamental data structure of Python is a dictionary, as was a cons-cell for Lisp.) Because dictionaries are so fundamental, the mutable/imutable separation is fundamental too. (It takes much creativity to make mutable keys even partly work.) And consider the fact, that you would have to completely rewrite the python library also, because basically every piece of python code relies upon call by value. > After I had written this mail actually thought that I had to add this on > top: > CBR is not a die hard feature that I must have if it gets a whole lot of > work to fix it. But I would apreciate anny suggestions on how to make it > with a limited amount of work. Forget it :) Write some small (~1000KLOC) applications in Python, do some data manipulation stuff, and then reconsider your project ;) Actually one funny side note on CBR: Calling a.method() would allow the method to change the object that a is pointing to, because the method gets an explicit self parameter that points to a, ... > That I understand but hadn't thought about it. What might be possible now > when you point it out like that is that maybe I can use the current Python > model untill I come to a return statement in a function. At that time I > reattatch the internal object to the pointer/refference/name that I sent in. > Clearly neither this is well thought over. I will come there in a month or > so. Well, it's usually a bad idea to try fixing a language, that you do not know well enough. Especially if you don't know the basic "idioms". And I strongly question the fact if passing values by reference is easier to understand than assigning values. (which call by value is) > >ones do such intrusions in their callers' namespaces. > From my point of view such intrusions is not a bad thing, this language is > for beginners and not for critical aplications. > If that is most intuitive and don't come with alot of problems it is also > the best. But this kind of changes is not intuitive. The only people that will find this intuitive are FORTRAN and perhaps BASIC diehards ;) > From: "Terry Reedy" > > In a real sense, Python does not have variables. It has objects, each > > of which has 1 or more named or unnamed references thereunto. > > Okey this is what I have to work with then and from that modify the > interpreter so the novice get the feeling that it works as I outlined above. > Maybe I am working against the python modell I dont know that yet but I am > confident I will know when the time comes. > If that is the case I will either have to rethink my priorities or change > Language to work with (change of language ofcourse get less likely the more > time gets by and the more code I write). > I might even throw in a preprocessor that changes the usercode into python > right before it is ran. That ofcourse is not a good solution but I have t in > mind. Nope. Preprocessor would be a quite bad idea. Makes for bad error messages, and python is dynamic enough, that some running code could discover that it was mangled and go in some creative way wrong. Andreas From johnroth at ameritech.net Tue Jul 30 07:29:25 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 30 Jul 2002 07:29:25 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: "Huaiyu Zhu" wrote in message news:slrnakb792.aej.huaiyu at gauss.almadan.ibm.com... > Fredrik Lundh wrote: > >to fix the other "mistake", some needs to come up with a > >really great syntax (and get michael hudson to implement > >it for them ;-). ideas are welcome. > > No great syntax here, but some ideas on why it is difficult syntax-wise (in > the hope that someone can overcome them). > > Python uses indentation to denote lexical scope at or above the statement > level, while using parenthesis at the expression level. It is rather easy > to embed parenthesis inside indentation, but the other way is difficult. > > So to allow statements in lambdas, it is either necessary to delimit > statements with some begin/end marker in lieu of indentation, or to come up > with a way to embed indentation scoping inside parenthesis scoping. Exactly. AFIK, everyone has been pursuing the first path, while it is conceptually simple to do the second. See my response to Steve Holden's comment for how it would look in practice. It's easy to write, not quite so easy to look at. I have no idea whether it would be easy to implement in the compiler. (The interpreter shouldn't care.) The trick is to use 'def' as the keyword, not 'lambda.' > > Another possibility is to allow only those statements that do not have > further scopes. For example, print and assert would be allowed but > if/then/else would not. Why bother with the restrictions? Fredrik had the right idea when he said that we needed something to make it obvious that functions are first class objects. That is, allow anonamous functions anywhere you can have a function object. John Roth > > Huaiyu From donn at drizzle.com Fri Jul 26 00:02:11 2002 From: donn at drizzle.com (Donn Cave) Date: Fri, 26 Jul 2002 04:02:11 -0000 Subject: how to count lines in a file ? References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> Message-ID: <1027656130.63094@yasure> Quoth Richard Jones : | On Fri, 26 Jul 2002 12:45 am, Alex Martelli wrote: ... |> [alex at lancelot jython-2.1]$ jython |> Jython 2.1 on java1.4.0_01 (JIT: null) |> Type "copyright", "credits" or "license" for more information. ... |> I exited the interactive interpreter with a clean, normal |> control-D, but as you see file aname was created but its |> contents not written. | I think the major problem that we're running into here is that before there | was GC, the refcounting-based cleanup of objects was clear, straight-forward | and reliable. Now it's not clear when objects are cleared up. That's a fairly | major problem for some of us old-timers (and, quite possibly, a lot of | newbies) to come to terms with. I hadn't realised that GC threw such a big, | ugly spanner in the works :( Hm, I wouldn't have drawn the picture that way. As I understand it, the garbage collection changes to the C Python that we use have not compromised its reference count driven behavior at all. You're just looking at the other Python there, Jython. Its object lifetime policy is Java's, and that doesn't support timely finalization. There's your spanner. Donn Cave, donn at drizzle.com From bokr at oz.net Sat Jul 27 16:25:27 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2002 20:25:27 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> <8ro4ku4v5lc3u66quet6ieg8m18boc4bq5@4ax.com> Message-ID: On Sat, 27 Jul 2002 12:10:07 +0300, Kristian Ovaska wrote: >bokr at oz.net (Bengt Richter): >[f.readlines(N)] >>That bothers me. ISTM it should return as many lines as >>will fit in N bytes, but no more. Otherwise you have no >>memory use protection against a single monster line > >You can't have complete protection in any case: what if there is a >line of length > N? (Or length >> N...) > It wouldn't be returned. Lines up to it would be returned, unless it was the first line about to be read. Then I think an exception would be appropriate. You could catch it if you wanted to investigate with ordinary read(n). Regards, Bengt Richter From max at alcyone.com Sun Jul 21 00:43:19 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 20 Jul 2002 21:43:19 -0700 Subject: getting date into rfc822 format References: Message-ID: <3D3A3BE7.B3D24D34@alcyone.com> "Jon J. Morin" wrote: > date = time.ctime(time.time()) > > Which gives me a date like this: > Sat Jul 20 00:02:03 2002 > > When what I want is something like this: > Fri, 01 Mar 2002 00:18:17 -0500 (EST) Try time.strftime, though you might have to hack up the timezone information yourself. http://www.python.org/doc/current/lib/module-time.html > Incidentally, I have read the rfc822 and I can't figure out what the > -0500 > is in the date/time. Can anyone explain this to me? It's the timezone. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From opengeometry at NOSPAM.yahoo.ca Wed Jul 3 12:34:15 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 3 Jul 2002 16:34:15 GMT Subject: Splitting Text files References: Message-ID: Jonathan Hogg wrote: > Given that the header was given in the body of the message, I hardly see > that it will make any difference - it won't get honoured. The actual header > contained: > > X-No-Archvie:Yes > > which the astute will notice also wouldn't have worked ;-) > > Still, if you post to usenet news, you should expect your words to live on > in perpetuity. > > In years to come you'll find it fantastic fun to search Google for things > you said when you were younger . > > -ah-them-were-the-days-ly y'rs, > > Jonathan If you go over to Google, you'll see his original post is not archived. Google honours 'X-No-Archvie:' header if it is at the top of body. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From parker at gol.com Thu Jul 11 23:39:28 2002 From: parker at gol.com (Ian Parker) Date: Fri, 12 Jul 2002 12:39:28 +0900 Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> <3D2C500D.5000100@thomas-guettler.de> Message-ID: In article <3D2C500D.5000100 at thomas-guettler.de>, Thomas Guettler writes >John Hunter wrote: > >>>>>>>"Thomas" == Thomas Guettler writes: >>>>>>> >> >> Thomas> Hi! Does someoone know an editor for editing >> Thomas> >> Thomas> text data? >> >> Thomas> I need it for something like a todo-list. One task can >> Thomas> have several subtasks. >> Emacs has a number of todo modes: >> http://www.emacswiki.org/cgi-bin/wiki.pl?ToDo > > >I love emacs for editing source code. But I need something that >can be used by everybody. The treeview should look like in the >windows explorer. > > thomas > > If you wanted something only for Windows, then MS word has an outline mode. Regards -- Ian Parker From b.maryniuk at forbis.lt Mon Jul 29 03:49:46 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 29 Jul 2002 09:49:46 +0200 Subject: Let's Talk About Lambda Functions! In-Reply-To: References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: <200207290949.46556.b.maryniuk@forbis.lt> On Saturday 27 July 2002 22:17, Fredrik Lundh wrote: > Oh, sorry, I didn't mean you. I meant the "lambda lovers have > childhood traumas" guy. If he cannot defend his position with- > out stuff like that, it must be a pretty worthless position. Ouuhhh! Maybe ESR is "bad programmer", since he loves lambdas in Python... :D -- Sincerely yours, Bogdan M. Maryniuck "Linux poses a real challenge for those with a taste for late-night hacking (and/or conversations with God)." (By Matt Welsh) From linuxbrad at rogers.com Sun Jul 7 20:37:28 2002 From: linuxbrad at rogers.com (Brad Fonseca) Date: Mon, 08 Jul 2002 00:37:28 GMT Subject: Getting IDLE 0.8 to recognize Python 2.2.1 Message-ID: Hi! I've upgraded to python 2.2.1 but when I start IDLE it still starts Python 2.1.1. How do I get IDLE to start Python 2.2 Regards, -- --- Brad Fonseca From jdavis at empires.org Thu Jul 25 05:32:51 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 25 Jul 2002 09:32:51 GMT Subject: random 64-bit int References: <5nM%8.30598$4T2.8891354@twister.socal.rr.com> Message-ID: <7BP%8.31421$4T2.9101969@twister.socal.rr.com> Thank you for your reply (and the other person who responded). You mention that I am wasting two random bytes. How might I go about getting those two bytes? if I use randrange() for the entire range of ints, than I get an overflow. random() isn't really all that random either, since it is only zero to one and a conversion to a float loses a lot of information (I think... let me know if I'm mistaken). The only thing I could think of was to use a short. Thanks again, Jeff Martin v. Loewis wrote: > Jeff Davis writes: > >> It seems like the above works, but I'd like to know whether I am losing >> randomness, or whether there is a more efficient or faster way to >> accomplish that. Would it be a good idea to include a call to >> random.seed()? >> >> Also, it would be *really* nice if there was a good way to do that in >> python2.1, which does not seem to allow the "q" type for unpack(). > > I think the randomness of this is as good as any other algorithm you > could find. On speed and portability, you might consider using hex or > octal strings, or plain arithmetic computations. Notice that each > random() call really gives you roughly 32 bits of randomness, so you > are wasting 16 of them. > > The approach based on octal numbers works on grounds of > > long("-12312357623526234343454642342164",8) > > being supported in all Python versions. Create 7 octal digits (21 > bits, unsigned) with two call to random, then create the missing 22 > bits (including sign) with another call; print the strings octal, > concatenate them, and invoke long(). > > The approach based on arithmetic works the same, but avoids the string > operations: Create three 21 bit numbers a, b, c (a should be signed), > then use > long(a)<<42 + long(b)<<21 + c > > You should time all three approaches if performance matters. > > HTH, > Martin From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 18:36:24 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 15:36:24 -0700 Subject: performance problem in python 2.2 References: Message-ID: <7xn0sedslz.fsf@ruckus.brouhaha.com> Fernando Perez writes: > #!/usr/bin/perl > > $p = 2**64; > $c = $ARGV[0]; > > $n = 1; > foreach $i (1..$c) { > $n = ($n * ($p-$i)) / $p > } > print 1-$n, "\n"; > > But again, there's NO WAY you are going to write perl code to do this at C > speed (short of a trick like inlining C in perl). Does $c = 0.0 + $ARGV[0]; making $c a float instead of a string help? Also: $p = 2**64; $c = $ARGV[0]; $n = exp(-($c*$c) / (2*$p)); print 1-$n, "\n"; should give a pretty close approximation faster than any of the iterative methods listed. From news at lindbergs.org Sat Jul 6 17:31:57 2002 From: news at lindbergs.org (VanL) Date: Sat, 06 Jul 2002 15:31:57 -0600 Subject: Given PID, make sure a process is running on Unix? Message-ID: <3D2761CD.1090503@lindbergs.org> Hello, I am trying to get write a python script that on Unix reads a PID from a file and, if that process is still running, exits. If the process is not running, the process would be started. I have everything written except the part that makes sure the process is running. I have poked through the os module, but I can only seem to find information about the current process or child processes, not just some arbitrary process. This would run from cron or as a daemon, sleeping most of the time. Any help? Thanks, VanL From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 25 12:44:16 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 25 Jul 2002 16:44:16 +0000 Subject: Jython newbie question In-Reply-To: <3D401577.65D61189@ingenta.com> References: <3D401577.65D61189@ingenta.com> Message-ID: <200207251544.g6PFiG009089@helios.gatwick.geco-prakla.slb.com> On Thursday 25 Jul 2002 3:12 pm, Christopher Myers wrote: > I just downloaded Maxq (http://www.bitmechanic.com/projects/maxq/) > - a web testing application, which is written in Java, and it uses > Jython for a scripting language. > I've never used Jython before, and consider myself an intermediate > Python programmer. > > And the test script begins as follows: > (My addition is the 'import time, string' line). > Note - there are no complaints about the time module, only the string > module. > > # imports > from com.bitmechanic.maxq import HttpTestCase > from junit.textui import TestRunner > from java.util import HashMap > import time, string > > # defintition of test class > class MaxQTest(HttpTestCase): > def __init__(self): > HttpTestCase.__init__(self, "") > self.page = "" > > (etc . . .) Christopher, I can;t answer your question but there is a difference between the time module and the string module as shown here [bpse at m-franklin bpse]$ jython Jython 2.0 on java1.3.0 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> >>> import string >>> string.__file__ '/usr/python/Jython/Lib/string.py' >>> import time >>> time.__file__ Traceback (innermost last): File "", line 1, in ? AttributeError: class 'org.python.modules.time' has no attribute '__file__' >>> >>> time >>> string >>> time loks like it's a builtin module and string is a Library module. So I would think there is somthing wrong with the sys.path Can you do the above at the jython command line? Cheers Martin From steve_greiner at pobox.com Sat Jul 13 22:56:29 2002 From: steve_greiner at pobox.com (Steve Greiner) Date: 13 Jul 2002 19:56:29 -0700 Subject: Passing SAFEARRAY data type from win32com.client Message-ID: I am trying to automate Internet Explorer, and I need to use the Post function. I can get IE to send a Post-method request, but the data that it sends appears to be intrepreted as an incorrect type; in fact, if I try to send a single character, it actually thinks it should send 16 bytes. It appears to me that the value I'm passing as the Data parameter is being passed as the wrong type. IE expects a SAFEARRAY data type, and I think I've tried every Python type, but none of them seems to convert correctly. I am using win32com.client with makepy (thought I've also tried it without makepy). Can anyone tell me if I'm attempting the impossible, or should I dig in and figure out what I'm doing wrong? From fredrik at pythonware.com Wed Jul 10 06:59:34 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jul 2002 10:59:34 GMT Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: Fredrik Lundh wrote: > > There did used to be a MoinMoin-based Wiki somewhere > > under www.python.org > > http://www.python.org/cgi-bin/moinmoin > > resurrecting it (and moving it's focus to Python in general, > rather than Python 2.0 ;-) sounds like a good idea. > > maybe we should start here: > > http://www.python.org/cgi-bin/moinmoin/Python > > and see what happens... from what I can tell, nothing happened. I'll restore the wiki to it's original "historical" state, when I find the time. From dswegen at software.plasmon.com Mon Jul 22 10:13:18 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Mon, 22 Jul 2002 15:13:18 +0100 Subject: Webmin-alike cgi script and security In-Reply-To: References: <20020722133609.GB2610@software.plasmon> Message-ID: <20020722141318.GD2610@software.plasmon> On Mon, Jul 22, 2002 at 06:08:26PM +0400, Denis S. Otkidach wrote: > On Mon, 22 Jul 2002, Dave Swegen wrote: > > DS> The scripts themselves are run as the default webserver > DS> user, and take > DS> care of stuff like authentication and basic sanity checking. > DS> > DS> If all input checks out an external script is called using > DS> sudo to gain > DS> root privs. Any data that should be provided is pickled and > > Adding webserver default user to sudoers is a bad thing anyway. > It's better to use suexec with unique user, that will be used for > this script only. Thanks, this is exactly the sort of info I'm looking for. Cheers Dave From jonathan at onegoodidea.com Thu Jul 25 03:57:03 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 25 Jul 2002 08:57:03 +0100 Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <3D3E9BCF.90806@mxm.dk> Message-ID: On 24/7/2002 17:11, in article BkA%8.112577$Jj7.2658921 at news1.tin.it, "Alex Martelli" wrote: > You have a point. Such a need is so rare and weird that I would not be > highly troubled by having to use weird ways to meet it. However, taking > "callability" as outside the range of polymorphically emulable behaviors > would indeed reduce regularity, so it might be a bad idea even though the > serious use cases for it ARE weird:-). You seem to be starting from the point of view that __call__ is bad and using that as an argument that serious uses of __call__ must therefore be rare and weird ;-) I would use an object with __call__ for even trivial callable objects because of the ability to redefine the 'repr' interface and access attributes. Another thread here discussed wrapping a function to provide 'before' and 'after' hooks. This is exactly the situation where I would use a __call__ interface. Consider: >>> def hello( name ): ... print 'Hello', name ... >>> def upper( args, keys ): ... return (args[0].upper(),), keys ... >>> hello = wrap( hello, before=upper ) >>> hello( 'Jonathan' ) Hello JONATHAN >>> hello >>> hello.before >>> Here 'wrap' is a class that implements the __call__ interface. The resulting object behaves just like the original function so I can drop it into existing code, it explains what it is via __repr__, and provides access to the state for examination. Try something similar with a closure or a bound method. -__call__-doesn't-kill-readability-people-kill-readability-;)-ly y'rs, Jonathan From jonathan at onegoodidea.com Sun Jul 14 13:11:42 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Sun, 14 Jul 2002 18:11:42 +0100 Subject: sorting many arrays from one... References: Message-ID: On 14/7/2002 6:46, in article mailman.1026625704.19305.python-list at python.org, "Tim Peters" wrote: > I've worked very much harder for very much less gain. Thanks! I checked in > a variant of this (inside the core it's kosher to use the quicker > PyTuple_SET_ITEM macro). Oh well, in that case you can trim another couple of % off the calls with: Index: listobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v retrieving revision 2.116 diff -r2.116 listobject.c 783c783 < res = PyEval_CallObject(compare, args); --- > res = PyObject_Call(compare, args, NULL); Since PyEval_CallObject just does some unnecessary typechecks on the arguments. Or being even more aggressive: Index: listobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v retrieving revision 2.116 diff -r2.116 listobject.c 783c783 < res = PyEval_CallObject(compare, args); --- > res = (*compare->ob_type->tp_call)(compare, args, NULL); 1297a1298,1302 > } > if (compare && compare->ob_type->tp_call == NULL) { > PyErr_Format(PyExc_TypeError, "'%s' object is not callable", > compare->ob_type->tp_name); > return NULL; i.e., pull the remaining typecheck out to 'listsort'. But I don't much like this one as it gains only a tiny amount over the one above, seems quite a bit more obtuse (or is there a neater callable check macro?), and also subtly changes the semantics (sorting an empty list with a non-callable fails - though perhaps it should). > It also adds up even if you do 5 million in slow succession . If your > fingers are well-rested, get into a debugger and single-step through what > happens when cmp gets called in this context. It's a revelation of > apocalyptic dimension . Yeah, I've had a short wander through the innards of cmp. It's a bit of a convoluted one, but necessarily so. I don't see how the calls can be made more optimal and cmp has to be the way it is, so I don't think '.sort(cmp)' can be made any faster without checking to see if 'compare' *is* 'cmp' and then not bothering to make the calls ;-) Jonathan From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 20:31:01 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 17:31:01 -0700 Subject: performance problem in python 2.2 References: <7xd6tayqt6.fsf@ruckus.brouhaha.com> Message-ID: <7xptxaj9kq.fsf@ruckus.brouhaha.com> Jeff Davis writes: > Strange that you mention that, because I sort of thought I might get a > more precise answer. After all, mine preserves the entire number 2^64, > yours just preserves most. Mine might end up losing it all later in the > calculations (because there are more multiplications), is that what you > mean? No, on most computers a C integer can't represent numbers like 2**64. It only has 32 bits. If you multiply numbers together that overflow 32 bits, you'll get the wrong answer unless the language mysteriously converted them to floats for you (the rules for that are slightly obscure). Python has exact integers (Python "longs" are not to be confused with C longs which are usually 32 bits) but at a cost. If you use longs in Python, your program runs a lot slower. From b.maryniuk at forbis.lt Wed Jul 24 05:05:48 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 24 Jul 2002 11:05:48 +0200 Subject: how to count lines in a file ? In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: <200207241105.48913.b.maryniuk@forbis.lt> On Tuesday 23 July 2002 19:02, Bjorn Pettersen wrote: > Now, why on earth would you use that monstrosity instead of: > > for line in open(filename): > count += 1 Or even: print len(open('/etc/passwd').readlines()) -- Sincerely yours, Bogdan M. Maryniuck "Absolutely nothing should be concluded from these figures except that no conclusion can be drawn from them." (By Joseph L. Brothers, Linux/PowerPC Project) From talsit at talsit.org Tue Jul 30 22:32:41 2002 From: talsit at talsit.org (tALSit de CoD) Date: 31 Jul 2002 12:32:41 +1000 Subject: Debug version crashing... Message-ID: Hi guys! I'm writing a small DLL thingy that requieres the use of loading the Python interpreter and executing a series of scripts. I have generated an interface to my dll with SWIG and put it in. It works like this: 1) a small .exe loads the .dll and calls the main init() function 2) the dll starts up some services, among them Py_Initialize () 3) i tell python to execute: execfile("kikura.py") (kikura.py is the file that SWIG generates for the shadow classes) All this works in the release version, but in the debug version i get this error message along with an assert failure: Fatal Python error: Interpreter not initialized (version mismatch?) Now, this might due to a fault of mine, but... The thing is that the windows installer of python didn't come with debug libraries or .dll, so i downloaded the python source, and compiled those, and am using those for the debug, but the original instalation ones for release version. Can anyone help? Thanx From mertz at gnosis.cx Fri Jul 26 14:36:31 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Fri, 26 Jul 2002 14:36:31 -0400 Subject: Ain't workin' In-Reply-To: References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <16Q%8.116512$Jj7.2728704@news1.tin.it> Message-ID: |>AND because the "you" is actually redundant if I understand |>"slang grammar" correctly (isn't the great song's title just |>"Ain't Misbehavin'" without any pronoun?-). |"Ain't" can be used with any subject in incorrect English, actually. I |don't know "Ain't Misbehavin'", but the subject of the song "Ain't |Superstitious" is "I", frex. "Ain't" is originally a contraction of "am not" (with some simplification of the "mn" consonant cluster that doesn't sound right to English ears). It's been several centuries since "ain't" has been extended to cover numbers and persons other than first-person singular. But at least to my ears, if I hear "ain't" without a specified subject, the "I" pronoun is the default subject. However, other semantic context can lead to a non-default interpretation. -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From dreadi at gmx.de Fri Jul 5 10:21:23 2002 From: dreadi at gmx.de (Basim) Date: Fri, 05 Jul 2002 16:21:23 +0200 Subject: undo and marked linebreaks in text-widget Message-ID: hi, i have two questions concerning the tk(inter) text-widget: 1) are there any ready to use extensions which provide a undo/redo-mechanism? if not, what would be the best strategy? Would it be enough to override the widget's insert and delete-method and record these actions? (in my app there are no marks/bindings which have to be preserved) 2) could anyone point me the direction for extending the widget that line-breaks are marked by a special symbol? thanks in advance, Basim From correia_j at hotmail.com Thu Jul 4 22:22:30 2002 From: correia_j at hotmail.com (Jose Correia) Date: Fri, 05 Jul 2002 02:22:30 GMT Subject: win32com and internet explorer References: <3d235b64$1@post.usenet.com> <6vZU8.409778$cQ3.28013@sccrnsc01> Message-ID: Don't know how to get the entire page saved to disk, but hopefully this gets you a little closer to your goal if you're trying to get at the info on the page. >>> from win32com.client import Dispatch >>> ie = Dispatch("InternetExplorer.Application") >>> ie.Navigate("http://www.google.com") >>> ie.Visible=1 >>> ie.Document.body.innerHTML '

\015\012 Message-ID: In article , Alex Martelli wrote: >jubafre at zipmail.com.br wrote: > >> how i can disable de maximise button in tkinter, i don?t want the user >> modific the size of the window, i want a real size of window, how can i do >> it??? > >You can remove all decorations: > >import Tkinter >root = Tkinter.Tk() >root.overrideredirect(1) > >Apart from this, you may choose to fix the size: > >import Tkinter >root = Tkinter.Tk() >root.resizable(0,0) > > >I know of no way to affect the maximize button ONLY, without also >affecting other ways to resize the window, but then from your post's >text I don't see why you should ONLY want to affect said button. > > >Alex > > It is possible, though. That is, I believe, without making the time to verify this myself, that there's an effective way to achieve this under crucial window managers. You're right, Alex, that overrideredirect achieves what makes sense in this area. However, as I believe you know, many vertical applications Windows hosts are configured with maximize and remove-window buttons disabled, leaving only iconify. Clients expect to see this, whatever we think of its (ir)rationality. Al- though Tkinter proper doesn't provide a means to achieve this, there are win32 calls accessible through *that* module that make it happen. I've forgotten what they are. If I were going to pursue this, I'd check with operating-system experts for the correct lower- level calls. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From phr-n2002b at NOSPAMnightsong.com Wed Jul 17 18:44:03 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 17 Jul 2002 15:44:03 -0700 Subject: Sharp Zaurus References: <1026919964.826307@irys.nyx.net> Message-ID: <7xznwqf00c.fsf@ruckus.brouhaha.com> sarayu balu writes: > Is there any Python, more appropriately Jython, for this PDA ? I know Python has been ported. I don't know whether Jython has been ported. > Is Jython Open Source ? Yes. From aleax at aleax.it Fri Jul 26 03:46:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 07:46:47 GMT Subject: Just starting out References: <1763824.4DULROvNVE@CoReKill@localhost> Message-ID: CoReKiLL wrote: > > Hi > > Iam just starting out programming in python and wondering if anyone knows > a good site for guides etc ? Lots of good links at: http://www.python.org/doc/Newbies.html > Also is it best just to use python fron a > command line in linux or is there a gui front end for it ? Dinosaurs like me tend to be commandline enthusiasts, with variants such as EMACS (not for me), VIM (yeah, that's my baby) &c. But IDLE's quite good, simple, and free -- installs with standard Python, too, if you have Tcl/Tk already installed on your Linux box (and Tkinter goes on top of Tcl/Tk and is the basis for IDLE). Other smart editors such as SciTE (a tiny elegant wrapper on the Scintilla component that IDLE and others use) have some Python specific help too. Then you get into commercial or at least commercial-if-used-for-gain development environments, such as Activestate's Komodo, Archaeopteryx's Wing, Secretlabs' Pythonworks, theKompany's Blackadder, and more. I've used Blackadder (love the name -- and the show -- and the help it gives specifically for PyQT, which I had to pick up in a hurry a short while ago), but in the end I keep going commandline+readline+rlcompleter and VIM in support for just about all of my development. And an occasional foray into IDLE just to keep in practice. Your mileage will no doubt vary. Alex From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 21:22:15 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 18:22:15 -0700 Subject: Internet Explorer Automation Object Crossframe Element Troubles References: Message-ID: <7xn0sobjg8.fsf@ruckus.brouhaha.com> danieleburrow at yahoo.com (Daniel E. Burrow) writes: > I am able to fire cross-frame elements now but doing so in the manner > shown in the *** ClickCrossFrameElement *** method below troubles me > greatly: ... What is troubling you? From sholden at holdenweb.com Sat Jul 27 00:19:03 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:19:03 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: "John Roth" wrote in message news:uk3abpr4treeb9 at news.supernews.com... > > "Britt A. Green" wrote in message > news:mailman.1027705851.8443.python-list at python.org... > > So I know what lambda functions are, their syntax and how they're > used. > > However I'm not sure *why* one would use a lambda function. What's the > > advantage that they offer over a regular function? > > They let you put short, one-time functions inline. In some > environments (Tkinter comes immediately to mind) there > are lots of places where short, one-line functions are useful. > Putting a short, one-time function inline aids readability, > (at least for people who regard lambdas as readable.) > > IMO, if the function is of any significant length, or if it > duplicates functionality from elsewhere, it should be > named and written separately. > And let us not forget that those who hate naming one-off functions can reuse the names if they want. def a(x): print x def a(y): print y*y is perfectly legal Python. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From daniel.dittmar at sap.com Tue Jul 23 11:32:08 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 23 Jul 2002 17:32:08 +0200 Subject: Make me beautiful (code needs help) References: Message-ID: Mark wrote: > Ok, I have the following data: > > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] > > That is, I want to get the successive differences into their proper > place. I don't care what is in the question mark spot. I'll figure > that out later. > > Here's my current code: > > for i in range(len(data["A"])): > try: > data["new"].append(data["A"][i] - data["A"][i-1]) > except OutOfBounds: > data["new"].append("?") > from __future__ import generators def difference (collection): iterator = iter (collection) yield None last = iterator.next () for current in iterator: yield current - last last = current print list (difference ([])) print list (difference ([1,2,4,10,50])) It's a bit longer, but it works with any collection that is iterable. > Now, the other problem, is that in general, I want to fill > data["new"] with an arbitary function of the values in data["A"]. As > a dumb example, I might want to fill data["new"] with copies of the > mean (average) of data["A"]. So, in some cases, the new values are > relative to the current location (ie i and i-1) and in other they are > absolute (ie all of them). If you want a moving average, then the solution above is easily generalized. If you want the simple average, then a simple function should be sufficient, there is no need to over generalize. def avg (values): sum = 0 for value in values: sum += value return sum / float (len (values)) Daniel From trentm at ActiveState.com Wed Jul 10 14:02:07 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 10 Jul 2002 11:02:07 -0700 Subject: HT download from activstate? In-Reply-To: ; from K.Rdt@TU-Berlin.DE on Wed, Jul 10, 2002 at 07:47:32PM +0200 References: Message-ID: <20020710110207.A3184@ActiveState.com> [Klaus Reinhardt wrote] > --------------------------------------------------------------------- > Hi > > I tried to get the python-module for > ping, > but run in a circle. I presume you are talking about PyPPM that comes with ActivePython. This is what I get: H:\>pyppm install ping Created PyPPM configuration file in C:\Python22\pyppm.xml Installing package 'ping'... Connecting to SOAP server ActiveState Package Repository... (fetching ping-1.0.0.0.win32.2.2.zip) [ 16, 10 ] ************************************* [ 162 ] entering install binary... ping-1.0.0.0.win32.2.2.zip Trying to inflate and install downloaded binary ping-1.0.0.0.win32.2.2.zip in di rectory C:\DOCUME~1\trentm\LOCALS~1\Temp/ping-1.0.0.0.win32.2.2 Decompressing the archive ping-1.0.0.0.win32.2.2.zip... Archive format recognized as: ZIP file Inflating 'ping-1.0.0.0.win32.2.2.zip'... creating ping-1.0.0.0 creating ping-1.0.0.0\build creating ping-1.0.0.0\build\lib installing the package using setup.py script running install running install_lib creating C:\Python22\Lib\site-packages\ping copying build\lib\icmp.py -> C:\Python22\Lib\site-packages\ping copying build\lib\inet.py -> C:\Python22\Lib\site-packages\ping copying build\lib\ip.py -> C:\Python22\Lib\site-packages\ping copying build\lib\ping.py -> C:\Python22\Lib\site-packages\ping copying build\lib\traceroute.py -> C:\Python22\Lib\site-packages\ping copying build\lib\udp.py -> C:\Python22\Lib\site-packages\ping byte-compiling C:\Python22\Lib\site-packages\ping\icmp.py to icmp.pyc byte-compiling C:\Python22\Lib\site-packages\ping\inet.py to inet.pyc byte-compiling C:\Python22\Lib\site-packages\ping\ip.py to ip.pyc byte-compiling C:\Python22\Lib\site-packages\ping\ping.py to ping.pyc byte-compiling C:\Python22\Lib\site-packages\ping\traceroute.py to traceroute.py c byte-compiling C:\Python22\Lib\site-packages\ping\udp.py to udp.pyc creating C:\Python22\Lib\site-packages\ping.pth Removing downloaded files... Package ping was successfully installed > What's my mistake? What did you do and what output did you get? Cheers, Trent -- Trent Mick TrentM at ActiveState.com From pinard at iro.umontreal.ca Fri Jul 12 11:09:39 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 12 Jul 2002 11:09:39 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C7C@hendrix.empolisuk.com> References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C7C@hendrix.empolisuk.com> Message-ID: [Harvey Thomas] > > The main goal of XML was to please machines, because full SGML is so > > difficult to parse. > I think you should substitute "software writers" for "machines". Of course. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mbelanger_NOSPAM at NOSPAM_pixelsystems.com Wed Jul 31 12:42:37 2002 From: mbelanger_NOSPAM at NOSPAM_pixelsystems.com (Mathieu Belanger) Date: Wed, 31 Jul 2002 12:42:37 -0400 Subject: Console Installation References: Message-ID: Thanks for all your answers, it will be very useful! I've tested the Wise installer in silent mode and it works fine but not as expected. The problem is that I want to be able to specify the directory like this: >python-2.2.1 /s d:\python22 or something like that!! But the installer always install it in c:\python22! Is there a way to specify the path? Thanks again! From hst at empolis.co.uk Tue Jul 23 06:47:21 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 23 Jul 2002 11:47:21 +0100 Subject: good books Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C9D@hendrix.empolisuk.com> RPM1 wrote: > Sent: 23 July 2002 11:37 > To: python-list at python.org > Subject: Re: good books > > > I agree. > > > "Dave Cinege" wrote in message > news:mailman.1027405211.16343.python-list at python.org... > > On Tuesday 23 July 2002 2:13, Percy Tambunan wrote: > > > what is a good book in python, If i can only afford to > buy just one > book? > > > > IMO Python 2.1 Bible, www.hungryminds.com > > > > -- > > The time is now 22:48 (Totalitarian) - http://www.ccops.org/ > > > > > > > > And I _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From trentm at ActiveState.com Tue Jul 30 17:49:23 2002 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 30 Jul 2002 14:49:23 -0700 Subject: Console Installation In-Reply-To: ; from tim.one@comcast.net on Tue, Jul 30, 2002 at 05:23:35PM -0400 References: Message-ID: <20020730144923.B11800@ActiveState.com> [Tim Peters wrote] > [Mathieu Belanger] > > We have many PC installed everywhere in the entire country (Canada) and > > we want to install python 2.2 on each one. The only way for now to do > > that is to log into each PC with PCAnywhere and run the Wise installer. > > It is a way too slow. > > > > Is there a console installer that don't have to be interactive?? > > I've search for that everywhere and didn't find anything! > > > > All our PC run WinNT4. > > If that (particularly /S) doesn't do the trick, I'd suggest contacting > ActiveState. Their installer (well, at least one of them) is built on MSI > technology, which may be more friendly to remote admin-driven installation. ActivePython packages are .msi's (i.e. Windows Installer tech). Here are command line options that you can use to install any .msi package (and thus ActivePython). http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/over_73eb.asp ActivePython's installation notes show you how to install silently from the command line: http://aspn.activestate.com//ASPN/Reference/Products/ActivePython/RELEASE.html#windows%20(x86) like this: C:\> msiexec /i /q As well, I have heard of one being able to remotely install MSI packages via Microsoft's SMS (Systems Management Server). However, I have no experience with it. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From jb at cascade-sys.com Wed Jul 10 21:11:43 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 10 Jul 2002 18:11:43 -0700 Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: <3D2CDB4F.4357F810@cascade-sys.com> Tim Daneliuk wrote: > I want to write a program which goes to specific registry locations and > scrubs out the MRU cruft left behind by so many programs. So, for example, > say I've edited a bunch of Word docs, I want to run a script from the scheduler > which periodically goes in and removes the MRU entries. Yeah, sure. I bet what you REALLY want is to scrub your MRU list of all those Porn pix you downloaded. ;o) Anyway the win32api module that comes with the standard pythonWin distribution includes all (IIRC) the registry functions. There's a help file that documents the calls. Whatzizname's Python Windows book is worthwhile if you're doing much. [ Doesn't this belong on c-l.py? ] Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From SBrunning at trisystems.co.uk Mon Jul 1 05:50:49 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 1 Jul 2002 10:50:49 +0100 Subject: How to get rid the new line Message-ID: <31575A892FF6D1118F5800600846864DCBD473@intrepid> > From: Frank Tobin [SMTP:ftobin at neverending.org] > I think the fact that the first few tries here were *wrong* about how to > implement a chomp indicates that it really should part of Python. Just > because it's easy to implement doesn't mean it can't be part of the, say, > string methods. I mean, look at str.{upper,lower,isdigit}, etc. A chomp > method would be popular; rstrip or implementing your own doesn't cut it. It will be, in all but name. See . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From duncan at NOSPAMrcp.co.uk Tue Jul 9 07:18:51 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 11:18:51 +0000 (UTC) Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: Alex Martelli wrote in news:zWvW8.46426$Jj7.1307017 at news1.tin.it: > What I see as the fallacy of "information hiding" as an active purview > (having pursued it diligently for lo those many years) is that it > reflects and responds to an assumed underlying "pecking order" which, > upon reflection, is not a best fit for most projects. To wit: the > designers of libraries and frameworks do an excellent job defining > exactly what functionality the client-code programmers need; those > client-code programmers, on the other hand, are rater clueless blokes > who'll trample all over the carefully designed library / framework > architecture unless strictly held in check for their own good. I wonder if it is worth making a distinction between "information hiding" and "information protection". Python supplies a limited form of hiding, which can be useful in cases where you want to ensure that subclasses don't accidentally reuse the same member names. It can be circumvented easily and fairly cleanly in those cases where you really need to get at a member that has been hidden. A greater use of Python's private members could be useful in some of the library, for example htmllib would be easier to use if you didn't have to know to avoid members such as self.literal, self.stack, self.offset which don't even appear in htmllib but only in its base classes. C++ provides a limited form of protection without actually hiding anything. This is rarely useful for anything. It can be circumvented easily but only by using nasty kludges. I am sorry to admit that I have been reduced to using '#define private public' just before including a header file for a library that went too far in its use of 'private' members. > The way some people are going ballistic about using self.whatever > (rather than typical C++'s m_whatever, &c) can be seen as either > tragic or ridiculous -- I'll choose the latter viewpoint, most > particularly given the temporal coincidence with yet another > round of the recurring saga of the joiner.join haters... May I just apologise for triggering that last thread: I posted a followup to a question about join, and then went on holiday for two weeks before the message had left my outbox. Naturally by the time I got back the thread had died out but the belated escape of my followup retriggered it. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From fredrik at pythonware.com Wed Jul 3 09:50:11 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jul 2002 13:50:11 GMT Subject: newbie question on Fredrik Lundh's simple script References: Message-ID: John Boik wrote: > Here is the problem. The frame pops up OK, but when I press the Quit button > nothing happens. When I press it twice, Python shuts down. I assume "Python" means "the IDLE environment" ? IDLE executes Python code inside it's own interpreter, and is also using Tkinter. If you run a program inside IDLE that shuts Tkinter down, you'll also shut IDLE down. That's really IDLE's fault, not Tkinter's... I recommend running the samples in a stand-alone Python interpreter, from the command line. (or use an IDE that knows how to run Python programs in a separate process...) From aleax at aleax.it Tue Jul 9 10:17:30 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 14:17:30 GMT Subject: sorting many arrays from one... References: Message-ID: <_fCW8.48028$Jj7.1333638@news1.tin.it> Shagshag13 wrote: > > "Duncan Booth" a ?crit dans le message de news: > Xns924692F5BE4Cduncanrcpcouk at 127.0.0.1... > >> drive, other1, other2, other3 = map(list, zip(*aux_list)) > > fine ! and with map ! but i still have another question i didn't > understand how this works (i think i didn't get zip(*aux_list)) Using *whatever as an actual argument to any function f passes the items of whatever, one after the other, as the actual arguments of f. So, zip(*aux_list) is just like zip(aux_list[0], aux_list[1], aux_list[2]) and so on for however many items aux_list has. All clear so far? Now, what zip does is: for each argument take the first item and zip them into one tuple; then for each argument take the second item and zip them into a second tuple; and so on until the shortest argument is exhausted -- then, done, return the list of all the tuples. So, here zip(*aux_list) returns a list where: the first item is a tuple made up of -- first item of aux_list[0], then, first item of aux_list[1], then, first item of aux_list[2], and so on. But the way we built aux_list, those "first items" are exactly the items of the 'drive' list. So, the first item of zip's return list is (a tuple form of) the sorted 'drive'. Similarly, the second item is a tuple form of 'other1' permuted according to the sort on drive, etc, for a total of four tuples in our case. All that map has left to do is turn each tuple into a list again. Basically this is what I meant by mentioning that (in a sense -- specifically, only for sequences all of the same length, and net of list vs tuple considerations) zip is its own inverse. zip(*zip(wha,te,ver)) == [wha, te, ver] if the sequences wha, te, and ver, are all tuples of the same length... Alex From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 12:08:04 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 12:08:04 -0400 Subject: Castalian: the Active Server Pages object model for Python-embedded HTML pages References: Message-ID: <3D207E64.6030309@removethisandallhyphens-o-n-e.net> I've done something very very similar with a project I'm working on and found it quite useful. Maybe we should colaborate some? - my system allows for page generation at runtime, or at 'build' time, allowing you to generate many pages from a db query or other data source... its closer to jsp than asp in the sense that you have to compile your pages with my system. Hrm, let me post this on the web and lets compare notes. -c Stuart Langridge wrote: > I've written a thing that provides the Active Server Pages object model to > Python embedded in HTML pages; that way, those of you who think of CGI stuff > in terms of Request.Querystring and Response.Cookies can use Python in pages > on Apache. > > The code might look something like: > > > Hello, world! > > Hello, world! (from HTML)
> response.write("Hello, world! (from Castalian)
") > > import os > response.write("Your environment variables are:
") > for i in os.environ.items(): > response.write("%s=%s
\n" % i) > > if request.querystring.has_key("foo"): > response.write("The 'foo' variable in the querystring was:") > response.write(request.querystring["foo"]) > ?> > > > > I'd be interested in comments; Castalian implements a reasonable > proportion of the ASP object model, and it's been used in some > reasonable-sized projects. > > Code available from http://www.kryogenix.org/code/castalian/. > > sil > > -- > 2. Make it halfway normal. I don't have any use for > laser-beam-shooting pocket combs, or non-existent existents existing > within their own existences, or ballpoint pens made out of lettuce. > -- CardinalT dictates rules for the raif Silly Game > From cliechti at gmx.net Mon Jul 22 19:58:36 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 01:58:36 +0200 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> Message-ID: Peter Hansen wrote in news:3D3C971E.D0386D7D at engcorp.com: > Paul Rubin wrote: >> >> Stefan Schwarzer writes: >> > > Just to not have to say "foo.foo()" or "from foo import foo". >> > > If the main purpose of the module is to provide one function, I >> > > think it's cleaner to be able to import the module and call the >> > > function without special tricks. >> > >> > I consider it cleaner to be explicit, and import the module and >> > call its function. :-) >> >> Does that reasoning not also apply to class instances? Why should >> class instances be callable through the __call__ method? > > Because that's how you create an instance of the class (i.e. an > object). no, no, read again... he already talks of instances, not classes. i.e. the __call__ method. > If you have a reasonable parallel for all modules _in > general_ then *that* would be the one reasonable case in which to use > this scheme. I can't think of a good one, myself. > >> > How many actual cases do you know of where a module has a single >> > function? Aren't they rare? >> >> I've written several, there are several in the Python library, and >> remember that it's not necessary for the module to have a single >> function for a __call__ interface to be useful. __call__ makes sense >> if there's a most-important or most-frequently-used function in the >> module. It's ok if there are other functions too. > > Although you can do as you wish, of course, I want to chime in > with a "this is a really bad idea" and hope you don't follow through > on it. This is, even in the best case, going to make your code > less readable to anyone else. It is also likely to cause > maintainability problems because making the claim "but this module has > only one function!" almost certainly means it will not stay that way > forever. no need for such a restriction. just because an object has a __call__ method does not mean that it must not have any others. a module is an object after all, so there is realy no good reason to prevent it from having a __call__ method... > Any time you find yourself going to a lot of effort to work around > what feels like a small wart or syntactical ugliness (neither of which > even apply in this case, IMHO) you should probably stop yourself and > say "whoa, what was I thinking?" and do it the standard way. yeah, its not realy needed. however having a __call__ function in modules would be nice for plugin systems, where a plugin == a module/file.py. it would allow to init the plugin by calling the module instead of defining an init() function or whatsoever. considering the backwards incompatibility, it makes no sense to add a __call__ right now. chris -- Chris From m.faassen at vet.uu.nl Thu Jul 11 02:39:03 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 11 Jul 2002 06:39:03 GMT Subject: Python in the enterprise: Pros and cons References: <7xbs9fta42.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: [snip snip] > Python is ready for some applications and getting there for others. > It has a lot of virtues and to be clear about it, I like Python better > than Java for most purposes. However, Python's advocates often don't > acknowledge that there are still areas where Python genuinely does > fall behind. We need to stay aware of Python's shortcomings so we can > acknowledge them and/or fix them. I think that this is a very good point to make. I thought the article to be a pretty fair assessment overall (though one can quibble over some points), and it certainly wasn't negative about Python. Python has a lot of good stuff going for it, but it's not perfect either. Quibble: I've been using ODBC in PythonWin since '98 and it's quite free. ;) I'm sure it's limited but sufficient for the little things I do with it. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From jb at cascade-sys.com Thu Jul 11 00:46:04 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 10 Jul 2002 21:46:04 -0700 Subject: Win32 Registry Manipulation w/PythonWin? References: <3D2CDB4F.4357F810@cascade-sys.com> <005b01c2288a$f3bad1e0$0101010a@local> Message-ID: <3D2D0D8C.8F8B2121@cascade-sys.com> Chris Gonnerman wrote: > ----- Original Message ----- > From: "James J. Besemer" > > > > Whatzizname's Python Windows book is worthwhile if you're doing much. > > Would that be Percival Whatzizname or Bartholomew Whatzizname? http://www.oreilly.com/catalog/pythonwin32/ My email filters back-fired and filed most of this thread (with a tundraware.com to or from) into a folder for a different list, wherein the lazy allusion should have sufficed. Also this explains they otherwise confusing "why isn't this in c-l.py?" -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From tchur at optushome.com.au Wed Jul 10 14:55:30 2002 From: tchur at optushome.com.au (Tim Churches) Date: Thu, 11 Jul 2002 04:55:30 +1000 Subject: Open Source Metaphysics (OT) References: <5.1.0.14.0.20020709164326.00a19140@mail.thewebsons.com> Message-ID: <3D2C8322.9C3AE7C8@optushome.com.au> Ben Ocean wrote: > > Hi; > This is a request for help. If metaphysics interests you, read on. If not, > you probably want to skip this email. > > I'm building a Web site to create open source metaphysics. There are many > reasons and methodologies, but here are some: > * Create a _science_ out of numerology by basing it in the study of taxonomy > * With that foundation, create a science out of all matrix-based > metaphysical systems, including astrology, the I Ching, the Enneagram, etc. > * Enable an open source community to develop the same > > There's much more to it, but I want to be as brief as possible here. What > I'm looking for is a few competent and trustworthy programmers who would be > willing to help me build this. There is no money involved: this is a work > of love. Ben, The resident metaphysician on python-list is David Mertz PhD. I'm not at all sure whether he is in a position to assist you, but you might want to visit his company's Web site at http://www.gnosis.cx - you will notice that they are currently having an ideational clearance sale, so you might be able to pick up some ideas for your project quite cheaply. You also mention matrix-based metaphysical systems. I think you should look into numarray, the successor to Numerical Python, and talk to its developers about incorporating support for the data types you might require for your project. Hope this helps... Tim C From pinard at iro.umontreal.ca Mon Jul 8 18:27:47 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 18:27:47 -0400 Subject: stackless python In-Reply-To: References: <20020708102618.A4681@glacier.arctrix.com> Message-ID: [Neil Schemenauer] > Here's [two] examples: > http://aspn.activestate.com/ASPN/Mail/Message/602876 I slightly changed it so it runs on Python 2.2.1. Appended below. > http://aspn.activestate.com/ASPN/Mail/Message/602993 The code contained two examples, the second of which is incomplete. The first is adapted, below. Thanks for providing these exercises! -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: essai1.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: essai2.py URL: -------------- next part -------------- -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From claird at starbase.neosoft.com Wed Jul 10 08:40:57 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 10 Jul 2002 07:40:57 -0500 Subject: expect module and/or functionality? Or SSH wrapper module? References: Message-ID: <68709B52CA2675FB.DA66E2B49118728A.A93C4D4E1CA0B0B6@lp.airnews.net> In article , Michael Hudson wrote: >claird at starbase.neosoft.com (Cameron Laird) writes: > >> If not, no, you can't Expect with pure Python; there's no >> practical way to get the pseudoterminal munging right without >> calls into the C run-time library that Python itself can't >> access. > >Huh? You have openpty, forkpty, ioctl, setsid, setpgrp, ... what more >do you want? . . . World peace. I'm concluding my counsel was ill-advised; maybe people shouldn't be listening to me. As of 2.2, (now-deprecated) pty was still the distribution module, not openpty or forkpty. I fear that my pettiness came across as a reflection on the great work done by Lance Ellinghaus, Thomas Wouters, and others on these modules. This would be an injustice. I overreacted to early re- leases that didn't work smoothly for other-than-Linux, and/or were not installed by default. I do want to emphasize the distinction between the modules you've listed above and, for example, PySSH, which operates at a higher level, as does Expect, also. As a programming interface, openpty, forkpty, and so on are rather Unix- centric. Thanks for correcting the errors I introduced. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From tim.one at comcast.net Thu Jul 25 22:35:11 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 25 Jul 2002 22:35:11 -0400 Subject: how to count lines in a file ? In-Reply-To: <200207261211.48567.rjones@ekit-inc.com> Message-ID: [Richard Jones] > ... > But something has changed - files aren't closed reliably in > Jython when they are in CPython. That isn't "a change", though. These three have always been true, and still are: 1. CPython uses refcounting. 2. Jython doesn't. 3. Python's Language Reference manual doesn't define when unreachable objects are collected, and explicitly warns that an implementation may even choose never to collect unreachable objects; it "strongly recommends" to invoke close()-like methods rather than just hope. None of those are likely to change, either . From anton.wilson at camotion.com Wed Jul 31 12:46:51 2002 From: anton.wilson at camotion.com (anton wilson) Date: Wed, 31 Jul 2002 12:46:51 -0400 Subject: a soft real-time system using python References: <20020731145848.GC1800@unpythonic.net> Message-ID: <200207311646.MAA07767@test-area.com> On Wednesday 31 July 2002 12:33 pm, anton wilson wrote: > O > > > A realtime system places an upper bound on all operations, but the very > > nature of Python makes this impractical if not impossible. > > > > An interaction between Python's handling of the GIL and the platform's > > pthread library is going to be the least of your problems if you > > actually intend to deliver a system which gives realtime guarantees on > > Python programs. > > > > Jeff > > If the soft-real-time system we use makes simple function calls and only > uses simple datatypes and possibly tuples, what are some of the potential > pitfalls we could run into? I understand the deallocation issue and the > garbage collection issue. (Does garbage collection have to be enabled?) Can > we somehow get an idea on the worse case time delays in python using only > simple function calls and assignments with small tuples and simple > datatypes? For further information, we're already having a certain problem where python threads seem to drastically decrease performance in the middle of the program for around a second. Garbage collection has been disabled, but it's possible that there is some other behind-the-scenes work that Python is doing. What other things should we be worrying about? I need a more complete understanding of what can happen or is happening that would affect consistent running of a python program. Anton From xeon at dacreations.cjb.net Fri Jul 19 14:38:59 2002 From: xeon at dacreations.cjb.net (xeon) Date: 19 Jul 2002 11:38:59 -0700 Subject: importing custom modules Message-ID: Hi, I'm new at python. I'm under the impression that 'import' searches the lib directory as defined in PYTHONPATH env. variable. Is there any way to load my own modules located outside the lib directory, but leaving the lib modules access intact (without changing the env. variables), from inside the intepreter? TIA From stefan.heimann at web.de Sat Jul 20 11:12:19 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 20 Jul 2002 15:12:19 GMT Subject: XSLT processor Message-ID: Hi! I need a XSLT processor for an application written in Python. Ok, there are some processors out there for python, but I need something special: I want to register my own templates. Imagine a code like that: fun foo(node): pass processor = XXLTProcessor() processor.registerTemplate('/bar/x/y', foo) # ... processor.run(xmlInputFile) Now, every time the pattern '/bar/x/y' is matched, the function foo is called with the current context node as parameter. I hope it is clear what I mean. Saxon - a XSLT processor written in Java - provides such an internal API. Does anyone know if there is something similar for python? Bye Stefan From aleax at aleax.it Fri Jul 12 10:03:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 14:03:28 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <93DC3CC822A7272F.07F7EC43197B112B.AD4BC7C14A3B6591@lp.airnews.net> Message-ID: Cameron Laird wrote: > I know just what'll help you feel better, Alex--thoughts > of the RDBMS vendors advertising that their datastores > have magically become the best places in the world to > keep all your tree-structured data. > > The part that might shock you is that I agree with them > occasionally. A well-implemented RDBMS is an excellent place in which to keep data with whatever structure -- you just have to ensure you represent that structure as a normalized relational form, to get all the benefits. ?E.g., each parent <-> children relation in a tree is a 2-column table of (parentid, childid), for example. I have nothing against building "richer" structure automatically on top of relational power -- indeed, that's a good part of what AB Strakt's application framework is all about. But I've always been wary of using specific RDBMSs' datamodel extensions (such as, e.g., PosgreSQL's "inheritance", tempting though it may be) -- and so far I've managed to prosper without ever tying any production system to any of them. Maybe if I'd ever had to do serious, 'production' OLAP, e.g., I'd feel differently. But I doubt XML's existence is going to change things all that much. The ability to export some query's results as XML -- and import such XML back to do inserts/updates -- sounds like a perfectly reasonable utility to have for a RDBMS, just like long-standing similar abilities for CSV and other textual file formats. Again, such extras need not alter the RDBMS's relational abilities -- I most definitely hope they don't! Somebody else commented that "XML databases" are a good idea because some programmers are bad at designing relational schemas. . Now THAT is an idea that sends shivers down my spine. Maybe I'm just too pessimistic, but I'd really like to look at the relational schemas autogenerated from DTD's or whatever -- and if the underlying relational stuff isn't there, or isn't at all accessible, then please include me out of such plans. Maybe I _am_ getting better understanding of where the anti-XML rage comes from. A few years of such prospects, and I might start on an anti-XML crusade too, if I don't watch myself...:-). Alex From aleax at aleax.it Sun Jul 21 16:39:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Jul 2002 22:39:51 +0200 Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? In-Reply-To: References: Message-ID: On Sunday 21 July 2002 10:33 pm, David LeBlanc wrote: > > > > I do hope Ascher and Lundh find the time to update "Learning" to > > 2.2 very soon, of course. But if they don't, it's still a good > > book indeed. There are other good books, but "Learning" is still > > my first recommendation to a programmer experienced in other > > languages who wants to get started with Python on the right foot. > > > > (Bias warning: working with David on the Python Cookbook has made > > us friends -- but I liked Learning Python even before then!-). > > > > > > Alex > > You know, I have a book called "Learning Python" (O'Reilly & Associates; > ISBN: 1565924649; (April 9, 1999)), but this version is written by Mark > Lutz, David Ascher and Frank Willison (Ed.) - is the Ascher/Lundh book a > different version? Sorry! I did mean Lutz -- "Lundh" was a Freudian slip here, no doubt. Alex From keith_s at ntlworld.nospam.com Fri Jul 26 07:54:43 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Fri, 26 Jul 2002 12:54:43 +0100 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> <3D3EFC18.30705@ntlworld.nospam.com> <3D412292.1030608@ntlworld.nospam.com> Message-ID: <3D413883.4000004@ntlworld.nospam.com> Chris Liechti wrote: > just return some real data, "print 'hello'\n" or so. > and i think you can exit the interactive loop by raising an EOFError > exception. Unfortunately returning any real data still loops. I guess interact is not what I'm looking for, then. I want a C function (that is a Qt slot which responds to a signal that the user has hit return in a QLineEdit widget) to send a string to the Python interpreter in much the same way as the interactive shell does, with the interpreter waiting for more input if required. - Keith From donnal at donnal.net Sun Jul 21 09:52:29 2002 From: donnal at donnal.net (Donnal Walter) Date: 21 Jul 2002 06:52:29 -0700 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> <918bc22f.0207200441.7a5a130d@posting.google.com> Message-ID: <918bc22f.0207210552.56806903@posting.google.com> Syver Enstad writes: > If you want to build you're own TestSuite with all methods prefixed > with test, you can do like this: > > suite = TestSuite() > suite.addTest(unit.cell_unit.Test('test1')) > suite.addTest(unit.cell_unit.Test('test2')) > > There is a TestLoader class (or hierarchy I can't remember) in > unitttest.py that will do this automagically for you by introspecting > your module and sucking out all TestCase derived classes and building > TestSuite objects with all 'test' prefixed methods. > > As for me I just put: > > if __name__ == '__main__': > unittest.main() > > In the bottom of my module and I can just run the module and it will > be done for me. Yes, from the responses here that does appear to be the conventional way of doing things, so I guess I will continue using unittest this way too. I had thought I might replace my batch files with a TestSuite, but I'm really not complaining about the way it works now. Thanks. Donnal Walter From jonathan at onegoodidea.com Tue Jul 30 07:42:24 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 12:42:24 +0100 Subject: lexing nested parenthesis References: Message-ID: On 29/7/2002 4:57, in article mailman.1027915180.16513.python-list at python.org, "Dave Cinege" wrote: > IE > if 1 and (var1 or ?(-d /etc/)): > > I want to find ?(.*), but not runneth under or over. While the general case is impossible with regular expressions as other people have already described eloquently, the particular example you gave is trivial: >>> import re >>> >>> text = 'if 1 and (var1 or ?(-d /etc/)):' >>> >>> matcher = re.compile( r'\?\(([^()]*)\)' ) >>> match = matcher.search( text ) >>> match.group( 0 ) '?(-d /etc/)' >>> print match.group( 1 ) -d /etc/ >>> If you know that you can't have parentheses *within* the ?(...) construct, then parentheses outside of it are of little importance. You can also write fairly complex regular expressions that allow parentheses inside the ?(...) if they are within single quotes. For instance: >>> text = r"if foo and (bar or ?(-d 'silly\')dir'))" >>> >>> matcher = re.compile( r"\?\((([^()']+|'([^'\\]|\\'|\\\\)*')*)\)" ) >>> match = matcher.search( text ) >>> match.group( 0 ) "?(-d 'silly\\')dir')" >>> print match.group( 1 ) -d 'silly\')dir' >>> However, If you mean that you want to find expressions of the form: ?( ... ( ... ) ... ) then you're gonna have to write a parser. Jonathan From dreed at capital.edu Wed Jul 31 09:18:51 2002 From: dreed at capital.edu (Dave Reed) Date: Wed, 31 Jul 2002 09:18:51 -0400 Subject: Python Cookbook dict problem In-Reply-To: <20020730224427.GA14027@nullcube.com> (message from Aldo Cortesi on Wed, 31 Jul 2002 08:44:27 +1000) References: <200207302001.g6UK1Rc07994@localhost.localdomain> <20020730224427.GA14027@nullcube.com> Message-ID: <200207311318.g6VDIpu15107@localhost.localdomain> > From: Aldo Cortesi > > Thus spake Dave Reed (dreed at capital.edu): > > > > > I'm trying the following Python Cookbook recipe with python2.2 > > > > > > def makedict(**kwargs): > > return kwargs > > data = makedict(red=1, green=2, blue=3) > > def dodict(*args, **kwds): > > d = {} > > for k, v in args: d[k] = v > > d.update(kwds) > > return d > > tada = dodict(*data.items(), yellow=2, green=4) > > > > > > but I get an error with the last line: > > >>> tada = dodict(*data.items(), yellow=2, green=4) > > File "", line 1 > > tada = dodict(*data.items(), yellow=2, green=4) > > ^ > > SyntaxError: invalid syntax > > > > What's wrong? > > > Dave, > > > Python expects you to do positional and keyword argument > unrolling at the end of the function argument list (i.e. > after all "normal" arguments). Change the last line to: > > tada = dodict(yellow=2, green=4, *data.items()) Thanks. Did something change in Python versions or is it a typo in the book? Dave From b.maryniuk at forbis.lt Mon Jul 8 05:36:14 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 8 Jul 2002 11:36:14 +0200 Subject: PKSC1 Message-ID: <200207081136.14578.b.maryniuk@forbis.lt> Hi all. Somebody heard something about PKSC1 for Python? Very shortly: this is a signature operation stuff for banking. Thank You much. -- Sincerely yours, Bogdan M. Maryniuck LILO, you've got me on my knees! (from David Black, dblack at pilot.njin.net, with apologies to Derek and the Dominos, and Werner Almsberger) From aleax at aleax.it Mon Jul 22 02:23:20 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Jul 2002 06:23:20 GMT Subject: maximum recursion depth References: Message-ID: Paul wrote: > I think I will rewrite my code using loops. This will be possible, I just > have to put my braincells back in active mode :-) Yes, any recursion can be systematically removed. Easier in a language with GOTO, but, worst case, one can use the "trivial form of Jacopini- B?hm" which shows how to map any flow diagram into a while loop with a switch as the body (if/elif tree as the body, in Python). Most often, one can do better in terms of both readability and performance. Alex From mike at bindkey.com Thu Jul 25 20:20:24 2002 From: mike at bindkey.com (Mike Rovner) Date: Thu, 25 Jul 2002 17:20:24 -0700 Subject: str() inconsistency Message-ID: Why it's not a bug: >>> 4.4 4.4000000000000004 >>> `4.4` '4.4000000000000004' >>> str(4.4) '4.4' >>> str([4.4]) '[4.4000000000000004]' IMHO, str() shall call str, not repr on complex objects. Regards, Mike From gerhard.haering at gmx.de Wed Jul 17 23:23:25 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 18 Jul 2002 03:23:25 GMT Subject: SSL support in 2.2.1/win References: <3d362ab9@duster.adelaide.on.net> <3d362d71@duster.adelaide.on.net> Message-ID: Gerald Squelart wrote in comp.lang.python: > Oh, and I've just tried with python/cygwin, linux and bsd, they all > have SSL built-in... So, why the inconsistency?... Because up to now, the Python win32 core developers (i. e. Tim Peters) didn't have the time/energy to fix it. This is being addressed now by a patch on Sourceforge. Btw. your quoting sucks. You might want to read http://www.uwasa.fi/~ts/http/quote.html > "Gerald Squelart" wrote in message > news:3d362ab9 at duster.adelaide.on.net... It's called an attribution line, not an attribution novel. >> I'd just like to be able to give my little program to friends and tell > them ^^ This b0rken quoting is an Outlook (Express) misfeature. There are technical solutions for fixing Outlook Express or you can just use a real newsreader. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mlai at intrinsyc.com Mon Jul 15 13:39:46 2002 From: mlai at intrinsyc.com (max) Date: 15 Jul 2002 10:39:46 -0700 Subject: Serial Port Returning Garbage. Why? Message-ID: Hi. I need some help. I've been trying to establish a bi-directional serial communications link between two microprocessors with a python script. The link is used by a 'master' processor to transmit commands to a 'slave' processor, while also allowing the 'slave' to return any output back to the 'master' for analysis. The information garnered from the 'slave' is used to determine subsequent actions. Here's some background on the 'master' and 'slave': 'Master': Processor: sa1110 Serial Connector: 3-wire OS: linux 4.0 Python Version: 2.0 'Slave': Processor: irrelevant Serial Connector: 3-wire OS: irrelevant Python Version: not applicable Now, when individually connected to HyperTerminal, both the 'master' and the 'slave' work perfectly. I can see that the master correctly sends the command with a carriage return at the end. Likewise, inputting a command to the 'slave' through HyperTerminal results in expected behaviour, with output that should be detectable by the 'master' if the two processors are connected together. However, this isn't the case. Whenever I display the output sent by the 'slave' in an SSH terminal connected to the 'master', I'm supposed to get a prompt that looks like "IBoot>", at which I write my commands. Instead, I get garbage that looks like the following: IBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: Invalid command.^M^JIBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: Invalid command.^M^JIBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: I Anyway, I'm using the os module's functions to read and write to the serial port, and i'm using os.system to invoke the stty program to set the properties of the serial port connection. The reason for using stty is because the termios and fcntl modules aren't available for use. I've also tried using the global open function to generate a file descriptor, but that shows the same results as with the os module. The serial port properties appear to be properly set through stty, while timing doesn't appear to be an issue. Knowing all of this, does anyone know what could be causing the output to become garbled? Thanks Maximilian Lai Embedded Software Developer Intrinsyc Software, Inc. 10th Floor, 700 West Pender Vancouver, BC V6C 1G8 p: 604-646-7970 f: 604-801-6417 e: mlai at intrinsyc.com w: www.intrinsyc.com Intrinsyc, the 'Connected Intelligent Device Company' From pinard at iro.umontreal.ca Sat Jul 20 18:33:58 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 20 Jul 2002 18:33:58 -0400 Subject: unloading imported modules In-Reply-To: References: Message-ID: [Alex Martelli] > > > > Is it possible in python intepreter to unload imported modules? > > > No. > Use sys.getrefcount(x) to know how many references there are to object x, > be it a module or any other kind of object. When the reference count > of an object drops to 0, the object is freed (at once, or eventually). So, when the reference count of a module drops to 0, and I get that this is possible, then the module is unloaded. Isn't it? Also, I wonder if a module coming from an `.so' file be effectively reloaded. And then, if the previous copy (the memory area in which the `.so' is paged) gets freed? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From tim at worthy.demon.co.uk Wed Jul 10 14:02:44 2002 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Wed, 10 Jul 2002 19:02:44 +0100 Subject: os.path and Windows UNC paths Message-ID: <9ecef7534b.tim@worthy.demon.co.uk> I've been trying to use os.path.exists and os.path.isdir on Windows(2000) UNC paths with Python 2.2 but it doesn't seem to behanve sensibly. os.path.isdir('\\\\server\\share') returns negative result when os.path.listdir('\\\\server\\share') produces a dir listing. Checking groups.google and the Python faq I found 8.6 Why does o.path.isdir() failon NT shared directories Which implies it should work if a tralling '\\' is added but os.path.isdir('\\\\server\\share\\') still returns negative result However os.path.isdir('\\\\server\\share\\\\') returns true. Is this sensible/to be trusted. As an aside; using os.path.isdir(r'\\server\share\') results in a complaint of invalid token - I thought the r prefix meant use raw string, so why the error ? -- ___ |im ---- ARM Powered ---- From cliechti at gmx.net Sat Jul 27 16:52:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jul 2002 22:52:01 +0200 Subject: wxPython TextCtrl overwriting References: Message-ID: Chris wrote in news:res5ku4e8agpfikcscrv872s67lu1bng4g at 4ax.com: > In my GUI I'm using a fairly standard dirDialog to get a path, with a > line for manual entry or the browse button beneath. How do I write > the selected path *over* the default text currently in the box. Seems > like it should be a one-liner (.replace, .erase, .clear, > .overwrite???). Currently I am using .write, which appends it. .SetValue() and .GetValue() should help chris -- Chris From aleax at aleax.it Sat Jul 6 17:27:14 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Jul 2002 21:27:14 GMT Subject: Python version of STL multimap? References: Message-ID: Roy Smith wrote: ... > multimap container template. Exactly what I've been doing in Python > without knowing the right name for it. Not quite -- multimap is a sorted container, not a hashed one. > So, the question is, is there a standard way in Python to do multimaps, > or should I just continue to roll my own with one of the above idioms > whenever I need one? There's a recipe in the Cookbook about this, but I'm not sure it's entirely usable or complete in the online form. Summarizing: there are a few optimal choices depending on what exactly you want. For many purpose the ideal form is a dict of dicts -- the value being either True or False, if you want items to be "in" the data structure either once or not at all (set-like behavior) or a count of occurrences if you want items to be "in" the data structure a number of times (bag-like behavior). Using the set-like behavior for definiteness, and Python 2.2: Adding an item under a key (whether or not it was already there): s.setdefault(key, {})[item] = True removing an item from a key (whether or not it was previously there): s.get(key, {})[item] = False checking if an item exists under a key: s.get(key, {}).get(item, False) iterating on all items of a key, in arbitrary order: for item in s.get(key, {}): whatever(item) Basically, as you see, just about everything relies on the setdefault and get items of dictionaries. s.get(key, X) and s.setdefault(key, X) return the same value (s[key] if key in s, otherwise X) but X also sets s[key] to X if previously key wasn't in s. This representation may leave False entries as values of s[key][item] and indeed entire, useless dicts filled with False entries as values of some s[key]'s. That's OK in terms of behavior but may waste too much memory for a long-running application. So you may want to periodically recompact your data structure s at otherwise idle times: for key in s.keys(): for item in s[key].keys(): if not s[key][item]: del s[key][item] if not s[key]: del s[key] If such periodic "recompacting" is a problem then you may want to choose other idioms for "removing an item from a key", such as: try: del s[key][item] except KeyError: pass This never stores a False value explicitly and only leaves you with the possibility of empty sub-dict's at some s[key] (which you may still want to re-compact -- either at each such deletion, or periodically as above). For immediate self-compaction you could use: try: del s[key][item] if not s[key]: del s[key] except KeyError: pass However, these idioms are slower than the previously recommended ones in some common cases. If your performance is critical, try benchmarking with the various possibilities. Alex From aleax at aleax.it Thu Jul 25 09:54:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 13:54:45 GMT Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> Message-ID: Thomas Guettler wrote: ... >> Many Python functions expect to get arguments of specific types >> (or polymorphic to such types, i.e., supplying all necessary >> methods and operations with equal signatures). >> >> Having them accept arguments of wrong types, with silent coercion, >> would hurt all careful developers, by hiding bugs. > > I agree, but than the exception should have a better message: Should it? Maybe I should have written than types supplying all necessary methods and operations with equal signatures are OK too. Oh, I _DID_? Hmmm... > $ python escape.py > Traceback (most recent call last): > File "escape.py", line 3, in ? > cgi.escape(2) > File "/usr/lib/python2.2/cgi.py", line 1024, in escape > s = s.replace("&", "&") # Must be done first! > AttributeError: 'int' object has no attribute 'replace' > > > A exception with a message like: > "Argument must be a string" > > would be better No, it would be an outright LIE. Why do you think a lie would be better than the truth? import cgi class goodenuf: def __init__(self, *args): pass def replace(self, *args): return self def __str__(self): return 'gotcha!' print cgi.escape(goodenuf()) An instance of class goodenuf is of course not a string. cgi.escape is perfectly happy to accept such an instance. Therefore, if cgi.escape said that its argument must be a string, then cgi.escape would be lying through its teeth. Lying is not nice. What cgi.escape SHOULD say, if an argument is passed to it that is unacceptable, is that the argument lacks a 'replace' [callable] attribute. THAT is the actual requirement. Wait a sec -- that *IS* exactly what the exception's value is saying! Strange, isn't it? It's giving you even more information, specifically WHAT is the type of the object that is lacking a [callable, but that's not yet diagnosed at that point] 'replace' attribute. Seems a nice information to give, and costs nothing. Note that other functions in Python's standard library DO lie. And some apply the deplorable practice called type checking, so that the smooth, perfect, seamless polymorphism of writing a "good enough" implementation of the actually needed methods/signatures isn't good enough any more. But you're criticizing one of the library functions that is impeccable in these respects. It requires just the minimal amount of functionality it in fact needs from the object you pass as an argument, and lets you know that said minimal amount is missing if it is. Perfect. Therefore, I find your criticism totally unfounded. Alex From opengeometry at NOSPAM.yahoo.ca Sat Jul 6 13:54:40 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 6 Jul 2002 17:54:40 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: Thomas Jensen wrote: > Hello group (and list :-), > > I've used Python for several years (and followed this group until about 6 > months ago). I work in a small company which specialises in collecting > and procesing financial data. Most of our production environment is based > on Microsoft stuff like ASP/VBScript, VB6, WinNT, MS SQL Server, etc. > > One of the next development tasks is rewriting the nightly processing job > which is having problems with our ~100mb database (it it written in > Borland C++, but absolutely not optimized for speed!). > > The goals of the rewritten piece of software would be: > * Improved speed > * Improved scalability - parallel processing on multiple machines/CPUs > * Improved scalability - ability to handle greater databases (>1gb) > * Ability to calculate only a subset of the data > > Now, instead of rewriting the job in C++, I'd (of course) like to use > Python. However the CEO (small company, told you :-), made a couple of > somewhat valid points against it. > 1) He was worried about getting a replacement devlopper in case I left. > 2) He said, "Name 3 companies using Python for key functions" > 3) He was worried about the stability/reliability of python in our > production environment (you know, 99.999 % and all that) > > I was hoping someone in this group could help with some really > compelling arguments, as I'd really to use Python for this job. If your cronjob can tackle 1MB but not 1GB, then I don't think this is programming language issue. Rather, you should look at your algorithm and data structure. If your company is private for-profit company, then use money argument: - Anyone who knows Python or Unix shell will have the necessary analytical skills. And, there can easily be found on or . - Scaling to multiple CPU is OS issue. Much easier with Linux (no comment on Windows :-) - Scaling to GB is algorithm issue. Python makes development easier, because it's easy to write and read. Mostly, he saves money because he will be able to find right people. The fact that they happen to know the right language is just bonus. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From donn at u.washington.edu Fri Jul 5 13:33:34 2002 From: donn at u.washington.edu (Donn Cave) Date: 5 Jul 2002 17:33:34 GMT Subject: Getting Process List On *nix References: Message-ID: Quoth William Annis : | | John Abel writes: | | > I am trying to write a script, capable of running on Win32, and *nix, | > which looks for certain processes. However, I can't seem to find any | > details of how to access of list of running processes under *nix, | | Well, each different flavor of Unix is going to handle this | somewhat differently. In a lot of recent flavors you have /proc, in | which you'll find a file system representation of processes. | | > without shelling out, something I'm loathe to do. | | In this case, shelling out for the Unix side may actually be | most portable. For sure. The traditional UNIX "ps" needs kernel structures that can move or change even between minor releases of the same platform, it's the farthest thing from portable. Unfortunately, the ps command isn't much fun either - command line and output vary substantially between platforms and aren't designed for computer analysis. Missing columns, columns that run together, etc. You'll end up having to locate the columns in the header line, and use that as a reference for each line. And /proc is different from one platform to the next, too. On NetBSD, /proc/18209/status is one line, white space separated values and comma separated tuples. On Redhat Linux, it's many lines, with a more verbose format that has things like "State: S (sleeping)". Enjoy! Donn Cave, donn at u.washington.edu From spam at ob_scure.dk Tue Jul 9 04:35:14 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Tue, 09 Jul 2002 10:35:14 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2A078A.7040502@ob_scure.dk> <06F2E275AA053281.30FCDA468DD949D2.9ED8D7E798995448@lp.airnews.net> <3D2A2586.5070302@ob_scure.dk> Message-ID: <3D2AA042.2000308@ob_scure.dk> Cameron Laird wrote: > In article <3D2A2586.5070302 at ob_scure.dk>, > Thomas Jensen wrote: > . > >>The last 6 months I've been working almost exclusivly on a (commercial) >>project heavily based on SOAP (not for performance objectives though :-). >>That part really doesn't scare me :-) > > . > Let me know if you want to publicize your work. > I frequently write articles and profiles of SOAP > projects for State-side magazines (and worldwide, > when there's an opportunity). Sounds interresting, it's coded in VB/C# though. Please mail me privately if You're still interested. (I've had som problems with my email but I'm hoping to sort them out today) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From emile at fenx.com Thu Jul 4 13:54:56 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 17:54:56 GMT Subject: testing a sequence for 'identicalness' References: Message-ID: Rajarshi Guha > OK - what if I allow numbers like 1.1 and 1 to be equal (that is numbers > which are close are also consdiered to be identical) > You could do something like: >>> def isclose(list): return map(round,list) ... >>> l1 = [1]*10 >>> l2 = [.9, 1,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7] >>> s = difflib.SequenceMatcher(None, isclose(l1),isclose(l2)) >>> s.ratio() 0.69999999999999996 which might do it for an appropriate isclose() -- Emile van Sebille emile at fenx.com --------- From eugene1977 at hotmail.com Fri Jul 19 23:44:49 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Fri, 19 Jul 2002 22:44:49 -0500 Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: thank you for helping me.. i'm sure that i encoded all strings to unicode (title,url) but it still gives me error.. =) this is so cool.. what module do i need to use? pypgsql?(yet another question, how do i check which module i have in my current system?) (one more irrelevant question: is this also possible in java?) ------------------------------------------------- cursor.execute("insert into history (col1, col1, col3) values (%s, %s, %s)", (self.url, self.title, self.firsttime)) From cbbrowne at acm.org Sat Jul 13 15:44:54 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 13 Jul 2002 19:44:54 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <7x65zj60ku.fsf@ruckus.brouhaha.com> Message-ID: Centuries ago, Nostradamus foresaw when Paul Rubin would write: > Christopher Browne writes: >> I think the widespread lemming-rush to try to get _everything_ mapped >> onto XML-based formats is a demonstration that a whole lot of people >> have never even _looked at_ Lex and Yacc. >> ... >> (reverse (concatenate 'string "moc.enworbbc@" "enworbbc")) > > Or Lisp... ;-) Sure. But in that it's atypical for people to be terribly accepting of languages options that don't look a whopping lot like C, I'll go with "something related to C." Perhaps they should look at Baker's META or ASN.1, but that _does_ get pretty abtruse pretty quickly, and who has heard of them? Yacc and Lex provide nice formal ways to describe grammars, can work with the "Langues-du-jour," and it would be very instructive to see that they _are_ usable for building parsers for small languages. -- (reverse (concatenate 'string "moc.enworbbc@" "enworbbc")) http://cbbrowne.com/info/spreadsheets.html This is Linux country. On a quiet night, you can hear NT re-boot. From phr-n2002b at NOSPAMnightsong.com Fri Jul 5 01:30:09 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 04 Jul 2002 22:30:09 -0700 Subject: Copyright metaphors References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> <7xwusbyncl.fsf@ruckus.brouhaha.com> Message-ID: <7x65zukahq.fsf@ruckus.brouhaha.com> mertz at gnosis.cx (David Mertz, Ph.D.) writes: > |Is it a worse metaphor than "the copyright bargain"? That phrase has > |been around for decades or centuries and is generally considered apt. > > Hmmm... however many decades or centuries, I've never read that specific > phrase before this thread. I do have a Ph.D. in social philosophy, and > have read moderately widely in legal opinions. But I'm sure you're > right that someone has used it (and have a particular interest in recent > trends in abusive extension of IP law). The phrase is used several times in the Eldred filings and in numerous Supreme Court opinions. > But I don't agree that copyrights were ever ethically defensible to > start with; nor that they ever "advanced the progress of arts and > science" as the US Constitution allows (as a limited possibility). http://www.baen.com/library/palaver4.htm has an important speech from the 1850's(?) on the subject, by the English historian Thomas B. Macaulay who you might be familiar with. The tension between copyright and individual freedom is certainly stronger now than it was in the 1800's, for reasons RMS talks about in his speeches. In the 1800's, copying books (in enough volume to be a problem for copyright holders) was only practical with a printing press and a lot of typesetting work, making many copies of the same book. That meant copyright was more like an industrial relation than today, where it controls what individuals can do in their own bedrooms with their own computers. Anyway, we live in interesting times. From "gkrohnXvolucris.8m.com".replace Wed Jul 24 21:38:47 2002 From: "gkrohnXvolucris.8m.com".replace (Greg Krohn ("X", "@")) Date: Wed, 24 Jul 2002 20:38:47 -0500 Subject: Tk Dynamic Menus problem References: <_mH%8.156269$uw.92148@rwcrnsc51.ops.asp.att.net> Message-ID: "Jeremy Bowers" wrote in message news:_mH%8.156269$uw.92148 at rwcrnsc51.ops.asp.att.net... > On Wed, 24 Jul 2002 13:42:22 -0500, Greg Krohn wrote: > > > I'm not exactly sure why it's printing '3', but you do have a scoping > > problem there. > > Replace 'lambda: printFunc(i)' with 'lambda i=i: printFunc(i)'. Supplying i > > as a keyword arg for the lambda brings i into the labmda's scope. > > > Thanks, that did it. > > I would be interested in a bit more explanation though. In the "real" > application, "i" were instances, not numbers (if that matters). Doesn't matter as far as I know. All varaibles in Python are an object (instance). > Why would > the 'i' in the previously created lambda commands "shift" to follow the > outside value of i? > > I thought I understood Python's scoping. ;-) I thought I did, too. I wouldn't have expected the original to work at all. ...Playing with code... Yeah, I can't figure it out. What version are you using? IDE? From skip at pobox.com Tue Jul 9 15:34:33 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Jul 2002 14:34:33 -0500 Subject: File size error in os.stat with large files. In-Reply-To: <28bbdc67.0207091119.6d9ecd48@posting.google.com> References: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: <15659.15049.252265.996242@gargle.gargle.HOWL> Joe> I have a 4.2GB file that os.stat is reporting to be 164MB. Smaller Joe> files seem to work just fine, but I have not played with it to find Joe> out where the cut-off point is. Was Python compiled with large file support? -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From gmfawcett at operamail.com Wed Jul 10 06:26:18 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 10 Jul 2002 03:26:18 -0700 Subject: writing python extension modules References: <3d2b8580$1_1@nopics.sjc> Message-ID: <3d799735.0207100226.4caf6c7a@posting.google.com> "Adonis" wrote in message news:<3d2b8580$1_1 at nopics.sjc>... > is there a simple hello world style program that can show me the extreme > basics on writing python extensions, i do not need some big code just Be sure to check out Pyrex during your research: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ It works fine with MSVC. -- Graham From lac at strakt.com Wed Jul 3 09:53:51 2002 From: lac at strakt.com (Laura Creighton) Date: Wed, 03 Jul 2002 15:53:51 +0200 Subject: what's up with 'patterns'? In-Reply-To: Message from "Guyon Morée" of "Wed, 03 Jul 2002 15:29:58 +0200." <3d22fb61$0$235$4d4ebb8e@news.nl.uu.net> References: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> <3D22F5FF.9070408@mxm.dk> <3d22fb61$0$235$4d4ebb8e@news.nl.uu.net> Message-ID: <200207031353.g63DrpLM007700@ratthing-b246.strakt.com> > aha, thanx a lot! > > is this something i should really look into or is it something that only is > usefull when i am designing large systems and such? > > thanx, > Guyon > Really look into it. You will be amazed at how much time you save not inventing 'the-square-with-this-neat-bit-where-i-round-the-corners-in-this interesting-way', when you could have had a wheel. Laura Creighton From see_reply_address at something.invalid Thu Jul 4 22:06:50 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 14:06:50 +1200 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 References: <3d799735.0207041113.3a830bdf@posting.google.com> Message-ID: <3D24FF3A.4010205@something.invalid> Graham Fawcett wrote: > I ran into a hitch when trying to build an extension class on > my Win32 machine: the compiler complained with "initializer not a > constant" errors. This is a known issue in Python; see the FAQ at > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp . Thanks for pointing this problem out. I'll see if I can do something about this in a future release. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From peter at engcorp.com Thu Jul 4 00:35:30 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Jul 2002 00:35:30 -0400 Subject: Efficient python programming... References: <3D00A456.4315EDA3@engcorp.com> <3d238f6b.579164824@news.dsl.pipex.com> Message-ID: <3D23D092.4E3AD523@engcorp.com> Simon Foster wrote: > > On Fri, 7 Jun 2002 21:03:08 +0100, "James Kew" > wrote: > >I favour Kent Beck's aphorism: "Make it work, make it right, make it fast." > > > I prefer this one: > > "You can have it right" > "You can have it cheap" > "You can have it now" > > Pick any two. Interestingly, XP provides a way to have all three... From asencio at mitre.org Fri Jul 5 19:37:45 2002 From: asencio at mitre.org (Angel Asencio) Date: Fri, 05 Jul 2002 19:37:45 -0400 Subject: calling wxPython from the shell References: <3D0FD764.4937BDB4@mitre.org> Message-ID: <3D262DC9.537F083C@mitre.org> Ok, found the flag of "MainLoop", and works like a charm using BOA. (Where I developed it first) But when I tried it on PythonWin, as soon I closed it, it bomb out. I tryied on IDLEfork also, If I close first the window (in selectOneHandler.py) and then exit the main loop, works fine (gives the result) but does not close the window. Viceversa closes the window but frezzes IDLEfork. The code relative to this is on selectOneHandler.py near the bottom at the button events code. This is the command that I am putting on the shell: print(selectorHandler.getOneStr( ["alpha","beta","chi","delta"] )) Ok, now for the source code: selectorHandler.py *********************** #!/usr/bin/env python #Boa:App:SelectorApp from wxPython.wx import * import selectOneHandler import selectMultipleHandler modules ={'selectMultipleHandler': [0, '', 'selectMultipleHandler.py'], 'selectOneHandler': [0, 'Main frame of Application', 'selectOneHandler.py']} class SelectorApp(wxApp): def OnInit(self): self.slctOne = selectOneHandler.create(None) self.slctMult = selectMultipleHandler.create(None) self.toReturn = None self.selection = -1 self.slctOne.setOwner( self ) self.slctMult.setOwner( self ) return true def setOneAsMain(self): self.main = self.slctOne def setMultAsMain(self): self.main = self.slctMult def setSelectionList( self, lstString ): self.main.setSelectionList(lstString) def setSelection( self, anIntegerOrLstOf ): self.selection = anIntegerOrLstOf def getSelection( self ): return self.selection def getObjectStrings(self, lstObjects ): toReturn = [] toReturn = [ obj.__str__() \ for obj in lstObjects ] return toReturn #colletion of strings def getObject(self, intIndex, lstObjects ): toReturn = None if (not (intIndex == -1)): toReturn = lstObjects[intIndex] return toReturn #an Object def getObjects(self, lstIntegers, lstObjects ): # PENDING toReturn = [] toReturn = [ lstObjects[ anIndex ] \ for anIndex in lstIntegers ] return toReturn #Zero or more objects def getSelctStr( self, intIndx, lstStrings ): toReturn = None if ( not (intIndx == -1 ) ): toReturn = lstStrings[intIndx] return toReturn def getSelctStrs( self, lstIntIndxs, lstStrings ): toReturn = None if ( not (len(lstIntIndxs) == 0 ) ): toReturn = [ self.getSelctStr(anIndx, lstStrings) \ for anIndx in lstIntIndxs ] return toReturn class TestObject: def __init__(self, strID = "noID"): self.id = strID def __str__(self): return self.id def getOneStr( lstString ): return mainOneStr( lstString ) def getOneObj( lstObject ): return mainOneObj( lstObject ) def getMultStr( lstString ): return mainMultStr( lstString ) def getMultObj( lstObject ): return mainMultObj( lstObject ) def mainOneStr(lstString ): application = SelectorApp(0) application.setOneAsMain() application.setSelectionList(lstString) application.main.Show(true) application.SetTopWindow(application.main) application.MainLoop() return application.getSelctStr(application.getSelection(), lstString) def mainOneObj( lstObject ): lstString = [] toReturn = None #should be an object application = SelectorApp(0) application.setOneAsMain() lstString = application.getObjectStrings(lstObject ) application.setSelectionList(lstString) application.main.Show(true) application.SetTopWindow(application.main) application.MainLoop() #stops when GUI closes toReturn = application.getObject( application.getSelection() , \ lstObject ) return toReturn def mainMultStr(lstString ): application = SelectorApp(0) application.setMultAsMain() application.setSelectionList(lstString) application.main.Show(true) application.SetTopWindow(application.main) application.MainLoop() return application.getSelctStrs(application.getSelection(), lstString) def mainMultObj( lstObject ): lstString = [] toReturn = None #should be a collection of zero or more objects application = SelectorApp(0) application.setMultAsMain() lstString = application.getObjectStrings(lstObject ) application.setSelectionList(lstString) application.main.Show(true) application.SetTopWindow(application.main) application.MainLoop() #stops when GUI closes toReturn = application.getObjects( application.getSelection() , \ lstObject ) return toReturn def main(): application = SelectorApp(0) application.main.Show(true) application.SetTopWindow(self.main) application.MainLoop() return application.getToReturn() if __name__ == '__main__': main() selectOneHandler.py ************************************* #Boa:Frame:SelectOneHandler from wxPython.wx import * from wxPython.lib.buttons import * def create(parent): return SelectOneHandler(parent) [wxID_SELECTONEHANDLER, wxID_SELECTONEHANDLERBTNACCEPT, wxID_SELECTONEHANDLERBTNCANCEL, wxID_SELECTONEHANDLERLISTBOX1] = map(lambda _init_ctrls: wxNewId(), range(4)) class SelectOneHandler(wxFrame): def _init_utils(self): pass def _init_ctrls(self, prnt): wxFrame.__init__(self, id = wxID_SELECTONEHANDLER, name = '', parent = prnt, pos = wxPoint(555, 60), size = wxSize(225, 455), style = wxDEFAULT_FRAME_STYLE, title = 'SelectOneHandler') self._init_utils() self.SetClientSize(wxSize(217, 428)) self.listBox1 = wxListBox(choices = [], id = wxID_SELECTONEHANDLERLISTBOX1, name = 'listBox1', parent = self, pos = wxPoint(56, 24), size = wxSize(115, 296), style = 0, validator = wxDefaultValidator) self.btnCancel = wxButton(id = wxID_SELECTONEHANDLERBTNCANCEL, label = 'Cancel', name = 'btnCancel', parent = self, pos = wxPoint(144, 344), size = wxSize(51, 51), style = 0) EVT_BUTTON(self.btnCancel, wxID_SELECTONEHANDLERBTNCANCEL, self.OnBtncancelButton) self.btnAccept = wxButton(id = wxID_SELECTONEHANDLERBTNACCEPT, label = 'Accept', name = 'btnAccept', parent = self, pos = wxPoint(32, 344), size = wxSize(51, 51), style = 0) EVT_BUTTON(self.btnAccept, wxID_SELECTONEHANDLERBTNACCEPT, self.OnBtnacceptButton) def __init__(self, parent): self._init_ctrls(parent) self.owner = None def setSelectionList(self, lstString ): self.listBox1.InsertItems( lstString, 0 ) def setOwner( self, someOwner ): self.owner = someOwner def getOwner(): return self.owner def OnBtncancelButton(self, event): self.owner.setSelection(-1) try: self.Close(true) print( "cancel closed") self.owner.ExitMainLoop() print("cancel loop") except: print( "cancel except") def OnBtnacceptButton(self, event): selection = self.listBox1.GetSelection() self.owner.setSelection(selection) try: self.Close(true) print( "accept closed" ) self.owner.ExitMainLoop() print("accept loop") except: print( "accept except" ) Angel Asencio wrote: > Greetings: > > I have been requested to write a function that will take a list, open > a selection window, and then when the window is closed the function > would return a list with the selected items. > > Looks like wxPython is quite favored, and I decided to use the Boa > Constructor, finished the tutorial. Everything fine and dandy, until I > wanted to create the function that you can call from the shell. > > The scenario that I have tried is for the function to call the MainApp > (that has the > MainLoop) with the Frame that will do the selection. I understand about > the events, but what ever I do with the event, 'myModule.myFunction( [ > "a","collection","to","select"])' return nothing on the combinations I > have tried. > > Bottom line is that I want a function call that I can call in the > shell, like as part of a print, that I do the selection, and when I > press ok on the window, the window closes and the print completes. > > Thanks to any pointer, > > -- > -Angel Asencio > The MITRE corp. > asencio at mitre.org From tim at vegeta.ath.cx Fri Jul 26 06:40:29 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: 26 Jul 2002 03:40:29 -0700 Subject: redirect to > and to console ? References: Message-ID: Gerhard Haering graced us by uttering: > "Shagshag13" wrote: >> i use many python script like that : >> ./myscript.py file_in > file_out >> >> i wish i would sometimes like to force output to be redirect to >> console instead of file file_out, is there any way of doing that? >> (for example to display errors message while file_in will contain >> only data processed) [...] > > Unix and Windows consoles have two different output streams: the > standard output one and the error stream. > > Standard output is accessible from Python as sys.stdout, the error > stream as sys.stderr. > > To write to the error stream, either one of > > sys.stderr.write("foobar\n") > > and > > print>> sys.stderr, "foobar" One thing that concerns me is how well do the COMMAND.COM/CMD.EXE shells handle redirection? I know that DOS used to support the standard '>' redirection, but I don't remember any robust way of handling stderr on the command line. Various *nix (and cygwin, yes) shells can use: $ command > file_out 2> file_err $ command > file_both 2>&1 $ command &> file_both ...and I think I heard CMD.EXE had slightly better support, but how does Win32's native command line stream redirection really compare? Tim Hammerquist -- You can lead a boss to a decision, but you can't make him think. -- Simon, BOFH From wdraxinger at darkstargames.de Sat Jul 27 08:29:43 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sat, 27 Jul 2002 14:29:43 +0200 Subject: Being a bit confused after hacking Python References: <3D343DA7.6010309@darkstargames.de> <3D34499C.1040300@shinners.org> Message-ID: <3D429237.3090303@darkstargames.de> Pete Shinners wrote: > Wolfgang Draxinger wrote: > > modules are only imported once. That's good to know. > I've never done this though, i don't believe it's hard, but > who knows? When I hacked into Python I also went through the import stuff. However most is done by reading things from files. However there's also the possiblity to load binary modules from .so, .dll whatever. For scurity reasons only modules named in a game specific dependicies list cn be loaded. I solved this problem by hooking into __builtin__.__import__ and unpacking the required module to a local cache directory. That has also the advantage, that a package may contain source modules, that are then compiled on the fly and stored in the cache >> 3rd: > with rexec you can keep the user from doing many things. you can also > replace calls like "open" to map to your own virtual filesystem (which > might be useful). there's some pretty good docs on it, but i'm not sure > how you would set one up from the "c api". My solution so far: I wrote a small python script setting up a rexec environment I can access from C and compiled that into a frozen code I included into my engines sources. Replacing the open function was a must and I scrached my head for nights on that problem. The solution via rexec is far better. > there's always a chance someone could do something like "while 1:pass" > or try to allocate millions of objects. Okay that is a problem, however if my engine has a small protection against this, when in user mode: If a event handler script takes longer than 5 seconds, then it isn't realtime and killed. Also scripting of prolonged processed, like a chain reaction in the game ( player ignites torch->5 seconds->burns rope->3 seconds->crate held by rope falls on enemy ;-) is done by shooting engine timers, which reside outside of the scripting system. > as for reloading sys resetting stdout, why do you ever need to reload > it? if you just want to reset the stdout variables, just set sys.stdout > to sys.__stdout__. the __stdout__ is the "original" stdout object. I just tried to understand the reload process out of interesst and ran about that confusing fact, that in the _PyInittab there is not initfunction entry for the builtin modules. In the case that on the console someone types ">>> import sys; reload(sys)", the console would be useless, since it has no longer access to Python std I/O. So long I'm catching the problem by hooking reload too, and checking for the modules I replaced. -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From tdelaney at avaya.com Mon Jul 8 21:38:48 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 9 Jul 2002 11:38:48 +1000 Subject: join [was: Re: converting an array of chars to a string] Message-ID: > From: pinard at iro.umontreal.ca [mailto:pinard at iro.umontreal.ca] > > [Duncan Booth] > > > Writing ''.join(list) still sucks though. > > JOINER.join(LIST) has some technical advantages, which are > much bolded by > its proponents. Despite theses advantages, it just remains > plain ugly. Very much - ugly and unintuitive. There are times that functions are better than methods. IMO this is one of those times. I have been using 2.0+ for quite a while now, and have yet to use ''.join() in preference to string.join(). Sure - I may suffer a slight performance decrease - but my code is a lot more readable. Tim Delaney From tim.one at comcast.net Wed Jul 17 01:16:30 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 17 Jul 2002 01:16:30 -0400 Subject: map del efficiency python2.2 and 2.1 In-Reply-To: <20020717041133.2407C38F61@coffee.object-craft.com.au> Message-ID: [Andrew McNamara] > ... > I wrote a very simple benchmark that allocated and deallocated a million > small objects on a 600MHz P3 running linux 2.4.18 and glibc-2.2.4 with > enough memory to prevent paging. > > Results and code are below. It's clear that the system malloc hurts > badly for deallocation, but even with pymalloc deallocation is still > an expensive exercise (the attribute dictionary, presumably). Slots are > very efficient for small objects, in terms of CPU and memory footprint. pymalloc in (all flavors of) 2.2 was still an experimental feature (that's why it's disabled by default), and wasn't tuned for the way new-style classes work. In particular, pymalloc's "small object threshold" is much too low in the 2.2 line, so low that *no* instance dict can get handled by it, and consequently it still passes on lots of work to the system malloc/free. The strong benefit you got from it is more indirect than you may think; your platform free() appears to be truly dreadful when dealing with lots of small objects. Under current CVS Python (what will eventually be Python 2.3), pymalloc is tuned properly for new-style classes, and the deletion times are minor on my home Win98SE 866MHz box (the del times below are 100x smaller than you were seeing with 221+pymalloc); they should become minor on your box too, as pymalloc's code is the same on all platforms, while its few hardcoded assumptions about OS paging are geared more toward Unix than Windows: C:\Code\python\PCbuild>python -O temp.py testing slots create + setattr took 13.1s setattr took 1.9s del took 0.6s testing obj create + setattr took 36.6s setattr took 2.1s del took 1.1s testing trad create + setattr took 30.8s setattr took 2.4s del took 1.0s This was leaving gc enabled, but changing your testit() to def testit(ctor, count): print "testing", ctor.__name__ start() a = map(ctor, xrange(count)) stop(' create + setattr') gc.collect() start() aa = ctor(0) map(aa.set, xrange(count)) stop(' setattr') del aa gc.collect() start() del a gc.collect() stop(' del') because it just confuses things to time explicit gc.collect() calls too (except when you're specifically trying to time collection, as you may have intended to do in your " del" test). gc is a bit zippier in current CVS too. From fredrik at pythonware.com Mon Jul 29 12:04:00 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Jul 2002 16:04:00 GMT Subject: Leo.py: Some Thoughts References: <3D44EAA9.7010607@thomas-guettler.de> Message-ID: Edward K. Ream wrote: > You can store any text. If that text represents pictures or tables, fine. > Depending on your situation this might be good enough. Often it is not. > This limitation is due to the limitations of the standard Tk Text widget and > probably won't be fixed until the Tk Text widget gets more capable. you can embed other widgets, as well as images, in a Text widget. what other capabilities do you need? From jiba at tuxfamily.org Thu Jul 25 07:03:04 2002 From: jiba at tuxfamily.org (Lamy Jean-Baptiste) Date: Thu, 25 Jul 2002 13:03:04 +0200 Subject: GUI toolkits References: Message-ID: <20020725.130300.202526548.1588@localhost.localdomain> Dans l'article , "Stefano Vedovelli" a ?crit : > As the interface will be "quite" rich, I'd like to know the opinions of > people who already faced this decision, which tool they have chosen and > why. I have tried Gtk, wxWindow and Tk, and finally the last one is the one i prefer. wxWindow has a VERY big startup time (tested under Linux), and i don't like waiting for an application to open. Gtk is good looking and Glade is helpfull, though Gtk 2 is absolutely not compatible with the widely used Gtk 1 -- the Python binding for Gtk 1 and 2 cannot be installed at the same time, and supporting both Gtk 1 and 2 is very hard... :-( Tk is faster (and start up quickly), easier and the most portable. Sure it lacks some widgets (trees, ...) but there's plenty Python modules that give these feature. In fact, the only default i can find to Tk is its non-themable look and feel. Jiba From clpy at snakefarm.org Sun Jul 7 06:56:47 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Sun, 07 Jul 2002 12:56:47 +0200 Subject: FancyURLopener: no HTTP status codes? Message-ID: <3D281E6F.2080909@snakefarm.org> Hi there, is there any possibility of getting the HTTP status code from a urllib.FancyURLopener object? Regards Carsten. From peter at engcorp.com Mon Jul 1 00:50:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Jul 2002 00:50:02 -0400 Subject: newbie Q: delete list few lines in file References: <7fe97cc4.0206291519.1c95ce31@posting.google.com> <3D1E5123.FDEFADDF@engcorp.com> <3D1E83C0.8060700@earthlink.net> <3D1E8A08.53DD2272@engcorp.com> <3D1FD948.25806D00@engcorp.com> Message-ID: <3D1FDF7A.3E3FA467@engcorp.com> Peter Hansen wrote: > > Jonathan Hogg wrote: > > > > I think that it is unclear from Xah's original post whether the files or the > > lines are to be deleted. Certainly, asking how to write to files in place > > suggests that the lines are to be deleted. > > I didn't catch that part. Apparently neither did anyone else who was > interested in helping, rather than criticizing... Bah, sorry for sniping, Jonathan. I think I need a vacation from this job. -Peter From emile at fenx.com Thu Jul 4 12:43:23 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 16:43:23 GMT Subject: testing a sequence for 'identicalness' References: Message-ID: Rajarshi Guha > does anybody knwo how I can check a sequence for 'identical ness', ie > given a sequence: > > [1,1,1,1,1,1,1,1,1,1] > > it would be classified as 100% identical > > and > > [1,1,1,1,1,1,1,1,1,2] > > would be classified as 90% identical. >>> import difflib >>> l1 = [1,1,1,1,1,1,1,1,1,1] >>> l2 = [1,1,1,1,1,1,1,1,1,2] >>> s = difflib.SequenceMatcher(None, l1, l2) >>> s.ratio() 0.90000000000000002 -- Emile van Sebille emile at fenx.com --------- From tim.one at comcast.net Mon Jul 22 22:16:31 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 22 Jul 2002 22:16:31 -0400 Subject: calendar lameness! In-Reply-To: <3D3C0A21.1EB8A671@anansispaceworks.com> Message-ID: [Terry Hancock] > ... > "calendar" is pretty neat -- except it has pretty > annoying arbitrary limits on the date: > > 1900-1/1 to 2038-1/18 > > I can see that this is adequate for a business > planner, but for historical or astronomical uses, > it's really inadequate. > ... Get Marc-Andre Lemburg's mxDateTime. Python 2.3 will have some sort of standard more-powerful datetime gimmick, but Guido is anti-interested in arguing with datetime weenies <0.9 wink>. > ... > This is Python 2.1. Anyway -- any chance these got > fixed in a later release? None. > Why the range? > ... > Actually, it looks like maybe it's "mktime" that > is the limiter here (?). Bingo! > ... > It seems like Python longs would make it unnecessary to > have such arbitrary limits. See Demo/classes/Dates.py in the Python source distribution. From pecora at anvil.nrl.navy.mil Tue Jul 9 17:17:28 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 17:17:28 -0400 Subject: Why self? References: Message-ID: <090720021717282330%pecora@anvil.nrl.navy.mil> In article , wrote: > > s = self > s.y = s.x**2 * s.t/s.z + s.a * FFT(s.tseries) Yep, I've done that. Not bad. I've even used just an underscore "_" for the self variable. That hides it more. _=self _.y = _.x**2 * _.t/_.z + _.a * FFT(_.tseries) Is that better? Well, a little. -- Lou Pecora - My views are my own. From dsavitsk at e-coli.net Fri Jul 12 00:32:01 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 12 Jul 2002 04:32:01 GMT Subject: window icons in Tkinter References: <3d2e442c$0$11264$afc38c87@news.optusnet.com.au> Message-ID: <5ZsX8.2270$931.1025656@newssrv26.news.prodigy.com> look for tkicon at http://effbot.org/downloads/ "Steven" wrote in message news:3d2e442c$0$11264$afc38c87 at news.optusnet.com.au... > Can anyone shed some light on how to get the root window to use an icon > other than the 'Tk' symbol? > > I can't seem to find an example of this anywhere > > thanks > > Steven > > From dcinege at psychosis.com Tue Jul 23 02:17:13 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Tue, 23 Jul 2002 02:17:13 -0400 Subject: good books In-Reply-To: References: Message-ID: <200207230217.13355.dcinege@psychosis.com> On Tuesday 23 July 2002 2:13, Percy Tambunan wrote: > what is a good book in python, If i can only afford to buy just one book? IMO Python 2.1 Bible, www.hungryminds.com -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From Gabe.Newcomb at noetix.com Fri Jul 12 13:27:11 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Fri, 12 Jul 2002 10:27:11 -0700 Subject: Input again (!!@#&#$^@#$) Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6067@NOXMAIL.noetixad.com> a couple things: 1. remember to use == instead of = for checking for equivalence (= is only for assignment) 2. I don't know if this was just your pseudocode, but remember there's no 'then' keyword in python, just the colon 3. raw_input will return the newline symbol (\n) I think, so try something like: if raw_input.startswith('Yes'): do_something... else: do_something_else HTH, Gabe -----Original Message----- From: Seth Ainsley [mailto:sethtoday at hotmail.com] Sent: Friday, July 12, 2002 9:37 AM To: all_things_python at yahoogroups.com; python-list at python.org Subject: Input again (!!@#&#$^@#$) Sorry, Input again. Thanks for the answer on what I thought was raw.input (but was actually raw_input), but how would it be for me to get something like the following to work: input = raw_input('What's your answer? ') if input = "Yes" then print "Something" else print "Something else" What I'm trying to do here is basically tell Python if the person answers "Yes" then print "Something". If it's anything else, print "Something else." But this doesn't work. Any suggestions? Thanks for your help in advance, Seth A. _____ Send and receive Hotmail on your mobile device: Click Here -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Jul 3 23:54:18 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 03:54:18 GMT Subject: how can I put mysql input without ([,]) References: Message-ID: "Ria" wrote in message news:JHKU8.256512$yP6.9941766 at Flipper... > And how about when I use: > cursor.execute("select column_1, column_2, column_3 from tabel") > How about: results = cursor.fetchall() for column_1, column_2, column_3 in results: dostuff_with(column_1, column_2, column_3) -- Emile van Sebille emile at fenx.com --------- From list-python at ccraig.org Mon Jul 29 00:41:10 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 29 Jul 2002 00:41:10 -0400 Subject: How to detect the last element in a for loop In-Reply-To: References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: Tom Verbeure writes: > Then what about this? > > for a in myList: > if last_one: > special_stuff > do_stuff > Tom Okay, not as simple, but it should work for a, i in zip(myList, xrange(len(myList))): if i==(len(myList)-1): special_stuff do_stuff -- Christopher A. Craig "Imagination is more important than knowledge" Albert Einstein From aleax at aleax.it Wed Jul 24 08:15:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 12:15:24 GMT Subject: GUI toolkits References: Message-ID: Stefano Vedovelli wrote: > Hello all > > in my spare time I am writing a tool in python, with the intention of > deliver it under GPL. > > I am now starting to approach the GUI part. I have read a lot about > Tkinter, PyQT and wxWindows, but I am now actually even more confused. > > As the interface will be "quite" rich, I'd like to know the opinions of > people who already faced this decision, which tool they have chosen and > why. PyQt, because Qt is the richest and fastest. Dunno 'bout the license situation though -- I'm pretty sure you're OK with GPL for Qt-using stuff on (e.g.) Linux, but on Windows it might be different (alas, Trolltech's license lawyers have weaved a thick thicket there, sigh). For Python discussions in Italian, by the way, I suggest: http://www.penguin.it/mailman/listinfo/python Seems to be full of wxPython-lovers (and not only there -- Robin Dunn just won this year's "Programmers' Choice" ActiveAward, and quite deservedly too!!) so I can guess what THEY'll advise:-). At least the license issues seem OK with wxPython/wxWindows on whatever platform you run it on!-). Alex From cliechti at gmx.net Tue Jul 30 19:45:51 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 01:45:51 +0200 Subject: .wav music problems References: Message-ID: "Seth Ainsley" wrote in news:mailman.1028071080.13682.python-list at python.org: baahh HTML mail... not eveyones friend, please try to post text only. > I'm having problems getting the wave module to work. I > tried this, and you can see what happened: > from wave import * #import the wave module never use import * with the wave module. you won't be able to open normal files afterwards. use: import wave > q=wave.open('gemstorm.mid','r') #open gemstorm.mid in read > Traceback (most recent call last): ... > NameError: name 'wave' is not defined because you didn't imported the module under that name. if you change the import above as i sugest it will find the module. > "Error: file does not start with RIFF id" that is because a .mid (MIDI) file has absolutely nothing in common with a .wav (WAVE) file. a midi contains notes to play, a wav is a digital recording. you can do diffrent things a) use a module that can work with midi (pygame might be able to play them) b) convert it to a wav. google should help to find a software for that. chris -- Chris From thehaas at binary.net Wed Jul 17 17:23:51 2002 From: thehaas at binary.net (thehaas at binary.net) Date: Wed, 17 Jul 2002 21:23:51 GMT Subject: 'capwords' is not a string method Message-ID: Here is something I very recently discovered . . . "capwords" are not included as a method of the string type, but "upcase" is: >>> str = "python rocks" >>> str.capwords() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute 'capwords' >>> str.upper() 'PYTHON ROCKS' But "capwords" *is* included in the string module: >>> string.capwords(str) 'Python Rocks' So I can still do it, but this seems a little inconsistant to me. Is there a reason, or is it just an oversight?? -- mikeh -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas GnuPG key: http://www.binary.net/thehaas/mikeh.gpg From fredrik at pythonware.com Thu Jul 11 19:55:19 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Jul 2002 23:55:19 GMT Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <3D2E11B5.4070502@removethisandallhyphens-o-n-e.net> Message-ID: string.join(list("-%s-" % random.choice(teams))) wrote: > No, you are only using a convention to let other developers know > that these variables are private - the python interpreter does not > even attempt to hide a '__' variable from other classes or code. class Spam: def __init__(self): self.__private = 1 def get(self): return self.__private x = Spam() print x.get() print x.__private $ python test.py 1 Traceback (most recent call last): File "test.py", line 10, in ? AttributeError: Spam instance has no attribute '__private' From cce at clarkevans.com Sun Jul 28 11:44:57 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Sun, 28 Jul 2002 11:44:57 -0400 Subject: Python and XML help In-Reply-To: <_iB09.17825$p56.5762976@newsb.telia.net>; from fredrik@pythonware.com on Sat, Jul 27, 2002 at 06:06:50PM +0000 References: <_iB09.17825$p56.5762976@newsb.telia.net> Message-ID: <20020728114457.A48706@doublegemini.com> On Sat, Jul 27, 2002 at 06:06:50PM +0000, Fredrik Lundh wrote: | $ more clarkbot.py Yes, my apologies for not thoroughly reading his request. Also, thank you for pointing to ConfigParser, neat package. Best, Clark From shalehperry at attbi.com Fri Jul 19 12:17:25 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 19 Jul 2002 09:17:25 -0700 (PDT) Subject: NEW TO THIS: Assigning values to strings in list? In-Reply-To: Message-ID: On 19-Jul-2002 Johannes Graumann wrote: > Hello, > > As stated in the subject, I'm new to this - but I think with this > question I might be already headed for my first good burn ;0) > > Basicely I have two lists, one containing the future string-names > and one containing the values I want to give them. The order is > identical in both. Right now I'm solving this by a dictionary, but > I would really prefer to have straight strings as a result of my > operation. > > Can anybody please tell me how to go about this and/or why I > totally shouldn't do this? > so you have: a_list = ['sean', 'johannes', 'margaret'] and b_list = ['this', 'other', 'fellow'] and you just want to swap their values? Why not just assign b_list to a_list? a_list = b_list Otherwise you have to muck with counters. for i in range(0, len(a_list)): a_list[i] = b_list[i] If none of this helped, provide some more detail, perhaps a small code snippet. Also, tutor at python.org is a great place for those "new to this" to hang out, ask questions and see other people's questions. You can learn a lot by just lurking and reading. From tom.verbeure at verizon.no.sp.am.net Sat Jul 27 17:33:27 2002 From: tom.verbeure at verizon.no.sp.am.net (Tom Verbeure) Date: Sat, 27 Jul 2002 21:33:27 GMT Subject: How to detect the last element in a for loop References: Message-ID: >> >> Hello All, >> >> I often have the case where I need to loop through a bunch of elements, >> but do something special on for the last line of code. > > That's not what you're doing below: > >> Currently, I can solve it this way: >> >> first = 1 >> for port in self.portDefsList: >> if first == 0: >> string += ", " >> else: >> first = 0 >> string += str(port) >> pass > > Here, you're doing something special (avoiding the += ", ") the FIRST > time. The pass is unconditional and adds absolutely nothing -- just > take it away. Duh. I copied the wrong piece of code. :-] > Anyway, this specific need is met to perfection by: > string += ", ".join([ str(port) for port in self.portDefsList ]) Interesting. My focus wasn't really on joining strings, but I didn't know this either. > This does assume that you have a sequence, not just an iterator, and can > thus slice off the first or last items easily. It's trickier but > not difficult to do special-on-first on an iterator: > > processfirst(iterator.next()) > for item in iterator: > processnormal(item) > > the .next call returns and "consumes" the first item, so the following > for starts from the second one, and all is sweetness and light. I am not familiar with iterators as objects in Python. I understand that for a in myList: ... will result in an implicit iterator on myList. How would you create an explicit iterator object of myList? > Detecting the LAST item for special processing is trickier still if > what you DO have is an iterator. You basically have to "stagger" > the output, e.g.: > > saved = iterator.next() > for item in iterator: > processnormal(saved) > saved = item > processlast(saved) Given that you have an explicit iterator, wouldn't it be trivial to add an 'end()' method to this iterator to indicate the end of the sequence (just like C++ iterators) ? This would result in: for item in iterator: if iterator.next().end(): do_something_special do_something_for_all Thanks, Tom From kalle at lysator.liu.se Thu Jul 18 18:45:55 2002 From: kalle at lysator.liu.se (Kalle Svensson) Date: Fri, 19 Jul 2002 00:45:55 +0200 Subject: i++ in Python? In-Reply-To: <5606b639.0207181429.2c6d2569@posting.google.com> References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <20020718224555.GA1090@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [OtisUsenet] > Python newbie question. How does one do something like this in > Python: > > # assign the value of j to i and then increment j by 1 > i = j++ i = j j += 1 Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9N0UZdNeA1787sd0RAvrvAJ9gJ/RAWvYBGkc/GDKiRcVLlaQN0gCgo1ib QxJ3iUwqOOjtRfeBGhO8CAA= =Q1pJ -----END PGP SIGNATURE----- From doru-cat at ifi.uio.no Tue Jul 16 18:04:38 2002 From: doru-cat at ifi.uio.no (Doru-Catalin Togea) Date: Wed, 17 Jul 2002 00:04:38 +0200 (MET DST) Subject: UnicodeError: ASCII encoding error: oridinal not in range(128) Message-ID: Hi! The following code works well (as expected) when the "tmplText" variable contains only english characters. f = open(htmlPrefix + htmlFileName, 'w') f.write(tmplText) f.close() The same code fails when "tmplText" comes from an XML files which contains norwegian characters (latin-1 extension), like ø, in the data, not in the tags, with the following error message: Traceback (most recent call last): File "./python/genh1.py", line 335, in ? f.write(tmplText) UnicodeError: ASCII encoding error: oridinal not in range(128) I have found the same behaviour for the builtin "print" function. print() works well with norwegian text in the Interactive Window of PythonWin IDE. What kind of strings do write() and print() handle? Hopefully I can convert my strings to that type. I am running ActiveState Python 2.2 on win 2000 Pro. Any help is appreciated. Thank you. Catalin <<<< ================================== >>>> << We are what we repeatedly do. >> << Excellence, therefore, is not an act >> << but a habit. >> <<<< ================================== >>>> From eugene1977 at hotmail.com Mon Jul 15 04:19:24 2002 From: eugene1977 at hotmail.com (a64bs4$1oo$1@newsreader.mailgate.org) Date: Mon, 15 Jul 2002 04:19:24 -0400 Subject: any web application available in python? Message-ID: hi.. i want to make a community-oriented website for programmers well, i don't know what features i would need yet though. however, it seems that message-board is pretty basic feature to any website.. is there any module(?) or open source code that i can use for message-board with apache? From peter at engcorp.com Fri Jul 19 09:50:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Jul 2002 09:50:56 -0400 Subject: win32com: makepy causes ie problems. References: <3D37C2B7.5010007@skippinet.com.au> Message-ID: <3D381940.3CFF66AF@engcorp.com> Mark Hammond wrote: > > David LeBlanc wrote: > > While trying to figure out how to make the recently posted (by Paul Rubin) > > ie navigation example work, I had occasion to run makepy.py on "Microsoft > > Internet Controls". After doing this, the sample would fail on "ie.visible = > > 1". Removing the generated file would return the sample to working order. > > > > Sample: > > from win32com.client import DispatchEx > > import time > > > > ie = DispatchEx('internetexplorer.application') > > ie.visible = 1 > > ie.navigate('http://www.w3.org') > > Was the problem "AttributeError: visible"? If so, the problem is simply > that the correct name for the property is "Visible". makepy is case > sensitive. Ahh, that would be the problem. I never use makepy (to date), so I guess I've become lazy and don't pay attention to the case, not wanting to spend my time reading Microsoft documentation to discover which is which. :) -Peter From nhodgson at bigpond.net.au Mon Jul 29 19:17:52 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 29 Jul 2002 23:17:52 GMT Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> <3D45894A.2090406@motorola.com> Message-ID: Stephen Boulet: > What if you wanted to do things like make a tabbed spreadsheet (tabs on > the bottom that break up a notebook int subparts, not '\t'), is this > possible with csv format? Recent versions of Excel can use an XML based file format. My advice would be to create a document that is much like you want to write from Python and decipher the XML enough to work out where you need to change. Then write templating code that can insert your data (wrapping each element in some XML) along with the rest of the XML from the saved file. http://msdn.microsoft.com/library/en-us/dnexcl2k2/html/odc_xlsmlinss.asp Neil From coventry at removethisandallhyphens-o-n-e.net Fri Jul 19 23:12:25 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Fri, 19 Jul 2002 23:12:25 -0400 Subject: Session ID & Security References: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> <3D38B779.3090602@removethisandallhyphens-o-n-e.net> <7xwurrkwes.fsf@ruckus.brouhaha.com> Message-ID: <3D38D519.8070501@removethisandallhyphens-o-n-e.net> http://web.systhug.com/kernel-lock/ - for linux atomic file locking. of course, wether your system is mulitprocess or multithreaded will vary the lock - a python multithreaded application can perform all locking internally. multiprocess requires external locking, such as the file locking provided above in linux kernels and filesystems. Note that _how_ you store and lcok your data can play a big part in how the lock affects performance. a single, big lock on a single file containing all session data will not scale. I use individual files per session in my projects, and lock individually - thus only simultaneous requests from the same session can block each other - which is normally acceptable. -c Paul Rubin wrote: > - c o v e n t r y - writes: > >>Why bother reinventing the wheel for a shared memory implementation >>when you could just use the filesystem like everyone is used to, just >>on a ram disk? >> >>Linux and the BSDs have the capability to do this... >> > > I'm not aware that Linux and BSD can do synchronous, atomic file > operations. I'm not terribly up on this stuff though. What semaphore > mechanism would you use? > > From peter at engcorp.com Tue Jul 30 21:11:55 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Jul 2002 21:11:55 -0400 Subject: Searching for email address References: Message-ID: <3D47395B.939CD4E9@engcorp.com> Graeme Longman wrote: > "Charl P. Botha" wrote: > > In article , > > Graeme Longman wrote: > > > I'm writing some code which searches html for email addresses. Does > > > anyone out there have a good regular expression syntax for searching for > > > the email string, I'm sure this must've been done a few times before. > > > > Excuse my curiosity, but what are you going to do with this code? :) > > In the process of translating our client's sites. > > Just a script to find all the email addresses so that the email addresses > aren't included for translation. Are there really going to be any addresses that don't follow the format user at host.domain on those web pages? With real email (i.e. RFC822 and later ones) there are many options including parentheses and quotation marks in addresses, but I've never yet seen such a thing in a simple "mailto:" URL on the web. Maybe you're trying to find a sledgehammer when a flyswatter will do... -Peter From peter at engcorp.com Mon Jul 22 19:57:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 19:57:00 -0400 Subject: setting the screen resolution References: <6edeb2ff.0207220845.86b6ebd@posting.google.com> Message-ID: <3D3C9BCC.5F6B9DF5@engcorp.com> Chad Haynes wrote: > > i am currently working on a program using wxPython which requires the > screen resolution to be 1024x768. is there a way to set this from > python? Can you tell us _why_ it requires a fixed resolution? Maybe you'll get some good suggestions on how to remove that restriction. -Peter From robin at jessikat.fsnet.co.uk Thu Jul 4 05:24:52 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 4 Jul 2002 10:24:52 +0100 Subject: replacing instance __setattr__ References: Message-ID: In article , Robin Becker writes >Is there something intrinsically hard about overriding an instance's special >methods? I'm using >python 2.2 and expected that it would be easy to wrap an existing __setattr__, >but >it seems the class is searched first not the instance. Must I clone the class >and >set the method on that? > .... well it seems Python not as dynamic as I believed. The object is searched last which seems completely counter-intuitive to me, but there you go. -- Robin Becker From jonathan at onegoodidea.com Tue Jul 16 07:27:45 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 16 Jul 2002 12:27:45 +0100 Subject: Iterator for Custom Sequence References: <87u1mzq5xw.fsf@athens.localdomain> Message-ID: On 16/7/2002 12:15, in article 87u1mzq5xw.fsf at athens.localdomain, "Patrick W" wrote: > class LinkedList: > .... > def __iter__(self): > def genitems(ls): > n = ls.head > while n.data is not None: > yield n.data > n = n.next > return genitems(self) > .... > > This does the job, but is it eccentric or counter-Pythonic? If so, > what's the conventional way to provide an iterator for a custom > sequence? I'm not sure why you've used a nested function. I would have written this simply as: class LinkedList: .... def __iter__(self): node = self.head while node.next is not None: yield node.data node = node.next .... When you call 'iter' on an object it should return an iterator. A generator returns an iterator when called. So making '__iter__' a generator suffices. In fact this is the main place I use generators. I made a couple of changes other than removing the function: I like 'node' better than 'n', and I think testing if 'node.data' is None is bogus as you might want to store None in the list. It makes more sense (and is more normal in linked-lists) to check if 'node.next' is None, since the last item should have no next item (obviously your other methods would need to match this convention). Jonathan From shagshag13 at yahoo.fr Sat Jul 20 05:33:20 2002 From: shagshag13 at yahoo.fr (Shagshag) Date: 20 Jul 2002 02:33:20 -0700 Subject: args command line... Message-ID: <409a56e2.0207200133.35cdc06b@posting.google.com> hello, i'm looking for a script able to handle/understand "common" command line options like : ascript.py -option this_is_a_directory/* ascript.py -another_option file1 file2 file3 -another_option2 this_is_another_dir i think that should exist somewhere... (i wish to learn as it should be written in a good pythoner's way but also gain time by re-using it) thanks in advance, s13. From b.maryniuk at forbis.lt Thu Jul 4 10:32:56 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 16:32:56 +0200 Subject: sending a file through sockets In-Reply-To: <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> Message-ID: <200207041632.56772.b.maryniuk@forbis.lt> On Thursday 04 July 2002 16:20, Guyon Mor? wrote: > ------- > encode some_file.jpg to basecode64 makes: SsDfgFVSFgfsaSZFASasfgAS > in send it through the socket and decode it back and write it to a file. > ------- > right? Yup! -- Sincerely yours, Bogdan M. Maryniuck "Even more amazing was the realization that God has Internet access. I wonder if He has a full newsfeed?" (By Matt Welsh) From mhammond at skippinet.com.au Sat Jul 13 21:39:22 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 14 Jul 2002 01:39:22 GMT Subject: python - asp References: Message-ID: <3D30D724.6050106@skippinet.com.au> www.ciquery.com wrote: > Does anybody know if the download of python 2.2 > from www.python.org for Windows includes the > ActiveX Scripting Engine . I need to build some ASP > pages that run Python on the server side. After installing Python itself you must also install win32all from http://starship.python.net/crew/mhammond. This will install the ActiveX Scripting Engine (for ASP) as well as a number of other Windows specific features. Mark. From marklists at mceahern.com Wed Jul 24 11:59:54 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 24 Jul 2002 10:59:54 -0500 Subject: error code In-Reply-To: <3d3ec90c$0$28132$afc38c87@news.easynet.fr> Message-ID: > In your example you write the Exception code . > > for example : > try : > server = smtplib.SMTP('XXXXXXX') > except : > print "error : %s --> %s " % ( sys.exc_value , sys.exc_type) > > If I put a bad host , I have the error : "error : host not found --> > socket.error" > > I suppose that the error "host not found" have a caracteristic number . > how can I get it ? As Alex pointed out, not all Exceptions have an error number or code associated with them. Notice how much easier it is to help you, by the way, when you post a real live sample of code. In the case of the above, I would write that: try: server = smtplib.SMTP('XXXXXXX') except Exception, e: ... Then, interactively, just to figure this out, I'd do this: print dir(e) Hmm, there's an args attribute there. What's in it? print e.args Result: (7, 'getaddrinfo failed') So, in this caes, e.args is a tuple. 7 might be what you're looking for. But I haven't looked into the smtplib module to see whether it is. But that's the wonderful thing about open source--you can. Cheers, // mark - From aleax at aleax.it Fri Jul 12 17:58:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 21:58:45 GMT Subject: switch recipe? References: <2cIX8.74333$vm5.2697823@news2.tin.it> Message-ID: Alex Martelli wrote: > Mark McEahern wrote: > >>> or possibly: >>> >>> def make_switch(*args): >>> """Return a generator that loops through args.""" >>> if not args: >>> raise RuntimeError("Missing parameter: args.") >>> def switch(): >>> while True: >>> for a in args: >>> yield a >>> return switch >> >> Holy cow, that's much nicer! > > Wouldn't you get exactly the same observable effect from > the simpler function: > > def make_switch(*args): > """Return an iterator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") > return iter(args) ...and the answer is "no", because the first function returns an unbounded iterator, looping around the args forever, while the second one returns a bounded iterator, looping around the args just once. I don't think there's any substantially simpler way to obtain the first function's effect. Alex From keith at peardrop.demon.co.uk Fri Jul 12 11:56:27 2002 From: keith at peardrop.demon.co.uk (Keith S.) Date: Fri, 12 Jul 2002 16:56:27 +0100 Subject: redirecting stdio Message-ID: <3D2EFC2B.1080504@peardrop.demon.co.uk> Hi, I'm rather new to Python and am trying to embed it into a C++ application. The documentation gives the basics of this, but I want Python's output (stdio/stderr) to be redirected to C++ functions (to display the text in a message window). Can anyone point me to a description or example of how this is done? thanks, Keith From workable4sx4 at yahoo.com Sun Jul 14 06:35:00 2002 From: workable4sx4 at yahoo.com (Autarchoglossa Aline) Date: Sun, 14 Jul 2002 03:35:00 -0700 (PDT) Subject: Fakes... Message-ID: <20020714103500.10215.qmail@web21205.mail.yahoo.com> There is something extremely wrong with every single person in this world. They seem to be part of a pointless simulation. "The Matrix" has portrayed this idea somewhat, yet we watch it and go back to our daily lives. Yet in this very life, underneath the seeming diversity in people's opinions, values, talents, and interests, there is something that makes everyone the same. It is as though this planet is populated only by mindless fakes, objects that provide the appearance of intellect on the surface but are based on only mechanical reflexes and primitive thought patterns. I don't really care if anything I say has been said before, if it was portrayed in movies, in books, or in the lyrics of some useless song. With 6 billion people covering the globe at any given time, thousands and thousands of years of written literature, probability dictates almost any combination of words has occurred numerous times. Yet there is clear evidence there was no action, so those words, just like the people who spoke them, must have been just more fakes. I am forced to use this language (also created by the fakes) because there is no alternative, so everything I write here could be misunderstood to make me sound like one of them, but it will be the action that I take and the dedication that will separate me from them. In my estimation the fakes that occupy this planet don't make up 99%, but more like 99.9999999% of the population. I know this because I've searched, and in my search have so far only found one true ally (I have found him via the internet as well). But even with those numbers we would not give up because there is no logic in giving up. The people on this planet are all fakes because the societies have made them this way. Ideas that populate people's minds have no logic or purpose. Concepts such as religion, god, morality, individualism, freedom, identity, happiness, love and billions of others are all just memes. Like parasites they infect the minds and spread from one person to the next. They have no point or purpose; they exist without any logical basis or foundation. The fakes are completely controlled by them, and they will never see beyond them. To not be controlled by them one must do more then just realize that they exist. One must resist any ideas that have no point, endlessly question, and never accept imperfection or compromise in any answer. We (myself and my ally) are different though. While we have had the limitation of existing only in these societies, something has made it possible for us to resist being indoctrinated into becoming one of those fakes. We have no arbitrary wants, needs, desires, or preferences. If this world continues to exist the way it is then nothing in it will ever have a point. It will always be just a product of random evolution, one with no importance or relevance. The only logical goal is to dedicate our lives to increasing our numbers, those that aren't fakes, so that in thousands of years our numbers may be such that the fakes would no longer be a threat to progress. Those that join us must see every other person occupying this planet as the enemy, and us as their only allies. Like us they must have dedication only to taking the most logical action, and to nothing else. To tell you more about us, we've posted some personal information about ourselves on a website. You'll also find past responses to us on that webpage. Obviously anyone reading this email is most likely just another fake. Do not simply reply to this email, if you do your message will almost certainly be ignored. If you do wish to communicate, first demonstrate your interest by taking the effort to find us online, one of the ways to do that is described below. Use a major search engine to search for every combination of any two words from the list below. The order of the words shouldn't matter as long as you do not search for them in quotes, but generally it should be clear what words can go together and in what order. Also when you pick the right combination you shouldn't need to look at more then the first matches. There are actually at least 7 (or more) different combinations and websites you can find by searching this list. The one you should contact will clearly say it is the 'communication' page and will have three forms to fill out. Mention what sites you did find, the more effort it seems you took the more likely we would believe in your dedication. There is no trick to this and this isn't meant to be quick, it should, however, be fairly clear if/when you find the right site. The following search engines were verified by us, please use any of them as other search engines may simply not list us correctly: Yahoo, Google, InfoSeek, Lycos, MSN, LookSmart, HotBot, InfoSpace, Ask.com, AllTheWeb, Teoma, WebCrawler, AltaVista, AOL Search, Netscape Search, Dogpile. perfect pointless theory endless desire defiance eternal wants logic competitive driving perpetual competition impartial vision logical meaningless teenage infinite dream final best escape fury objective purpose thought indoctrination only ambition clue view perfection If this can't be solved, or if you never reach us, there should be no reason for you to give up as we will never give up and thus there will always be some way to find us. -------------- Ryan and Jacob __________________________________________________ Do You Yahoo!? Yahoo! Autos - Get free new car price quotes http://autos.yahoo.com From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 25 17:39:10 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 25 Jul 2002 23:39:10 +0200 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> Message-ID: <3D406FFE.3050904@NOSPAMREMOVETHISxs4all.nl> Chris Liechti wrote: > http://pyro.sf.net was not yet mentioned :-) It's nice somebody did before I found out about this thread ;-) Irmen de Jong From rs at onsitetech.com Mon Jul 8 14:37:36 2002 From: rs at onsitetech.com (Robb Shecter) Date: 08 Jul 2002 18:37:36 GMT Subject: Why self? References: Message-ID: <3D29DBA4.7070606@onsitetech.com> Brian Quinlan wrote: >> self.__velocity = self.__factor1 * self.__factor2 >> > > Two of those characters are your own fault (the underscores). I don't think so: As I understand it, the double underscores are necessary in order to for the class to function correctly if subclassed. Without them, a subclass could inadvertently use/misuse/overwrite them. These requirements remind me of C++ or Perl, where in order to do the correct thing, you have to go through extra work. Or, conversely, the language encourages you to do the wrong thing. Robb From mcherm at destiny.com Mon Jul 22 16:47:29 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 22 Jul 2002 16:47:29 -0400 Subject: global variables Message-ID: <3D3C6F61.5070400@destiny.com> > Hi! > I 'm completely new to python. So here's my problem: > How can I handle global data in my application? > The application is a database application and I want > to provide non-static informations, like the user id, name, > etc. so that every object can access this information. > Normally, I use C/C++ for coding, but these tricks don't > work ;-) > Maybe, you can give me some hints... > > Thanks in advance > > Thorsten Harms Well, there is certainly more than one way to solve your problem. But I'm going to take a while guess and suggest that perhaps the solution you are looking for is... Global Variables. Ok, it's probably not how I would do it, but your subject line gave it away. Python has global variables... any variable declared at the "top level" (ie, not inside a function or class) is a global variable. The only trick that you need to know is this: global variables are tracked on a per-module basis. This means that if your code is all in one module, then you can go ahead and just use globals. If your code is in more than one module, then a simple solution would be to have a module which exists just to store the global variables. You could then import this in all of the other modules and access the information like this: myGlobals.userId Hope that answers your question. (PS: You might want to consider other solutions. In fact, I think that in this particular case, it is probably NOT wise to use globals... what if one day you want to support (for example) multiple users at once? What I would suggest is that you create a "Connection" class, with userId, name, port, etc as instance variables. But hey... Python is flexible... code it the way you are familiar with for now (but plan to learn Python idioms later).) From gleki at gol.ge Tue Jul 16 07:28:26 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Tue, 16 Jul 2002 13:28:26 +0200 Subject: web-hosting with psp? Message-ID: <3D34035A.F7904AE@gol.ge> Hello! Is there any web-hosting provider, which already supports webware python server pages? I remember a few providers supporting python cgi. Thank you, Giorgi From skip at pobox.com Sun Jul 28 23:03:48 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 28 Jul 2002 22:03:48 -0500 Subject: Guide to the python interp. source? In-Reply-To: References: <15684.23324.498143.792539@localhost.localdomain> Message-ID: <15684.45204.47307.670460@localhost.localdomain> >> I started things off with some notes I wrote a few months ago: >> http://manatee.mojam.com/pyvmwiki/ David> Even better, how about putting it on the Python org wiki? Fine, except for the fact that the Python.org Wiki is down at the moment... ;-) Skip From rajarshi at presidency.com Fri Jul 5 14:42:55 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Fri, 05 Jul 2002 14:42:55 -0400 Subject: shallow copy's Message-ID: Hi, I have some code: a = [1,2,3,4] b = a Do some operations on a Will the contents of b mirror a? Or will b remain unchanged? TIA From cliechti at gmx.net Tue Jul 2 19:01:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 3 Jul 2002 01:01:09 +0200 Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> <35nU8.46034$n4.10990740@newsc.telia.net> Message-ID: "Fredrik Lundh" wrote in news:oqoU8.46049$n4.10994800 at newsc.telia.net: > I wrote: > >> > ... >> > File "/usr/local/apache/MoinMoin/parser/wiki.py", line 335, in replace >> > return apply(getattr(self, '_' + type + '_repl'), (hit,)) >> > AttributeError: Parser instance has no attribute '_hmarker_repl' >> >> I have no idea -- it did work just fine about 30 minutes >> before I saw your post... > > the RecentChanges page has the answer, I think: > > Python Version: 2.2.1 (#1, Jul 1 2002, 20:45:11) Barry fixed it. it works fine now. chris -- Chris From aleax at aleax.it Sun Jul 7 17:22:40 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 21:22:40 GMT Subject: is this a bug? References: <1026076470.877638@master.nyc.kbcfp.com> Message-ID: news wrote: > Python 2.0 (#1, Feb 7 2001, 22:41:16) > [GCC 2.95.2 19991024 (release)] on sunos5 > Type "copyright", "credits" or "license" for more information. >>>> "aa" in ["aa", "ab"] > 1 >>>> "aa" in ["aa"] > 1 >>>> "aa" in ("aa") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'in ' requires character as left operand > > Is this a bug, or should this be consistent between lists and tuples? > > Puzzled. It's a bug in your code. (x) is not a tuple, whatever x -- it's just the value of x enclosed in parentheses. The way to write a tuple whose only item is x is (x,) -- note the comma. So, 'aa' in ('aa') is just line 'aa' in 'aa' -- incorrect because the RHS of 'in' is a string and the LHS has more than one character. 'aa' in ('aa',) is correct and does return 1 (True, in more recent versions of Python, but that's still 1 with a false moustache). Alex From loewis at informatik.hu-berlin.de Fri Jul 26 03:57:02 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 26 Jul 2002 09:57:02 +0200 Subject: locale on Japanese win XP References: <3324f4eb.0207240105.48db826e@posting.google.com> Message-ID: amir at clockwise3d.com (Amir Hadar) writes: > I'm trying to get the locale settings with the locale module under Japanese > windows XP. > when I try to set the locale settings with the following command: > > locale.setlocale(locale.LC_ALL,'') > > the locale throws the following exception: > > locale.Error locale settings not supported > > Any ideas? I've tried to reproduce this with ActivePython 2.2.1, on an English XP with a Japanese locale, Japanese system locale, and Japanese MUI; it always reports 'japanese_Japan.932'. I'd appreciate if others with 'true' Japanese XP could try to reproduce this problem. Regards, Martin From mgerrans at mindspring.com Wed Jul 10 01:21:55 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 9 Jul 2002 22:21:55 -0700 Subject: Learning how to program... but what's the best way? References: <3D2BB54C.90500@earthlink.net> Message-ID: A few posts down, there are some implementions of the 8 queens problem; maybe try to solve this manually on a chessboard for a while (to get an idea of the difficulty and also because it is kind of a fun puzzle), then show the program. A similar problem is the knight's tour, which is where you start with a knight and hop around the board (as knight's do), landing once and only once on each square. From duncan at NOSPAMrcp.co.uk Wed Jul 31 04:37:16 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 31 Jul 2002 08:37:16 +0000 (UTC) Subject: How do you import a module with "." in its filename? References: Message-ID: "Andrew P. Lentvorski" wrote in news:mailman.1028080249.16165.python-list at python.org: > So, how do I import a module with "." in its filename? > fname = 'c:/test/a.test.py' f = file(fname, 'r') a_test = imp.load_module('a_test', f, fname, ('.py', 'r', imp.PY_SOURCE)) f.close() See the module imp documentation for further details. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From thomas.heller at ion-tof.com Wed Jul 31 04:52:49 2002 From: thomas.heller at ion-tof.com (Thomas Heller) Date: Wed, 31 Jul 2002 10:52:49 +0200 Subject: Pyrex / py2exe import interaction References: <20020730165458.A81189@doublegemini.com> Message-ID: <086d01c2386f$a639db10$e000a8c0@thomasnotebook> From: "Clark C . Evans" > Hello. I'm having difficulty with using a combination > of pyrex and py2exe; the problem occurs when the module > compiled with pyrex has an "import". The program then > works just fine until the calling script is packaged > up with py2exe, then you get the following: > > Traceback (most recent call last): > File "", line 1, in ? > File "imputil.pyc", line 103, in _import_hook > File "", line 52, in _import_top_module > File "imputil.pyc", line 216, in import_top > File "imputil.pyc", line 267, in _import_one > File "", line 163, in get_code > File "imputil.pyc", line 89, in _import_hook > File "imputil.pyc", line 152, in _determine_import_context > AttributeError: 'module' object has no attribute 'get' > > Anyway, both of these programs play all sorts of tricks to > get importing to work, so I figure that interaction of the > two importing strategies is causing difficulty. > > Following is the source code for the various files that > I'm using. Further, these files are packged up at > http://clarkevans.com/tmp/prob.tgz ; the build was performed > with ActiveState 2.2.1 on Win2K using py2exe 0.3.3 and > pyrex 0.4 compiled using mingw32, gcc 2.95.3-6 > > Any help would be very cool. My actual setup is much more > complicated than this, but I tried to make the smallest > example which exhibits the behavior. Also, I've had to > split "setup.py" into two distinct files since I didn't > know how to make them both work together. Here's a combined setup script you could use: ----- from distutils.core import setup, Extension import py2exe from Pyrex.Distutils import build_ext setup( name = "Demos", scripts=["test.py"], ext_modules=[Extension("testmod", ["testmod.pyx"])], cmdclass = {"build_ext": build_ext} ) ----- but now to the more interesting questions: It seems to be a problem (as you also have discovered in later posts) in the way Pyrex does the importing. A nice way to debug this (which also works without py2exe, and without windows) is to check it with using imputil's own import hook in the interactive Python interpreter: C:\evans\prob>py22 Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import imputil >>> imputil._test_revamp() # install the hook >>> import testmod Traceback (most recent call last): File "", line 1, in ? File "C:\python22\lib\imputil.py", line 103, in _import_hook top_module = self._import_top_module(parts[0]) File "C:\python22\lib\imputil.py", line 187, in _import_top_module module = self.fs_imp.import_from_dir(item, name) File "C:\python22\lib\imputil.py", line 536, in import_from_dir result = self._import_pathname(_os_path_join(dir, fqname), fqname) File "C:\python22\lib\imputil.py", line 569, in _import_pathname return importFunc(filename, finfo, fqname) File "C:\python22\lib\imputil.py", line 602, in import_file module = imp.load_module(fqname, fp, filename, self.desc) File "C:\python22\lib\imputil.py", line 89, in _import_hook parent = self._determine_import_context(globals) File "C:\python22\lib\imputil.py", line 152, in _determine_import_context if not globals or not globals.get('__importer__'): AttributeError: 'module' object has no attribute 'get' >>> import pdb >>> pdb.pm() > c:\python22\lib\imputil.py(152)_determine_import_context() -> if not globals or not globals.get('__importer__'): (Pdb) l 147 will be looked for within that package. The context could also be None, 148 meaning there is no context -- the module should be looked for as a 149 "top-level" module. 150 """ 151 152 -> if not globals or not globals.get('__importer__'): 153 # globals does not refer to one of our modules or packages. That 154 # implies there is no relative import context (as far as we are 155 # concerned), and it should just pick it off the standard path. 156 return None 157 (Pdb) print globals (Pdb) So we see 'globals' is a module, not a dictionary (as it should be). IMO Pyrex should call PyImport_ImportModuleEx(), which AFAIK uses the import hook, and is also easier to use than to retrieving the __import__ from builtins, and it should probably call it with the result from PyEval_GetGlobals(), but I'll leave this to Greg. HTH, Thomas From mfranklin1 at gatwick.westerngeco.slb.com Tue Jul 16 12:05:59 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 16 Jul 2002 16:05:59 +0000 Subject: preview of object attributes In-Reply-To: References: Message-ID: <200207161509.g6GF9e717190@helios.gatwick.geco-prakla.slb.com> On Tuesday 16 Jul 2002 2:42 pm, Ingo St?cker wrote: > Hello Py-Freaks, > > I have a list which contains objects. These objects have two attributes. > > My task is that the second attribute should be shown a a kind of preview > window. > > but I don't know what to do? Are there any guys who can help me? > > Regards Ingo What are these objects???? we need more details before we can help! From lcullip at techie.com Fri Jul 26 11:38:24 2002 From: lcullip at techie.com (Lee) Date: 26 Jul 2002 08:38:24 -0700 Subject: What am i doing wrong Message-ID: <66614160.0207260738.1cefb9ad@posting.google.com> Hi all, I'm really new to Python programming, only been tinkering with it a couple of days. I started writing this program and can't quite work out what I'm doing wrong. I want the user to enter the details in the dialog box and then when they hit execute it runs the telnet stuff and writes the output back to a file. I'm obviously doing something really stupid and need some help. Any pointers would be great. Cheers Lee My code : import telnetlib import sys import Tkinter from Tkinter import * def detail() : telnet = telnetlib.Telnet(HOST) telnet.read_until("login: ") telnet.write(USER + "\n") telnet.read_until("Password: ") telnet.write(PASSWORD + "\n") telnet.write("ls -l /etc/init.d/oracle.sh\n") telnet.write("ls -l /etc/rc3.d|grep orac\n") telnet.write("cat /etc/oratab\n") telnet.write("exit\n") info = telnet.read_all() file = open('c:/temp/listing.txt', 'w') #write info to file file.writelines(info) file.close() login = Tk() Label(login, text="User Name:").grid(row=0, sticky=W) Label(login, text="Password:").grid(row=1, sticky=W) Label(login, text="Host:").grid(row=2, sticky=W) entry_ln = Entry(login) entry_fn = Entry(login) entry_ph = Entry(login) USER = entry_ln.grid(row=0, column=1) PASSWORD = entry_fn.grid(row=1, column=1) HOST = entry_ph.grid(row=2, column=1) b_execute = Button(login) b_execute['text'] = "Execute" b_execute['command'] = detail b_execute.pack() b_execute.grid(row=7, column = 1) login.mainloop() The errors I'm getting: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "C:\python scripts\teltest.py", line 9, in detail telnet.read_until("login: ") File "C:\Python22\lib\telnetlib.py", line 294, in read_until while not self.eof and apply(select.select, s_args) == s_reply: File "C:\Python22\lib\telnetlib.py", line 260, in fileno return self.sock.fileno() AttributeError: 'NoneType' object has no attribute 'fileno' Process terminated with exit code 0 From jonathan at onegoodidea.com Tue Jul 30 18:41:14 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 23:41:14 +0100 Subject: global interpreter lock not working as it should References: Message-ID: On 30/7/2002 21:43, in article mailman.1028058230.6943.python-list at python.org, "brueckd at tbye.com" wrote: > [...] Sure the GIL makes sure that Python object internals are > fiddled with one thread at a time, but if you have only 1 CPU, there's > only one thread running at a time anyway, regardless of whether your > program is in C or Python. Err... I believe that's why I prefixed my comments with: "If you have a multiple-CPU machine and a kernel-level thread implementation and a multi-threaded CPU-intensive application, [...]." >> Python threads just aren't any good for parallelism. > > Remove the word 'Python' and your statement is more correct. Threads > themselves aren't all that good for parallelism, which is fine because > that's not what they're for anyway. [...] No, I was quite careful in what I said. A good kernel-level threads implementation is perfectly capable of exploiting parallelism on multiple CPU machines. When I say Python threads I mean threads executing Python code. The GIL requires that this happen with mutual exclusion. >> They're mainly useful as a communication abstraction. > > Sorry, but that's just plain wrong. Python threads are useful for the > exact same things threads are useful for in Java, C, etc. (handling > multiple blocking tasks simultaneously, doing "stuff" while waiting for > user input, etc.). Unless you have a bunch of threads sitting around in timewait for the sheer heck of it, all of the blocking that threads do is on external I/O or inter-thread communication. There's no program of this kind that couldn't have been written using an event model instead (and probably more efficiently). Hence my point: they are mainly useful as a communication abstraction. >> You can browse the archives of this group for many (many) discussions on >> "fixing" the GIL, but you aren't going to get a solution. > > That discussion typically revolves around multi-CPU systems, but the OP > didn't mention having multiple CPUs. If the OP isn't trying to exploit parallelism then why write multiple CPU-bound threads? If his threads were blocking to do I/O he'd have no problem, so clearly they are doing CPU intensive work. If there's more than one of them he's trying to do CPU intensive work in parallel. If he doesn't have a multiple CPU machine and a kernel-level threads implementation then this will always be an exercise in futility. All of which brings me back around to my original point: "I think the main problem is that you're trying to do something with Python threads that they just weren't designed for: CPU intensive work." I really do think we're singing from the same hymn sheet here. -no-you're-right!-ly y'rs, Jonathan From jdhunter at nitace.bsd.uchicago.edu Mon Jul 15 13:32:17 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Jul 2002 12:32:17 -0500 Subject: any web application available in python? References: Message-ID: >>>>> "a64bs4$1oo$1 at newsreader" == a64bs4$1oo$1 at newsreader mailgate org writes: > hi.. i want to make a community-oriented website for programmers > well, i don't know what features i would need yet though. squishdot is a python based message board (shashdot clone) that works with the zope framework (not apache). http://www.squishdot.org zope also has a wiki web product, and lots more. JDH From jknapka at earthlink.net Mon Jul 15 21:37:10 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 16 Jul 2002 01:37:10 GMT Subject: App implementation help needed References: Message-ID: <3D3377DD.822E827A@earthlink.net> Dave Swegen wrote: > > I'm currently designing the second part of a little pet project of mine, > and run into a wall regarding how to proceed, and would much appreciate > some assitance in figuring out in which direction I should go. > > The setup is as follows: > > A daemon has a queue of times when it should perform an action that > involves fetching some data from a web site. > > These times, and associated data (which end up customising the URL), is > to be provided by users via a web interface. > > The user provided events, as well as some user data (username, password) > need to be stored. > > The program will in the first instance be running on Linux, but if for > no extra cost I can make it run on other platforms that would be nice > (but not at the cost of simplicity). > > All pretty simple stuff in itself. My problem is how to tie together the > different parts (web interface, updating queues, calling a certain function > at a certain time with certain user provided data). > > Are threads the best/easiest way to achieve this? Are fork()s sufficient? > Or would having the web interface based on asyncore allow me to avoid > using threads/forking entirely? > > Is using the Queue module appropriate, or would a list be sufficient? > > Would using sleep(1) in a loop be sufficient (I need second precision, > so cron is not really an option), or would sched be more appropriate? > > I don't want to use a full DB, so should I go with pickling or anydbm? > > So, lots of questions, probably not enough background information, and > somebody who is rather overwhelmed by the options avaliable. > > I'm hoping to keep this as simple as possible, so please, be gentle :) > > Any help much appreciated. If I were doing this, and I wanted to keep it extremely simple, I would do it like this: (0) Create a special directory, /workdir. This is a blessed place that's used for communication between the web interface and the daemon. (1) The web interface: a simple Python CGI script that essentially does this (forgive the silly fn names; I don't remember how to spell the file operations at present): def handleFormData(): queEntries = processFormData() tempfile = makeATemporaryFilename() f = open(tempfile,'w') f.write(queEntries) # Maybe pickle, but no need if the queue # entries are simple things that can be eval'd. f.close() moveTempfileToWorkdir() (2) The queue handler: a simple Python program that maintains the event list: def mainLoop(): sleep(for a little while) # Maybe use socket.select() if you # want really brief sleeps. processEvents() # Kick off any events that have expired. checkWorkDir() def checkWorkDir(): files = listFilesInWorkdirByCreationDate() for file in files: qes = readQueueEntriesFrom(file) addToEventList(qes) delete(file) It's important that we create the /workdir entries as temp files elsewhere and then move them to /workdir; that way the daemon never sees a half-written work file. You could do checkWorkDir() and processEvents() in separate threads, but that would be less simple! The communication mechanism (files in a blessed work directory) is lame, but should work pretty much anywhere. Porting such a thing to EvilEmpireOS should be a snap (just change the work directory name). I'll be interested to see other proposals. Cheers, -- Joe From max at alcyone.com Tue Jul 30 01:54:29 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 29 Jul 2002 22:54:29 -0700 Subject: ANN: lsystem 1.0 -- Lindenmayer system explorer Message-ID: <3D462A15.93D4943B@alcyone.com> Summary A simple implementation of Lindenmayer systems (also called L-systems, substitution systems) is provided. In basic form, a Lindenmayer system consists of a starting string of symbols from an alphabet, and has repeated transitions applied to it, specified by a list of transition search-and-replace rules. In addition to the standard formulation, two alternative implementations are included: sequential systems, in which at most one rule is applied; and tag systems, in which the transition only takes place at the beginning and end of the string. Despite being implemented entirely in Python, for reasonable rules on a modern machine the system is capable of running thousands of generations per second. Lindenmayer systems are found in artificial intelligence and artificial life and can be used to generate fractal patterns (usually via mapping symbols from the alphabet to turtle commands), organic looking patterns that can simulate plants or other living things, or even music. Getting the software The software is available in a tarball here: http://www.alcyone.com/pyos/lsystem/lsystem-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/pyos/lsystem/. Introduction Lindenmayer systems consist of strings of symbols from an "alphabet"; in this case, the alphabet is all 8-bit characters. The starting string is called the axiom (and is simply a string). Each generation, zero or more transitions are applied to the string, based on a list of rules. Each rule consists of an "input" and an "output"; the input is the search substring and the output is the substring it is to be replaced with. The ordering of the rules is significant. Null strings are legal as both input and output; if at the input, they will match at every location, and if at the output, the search-and-replace will amount to a delete. In the basic implementation (the 'LSystem' class), these transitions are done in order. The system scans through the string, checking the substring starting with the current position against each rule's input in order. If that rule's input matches, that substring is substituted with the output string for that rule; thus, the ordering of rules is significant. If no rule matches, that character is left alone and scanning continues. ... -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From spam at ob_scure.dk Mon Jul 8 19:11:09 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Tue, 09 Jul 2002 01:11:09 +0200 Subject: Clean Exit from Socket/Program References: Message-ID: <3D2A1C0D.5050000@ob_scure.dk> Larry wrote: > Can anyone give me some tips on... > 1. How to shut down a python program cleanly You can catch ctrl-c by catching the KeyboardError exception, like this: try: ... do something ... except KeyboardInterrupt: ... cleanup ... > 2. How to ensure that my socket buffer is empty before closing. Don't know about that one. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From steve.menard at polyester.com Fri Jul 26 09:46:37 2002 From: steve.menard at polyester.com (Steve Menard) Date: Fri, 26 Jul 2002 09:46:37 -0400 Subject: GUI toolkits References: Message-ID: "Cameron Laird" wrote in message news:BEA115092AB774F7.E39E2F1D90F7B623.715FCF3C12A52FBB at lp.airnews.net... > In article , > Steve Menard wrote: > . > . > . > >I personally settle on wxWindows. I will not say I like it. I am used to > >SWING and wxWindows is painful to use. But it works as well on all supported > >platforms. > > > > Steve > > > > > > You *like* Swing? > > Do you want to recommend Jython to the originator of the thread? > -- > Ah, no. And yes I like Swing. Maybe its because I have had the time to learn it properly. Maybe it just makes more sense to me. In any case, I am vastly more productive with it than I ever think to be in wxPython. Perhaps pyQT or pyGTK would change that, bttu since they are not (completely) available on Windows, I don't have the choice of even considering them. Steve From davidw at uq.net.au Fri Jul 12 02:30:39 2002 From: davidw at uq.net.au (David Wright) Date: Fri, 12 Jul 2002 16:30:39 +1000 Subject: Guido van Rossum Tutorial - .PDF or other format? Message-ID: Greetings Could someone please advise if this suberb document is available on the Web in a printer friendly format, such as .pdf or even .doc. (other than the hypetext version on line and on my PC). Yes, I'd like the *address* too ;-) Many thanks in advance David Wright ~~~~~~~~~~~~~~~~~~~~~~~~~~ Education is not the filling of a vessel, but the kindling of a flame." - Socrates ~~~~~~~~~~~~~~~~~~~~~~~~~~ From duduca007 at yahoo.com Wed Jul 31 12:29:36 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Wed, 31 Jul 2002 09:29:36 -0700 (PDT) Subject: Python Questionnaire In-Reply-To: <20020731091858.48784.qmail@web40301.mail.yahoo.com> Message-ID: <20020731162936.14387.qmail@web11404.mail.yahoo.com> --- Marta Gutierre wrote: > > Does any body know of any code in python for > questionnaires ??? > Tipicall web-forms with questions and storing > results in files or things like that Hummmmm. I use PyQt. Would be Designer, from QT, to create de interface questionnaires. The storage to a file would be easy. []'s Cadu Moreira KaduSoft President ----------------------------- [...Jython is cool...] __________________________________________________ Do You Yahoo!? Yahoo! Health - Feel better, live better http://health.yahoo.com From csposting at yahoo.com.au Tue Jul 16 07:15:55 2002 From: csposting at yahoo.com.au (Patrick W) Date: 16 Jul 2002 21:15:55 +1000 Subject: Iterator for Custom Sequence Message-ID: <87u1mzq5xw.fsf@athens.localdomain> Hi folks. To learn how to provide iterators for custom sequences, I've made a typical linked list with the following __iter__ method: class LinkedList: .... def __iter__(self): def genitems(ls): n = ls.head while n.data is not None: yield n.data n = n.next return genitems(self) .... This does the job, but is it eccentric or counter-Pythonic? If so, what's the conventional way to provide an iterator for a custom sequence? From marklists at mceahern.com Fri Jul 12 11:05:01 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 10:05:01 -0500 Subject: Making code 2.1 compatible In-Reply-To: <3D2EED98.BD59D615@tds.net> Message-ID: > Is there a way to ask Python not to allow 2.2 constructs? Having Python > complain when producing .pyc files would be good enough. this is listed as one of the goals of pychecker, which suggests it doesn't currently do that. http://cvs.sf.net/cgi-bin/viewcvs.cgi/pychecker/pychecker/TODO?rev=current&c ontent-type=text/vnd.viewcvs-markup did you know that 2.2 has been deemed the release targeted for stability by the pbf? // m - From rjones at ekit-inc.com Sun Jul 21 04:54:10 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sun, 21 Jul 2002 18:54:10 +1000 Subject: can i make a p2p application in python? In-Reply-To: References: Message-ID: <200207211854.10471.rjones@ekit-inc.com> On Sun, 21 Jul 2002 8:31 am, eugene kim wrote: > like kazaa or napster.. > > is it possible? Yes. Circle is p2p. Richard From opengeometry at NOSPAM.yahoo.ca Tue Jul 9 11:48:17 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 9 Jul 2002 15:48:17 GMT Subject: Splitting a string every 'n' References: Message-ID: Simon.Foster at smiths-aerospace.com wrote: > > What is the idiomatic way to split a string into a list > containing 'n' character substrings? I normally do > something like: > > while strng: > substring = strng[:n] > strng = strng[n:] > > > But the performance of this is hopeless for very long strings! > Presumable because there's too much list reallocation? Can't Python > just optimise this by shuffling the start of the list forward? > > Any better ideas, short of manually indexing through? Is there > something like: > > for substring in strng.nsplit(): > No, you pretty much have to slice out the range you want, ie. substring = string[i:i+n] -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From dfackrell at DELETETHIS.linuxmail.org Fri Jul 26 15:30:05 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Fri, 26 Jul 2002 13:30:05 -0600 Subject: automating control-D References: Message-ID: <3d41a33d$1_1@hpb10302.boi.hp.com> > "Victor Chen" vchen at meetingmaker.com> wrote in message > news:mailman.1027708758.17684.python-list at python.org... > Hi, > I'm fairly new a python stuff, working on my first python script. I was wondering if anyone knows how I can represent control-D as output using python. Firstly, I do not know the special string used to represent the control key and secondly, I would have to automate both the control and the d characters be pressed together. Any help is appreciated. Thank you. > > Victor Ctrl-A through Ctrl-Z generally translate to ASCII characters 1-26 in order, so Ctrl-D is ASCII character 4. chr(4) might do what you want, but might not, too. Programs can choose to only treat Ctrl-D specially if the input stream comes from a terminal. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From sholden at holdenweb.com Mon Jul 29 11:10:11 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Jul 2002 11:10:11 -0400 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> <3d438609$1@duster.adelaide.on.net> <3d439616$1@duster.adelaide.on.net> <2259b0e2.0207280652.202f1721@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:2259b0e2.0207280652.202f1721 at posting.google.com... > Now I see the source of my confusion. I thought the print "statement" > was > actually an expression with result None. However in Python > > result=print("something") > > gives a syntax error. Then my question is: why Guido decided to keep > the distinction between statements (with no value returned) and > expressions ? what are the advantages ? is it a matter of personal > taste ? Sorry if these > questions sounds naive, > He made that decision for the same reason he decided not to allow assignments inside expressions. You can find the justification in the FAQ if you look for it ... 6.30: Why can't I use assignment in an expression. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From lac at strakt.com Fri Jul 5 02:06:01 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 05 Jul 2002 08:06:01 +0200 Subject: Copyright metaphors In-Reply-To: Message from Paul Rubin of "04 Jul 2002 22:30:09 PDT." <7x65zukahq.fsf@ruckus.brouhaha.com> References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> <7xwusbyncl.fsf@ruckus.brouhaha.com> <7x65zukahq.fsf@ruckus.brouhaha.com> Message-ID: <200207050606.g65661LM015924@ratthing-b246.strakt.com> Paul Rubin > The tension between copyright and individual freedom is certainly > stronger now than it was in the 1800's, for reasons RMS talks about in > his speeches. In the 1800's, copying books (in enough volume to be a > problem for copyright holders) was only practical with a printing > press and a lot of typesetting work, making many copies of the same > book. That meant copyright was more like an industrial relation than > today, where it controls what individuals can do in their own bedrooms > with their own computers. > > Anyway, we live in interesting times. > -- > http://mail.python.org/mailman/listinfo/python-list One of the motivations for a copyright law at all was the rapid proliferation of Newspapers. They competed quite favourably with book publishers. Laura From chris.gonnerman at newcenturycomputers.net Wed Jul 10 23:27:53 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 10 Jul 2002 22:27:53 -0500 Subject: Win32 Registry Manipulation w/PythonWin? References: <3D2CDB4F.4357F810@cascade-sys.com> Message-ID: <005b01c2288a$f3bad1e0$0101010a@local> ----- Original Message ----- From: "James J. Besemer" > > Whatzizname's Python Windows book is worthwhile if you're doing much. Would that be Percival Whatzizname or Bartholomew Whatzizname? :-) :-) :-) (maybe this is a new-age Kilroy...) Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From john.abel at pa.press.net Tue Jul 9 07:42:31 2002 From: john.abel at pa.press.net (John Abel) Date: 09 Jul 2002 12:42:31 +0100 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <000601c2269e$09050f50$bd5d4540@Dell2> References: <000601c2269e$09050f50$bd5d4540@Dell2> Message-ID: <1026214951.12828.94.camel@lestat.howden.press.net> I apologise for being a nuisance. I've added the code in, as per Brian's comments below, but still get an error, when running the client: Traceback (most recent call last): File "MDClient.py", line 5, in ? print ServerConn.GetFiles ( "/test/file" ) File "/usr/local/lib/python2.2/xmlrpclib.py", line 821, in __call__ return self.__send(self.__name, args) File "/usr/local/lib/python2.2/xmlrpclib.py", line 975, in __request verbose=self.__verbose File "/usr/local/lib/python2.2/xmlrpclib.py", line 853, in request return self.parse_response(h.getfile()) File "/usr/local/lib/python2.2/xmlrpclib.py", line 896, in parse_response return u.close() File "/usr/local/lib/python2.2/xmlrpclib.py", line 571, in close raise apply(Fault, (), self._stack[0]) xmlrpclib.Fault: Nothing from the over-ridden _dispatch routine is printed out. The only output is from the the default logging of SimpleXMLRPCServer (as below) If I run the server script, with the default request handler, then everything works OK. The client makes a connection, and the server sends back the requested file. The server outputs the following line. lestat - - [09/Jul/2002 11:52:01] "POST /RPC2 HTTP/1.0" 200 - I've even tried running both scripts as root, in case that makes a difference. I've two different builds of 2.2.1 (initial RH install, and the AS install) on Red Hat 7.1. I apologise if it's something simple that I'm missing. Regards John On Mon, 2002-07-08 at 17:39, Brian Quinlan wrote: > OK, I apologise in advance for appearing dense. I've added the code > that was supplied by Brian, and the server script appears to run OK. > However, the client script displays the following error: > > Traceback (most recent call last): [snipped] > xmlrpclib.Fault: OK, it looks like the server is rejecting the client's IP address. > The server script: > > import sys, os, SimpleXMLRPCServer, string > > class AuthenticatingSimpleXMLRPCRequestHandler > (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): > def _dispatch(self,method,params): > self.UnknownIP = "UnknownIP" > if not (self.client_address == "144.178.234.189" or > self.client_address == "localhost" ): > raise self.UnknownIP, "Client IP Is Not Authorised" > else: 1. The IP check would be more readable if you wrote it like: if self.client_address not in ["144.178.234.189", "localhost"]: .... 2. For debugging purposes, try adding the following line: def _dispatch(self, method, params): + print 'client_address: %r' % self.client_address Then rerun your server and client to see why your server is rejecting your client's address. Cheers, Brian From gerhard.haering at gmx.de Mon Jul 22 06:22:46 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Mon, 22 Jul 2002 12:22:46 +0200 Subject: Alex Martelli is off the net for a few days :-( In-Reply-To: <200207221011.g6MABTVa009663@ratthing-b246.strakt.com> References: <200207221011.g6MABTVa009663@ratthing-b246.strakt.com> Message-ID: <20020722102246.GB18696@gargamel.hqd-internal> * Laura Creighton [2002-07-22 12:11 +0200]: > Some construction workers have severed his phone and internet lines. > Expect him back in a few days, not a few hours. :-( Laura, don't lie. I saw you sneek in at night to cut off his cables in order to make him work productively again ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From tdelaney at avaya.com Wed Jul 10 19:52:58 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 11 Jul 2002 09:52:58 +1000 Subject: JPython and Jython Message-ID: Jython is also Python 2.0+ implemented in Java - JPython is only for Python 1.5(.2). The current release version of Jython is 2.1, corresponding (strangely enough ;) to Python 2.1. Tim Delaney > -----Original Message----- > From: A Nilsson [mailto:anders at gamebox.net] > Sent: Thursday, 11 July 2002 2:24 AM > To: python-list at python.org > Subject: Re: JPython and Jython > > > Jython changed name from JPython a while ago - that?s all. > /Ando > > "oblomov" skrev i meddelandet > news:20020710180603.50a4e417.spam at oblomov.org... > > > > Could someone tell me a bit about the diffrences between JPython > > and Jython? I want to implement Python as a scriptlanguage in my > > Java environment. What would be the best solution? > > > > > > kalle > > > -- > http://mail.python.org/mailman/listinfo/python-list > From sandskyfly at hotmail.com Thu Jul 25 16:12:11 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 25 Jul 2002 13:12:11 -0700 Subject: Completion in emacs mode References: Message-ID: "Mark McEahern" : > > I'm looking for the ability to do command completion in Emacs' python > > mode. I haven't managed to get Google to show me anything really > > pertinent to this quest. > > http://www.geocrawler.com/archives/3/338/1993/12/0/1878323/ Useful enough link except for the fact that a portion of the code is missing from the post due to some cut-and-paste mishap. Subsequently, a couple of nice fellows try to salvage the problem by providing diffs of the emacs extension... Given that we are now in dodgy waters, is there an alternative to this route? (perhaps post a complete version of the extension here :-) regards, Sandy From brueckd at tbye.com Sat Jul 20 15:26:47 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sat, 20 Jul 2002 12:26:47 -0700 (PDT) Subject: A better self In-Reply-To: <200720021132243925%pecora@anvil.nrl.navy.mil> Message-ID: On Sat, 20 Jul 2002, Louis M. Pecora wrote: > > 3) Use the smarts of your editor - macros, special syntax highlighting, > > etc. > > Not practical for me (not sure about others) since I tend to develop > using an edit/run style. Python is so quick that with the Macintosh > IDE I just code a little, then quickly run a test. Correct code until > satisfied, then code more new stuff and test. etc. etc. etc. But that > eliminates the macros or fancy editor stuff. It's a great way to code > though (only with Python :-) ) I guess I don't understand what you mean - in my mind the two are independent. For example, if you're bothered by typing 'self.' then bind that text to a hotkey, e.g. Ctrl-s. The benefit doesn't depend on your coding style that much. If readability is your gripe, change the syntax highlighting to make 'self.' be lighter (so it doesn't jump out as much). Again, using an edit/run approach benefits. > > 6) Have Python generate the function bodies for you, e.g: > > > > class SomeClass: > > method = MyCoolUnboundMethodMaker('arg:x = y*z + t*arg') > > Hmmm...what's that? Just an idea - since Python is so dynamic, instead of writing the function you write a string describing the function and have another function read it and generate a method that does all the 'self.' stuff. Obviously you'd have to think it through some, but this is definitely possible. In the above example, I assume MyCoolUnboundMethodMaker would read the string, and use it to generate a string like this: '''def NewMethod(self, arg): self.x = self.y * self.z + self.t * arg ''' after which it would exec the string and then do a 'return NewMethod', and bingo, your class now has a method that performs that operation. It'd take some work to get it right the first time, but from then on you could reuse it for all your numeric work. > > 7) Change your design - if something is awkward it *may* be a flaw in the > > language, but there's also a really, really good chance that a different > > approach to your program would be best. > > Not too relevant to the math required. You have to write a math > expression. Sure it's relevant. For example, you have to specify 'self.' on all your variables because through your design you have *chosen* to make them all members of an object. I think that was a reasonable decision on your part, but it's certainly not the only possibility. -Dave From chris.lyon at spritenote.co.uk Sun Jul 7 14:36:42 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Sun, 7 Jul 2002 19:36:42 +0100 Subject: Concept Error References: <3d27d274$0$24427$afc38c87@news.easynet.co.uk> <3d2809cc$0$24392$afc38c87@news.easynet.co.uk> Message-ID: <3d288a36$0$24413$afc38c87@news.easynet.co.uk> Sussed it. I had a paramenter called conn and in fact I needed conn.conn I've just spent a day and a half focussing on the wrong variable ho hum "chris lyon" wrote in message news:3d2809cc$0$24392$afc38c87 at news.easynet.co.uk... > > Apologies the variable 'a' below should be 'conn' > > "chris lyon" wrote in message > news:3d27d274$0$24427$afc38c87 at news.easynet.co.uk... > > I've been at it all night and I don't understand why this does work:- > > (Its derived from www.e-coli.net/pyado.html , ok it's a straight copy ) > > > > > > import win32com.client > > > > class RecordSet: > > def __init__(self, DBConnection): > > """Initialize a Record Set Object""" > > self.rs = win32com.client.Dispatch(r'ADODB.Recordset') > > self.conn = DBConnection > > > > def listfields(self): > > for x in range (self.rs.Fields.Count): > > print 'Name:-',self.rs.Fields.Item(x).Name > > print 'DefinedSize:-',self.rs.Fields.Item(x).DefinedSize > > print 'Type:-',self.rs.Fields.Item(x).Type > > print 'Value:-',self.rs.Fields.Item(x).Value > > > > conn = win32com.client.Dispatch(r'ADODB.Connection') > > DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/octavia/c4i.mdb;' > > conn.Open(DSN) > > > > fred = RecordSet(a) > > fred.rs.CursorLocation = 3 > > fred.rs.Open('[Categories]',a.conn,1,3) > > fred.listfields() > > > > > > > > But this fails to run. > > > > import win32com.client > > > > class RecordSet: > > def __init__(self, DBConnection): > > """Initialize a Record Set Object""" > > self.rs = win32com.client.Dispatch(r'ADODB.Recordset') > > self.conn = DBConnection > > > > def listfields(self): > > for x in range (self.rs.Fields.Count): > > print 'Name:-',self.rs.Fields.Item(x).Name > > print 'DefinedSize:-',self.rs.Fields.Item(x).DefinedSize > > print 'Type:-',self.rs.Fields.Item(x).Type > > print 'Value:-',self.rs.Fields.Item(x).Value > > > > def getalltable(self , tablename, conn): > > self.rs.CursorLocation = 3 #adUseClient > > self.rs.Open('[Categories]', conn , 1 ,3) #adOpenKeySet > > adLockOptimistic > > > > conn = win32com.client.Dispatch(r'ADODB.Connection') > > DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/octavia/c4i.mdb;' > > conn.Open(DSN) > > > > fred = RecordSet(a) > > fred.rs.CursorLocation = 3 > > fred.getalltable('Categories', a) > > fred.listfields() > > > > > > It Fails with:- > > > > File > > > "C:\Python21\win32com\gen_py\00000205-0000-0010-8000-00AA006D2EA4x0x2x5.py", > > line 2008, in Open > > return self._oleobj_.InvokeTypes(0x3fe, LCID, 1, (24, 0), ((12, 17), > > (12, 17), (3, 49), (3, 49), (3, 49)),Source, ActiveConnection, CursorType, > > LockType, Options) > > TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a > > buffer object. > > > > Why can't I just treat rs as a property of the class RecordSet ? > > Obviously I can get functionality I require but I do not understand why I > > can't treat the RecordSet this way. > > > > I've examined as much of the underlying code as I can but I'm quickly > lost, > > and I notice that win32com.client.Dispatch is a function not a class so I > > can't sub-class it so that way seems closed. > > > > It feels that I am missunderstanding some aspect of the class mechanism so > I > > would dearly like to know what I'm doing wrong. > > > > ( And I will NOT write this app in VBScript :-) > > > > Chris Lyon > > > > > > > > > > > > > > From wadebk at nswc.navy.mil Fri Jul 12 06:53:00 2002 From: wadebk at nswc.navy.mil (Brian) Date: 12 Jul 2002 03:53:00 -0700 Subject: netCDF in 2.2 Message-ID: <57fe7929.0207120253.37865e70@posting.google.com> I'm a relative newbie in Python and I can't get netCDF to work under 2.2 on Windows. I found a .pyd file that makes it work under 2.1 (scientific_netcdf.pyd), but it doesn't work under 2.2. Does anyone have the equivalent version of this file or another easy solution? From matthewm at ihug.co.nz Sun Jul 21 22:27:27 2002 From: matthewm at ihug.co.nz (Matthew) Date: Mon, 22 Jul 2002 14:27:27 +1200 Subject: Problem building/installing zodb Message-ID: <3D3B6D8F.2090004@ihug.co.nz> Hi, I'm trying to get zodb to install. While building ExtensionClass I get following output:- D:\Python22\Downloads\zodb\ExtensionClass>python setup.py build running build running build_py not copying src\Xaq.py (output up-to-date) running build_ext building 'ExtensionClass' extension skipping src/ExtensionClass.c (build\temp.win32-2.2\Release\ExtensionClass.obj u p-to-date) D:\Program Files\DevStudio\VC\BIN\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH :d:\python22\libs /EXPORT:initExtensionClass build\temp.win32-2.2\Release\Extens ionClass.obj /OUT:build\lib.win32-2.2\ExtensionClass.pyd /IMPLIB:build\temp.win3 2-2.2\Release\ExtensionClass.lib d:\python22\libs\python22.lib : fatal error LNK1106: invalid file or disk full: cannot seek to 0x3ca2d08c error: command '"D:\Program Files\DevStudio\VC\BIN\link.exe"' failed with exit s tatus 12 I pretty new at all this stuff, but I've checked out and eliminated all the obvious causes (as stated by error msg, ie: disk full, python22.lib exists, etc). Platform is python2.2/win2k/vstudio97. I've also tried building in vs97 and get identical error while trying to link. Any help would be much appreciated. Thanks, matthew. From null at obscure.dk.X Thu Jul 4 17:07:46 2002 From: null at obscure.dk.X (Thomas Jensen) Date: Thu, 04 Jul 2002 23:07:46 +0200 Subject: start working with gzip : probs with linux/windows References: Message-ID: <3D24B922.2000605@obscure.dk.X> Do you open the files in binary mode? Makes a difference on Windows. /Thomas Pablo Pernot wrote: > Hello all, > > I started working with the gzip module. > It works fine in full linux env. > But when I upload (working with socket) gzip files in a windows env, > the files appear corrupted. > any clue ? From m.faassen at vet.uu.nl Tue Jul 9 08:23:01 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 9 Jul 2002 12:23:01 GMT Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: Thinkit wrote: > These people are dangerous, and will boot you if you do not agree to > their narrow worldview. They are an affront to the python > language--especially "dash". And it is full of Python Secret Underground agents too! Me, I go there to claim C++ is a superior programming language and that Lisp sucks, for much fun and amusement. They do kick you out a bit readily, I agree. I got somewhat annoyed when I got kicked out while apologizing for spamming with a misfired copy & paste buffer. Regards, Martijn From joost_jacob at hotmail.com Sun Jul 28 03:17:19 2002 From: joost_jacob at hotmail.com (J.Jacob) Date: 28 Jul 2002 00:17:19 -0700 Subject: turtle module information References: <13285ea2.0207261327.2827b3a6@posting.google.com> Message-ID: <13285ea2.0207272317.39a94189@posting.google.com> [David Wright] > Hi, > Since you have been using turtle.py, could you please tell this newbie how > to import it into IDLE and start using the turtle commands. Where do the > graphics appear? If you run idle you can type at the ">>>" prompt: >>> import turtle >>> turtle.write('David') Now you will see a separate window popping up with 'David' in it. From cliechti at gmx.net Wed Jul 31 19:04:07 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Aug 2002 01:04:07 +0200 Subject: Python and Sockets, References: <3D486809.6F2DC882@nospam.com> Message-ID: John J Breen wrote in news:3D486809.6F2DC882 at nospam.com: > Hey all, > I am writing a program in Pygtk that also has a Python/TK > component. I need these two components to be able to communicate with > one another through a third component written in python. I would like to > use sockets to send information back and forth, but am running into some > trouble. The components may be sending information at any time so I need > to the sockets to be able to listen/send at any time. I cant have a loop > for listening because that would keep the user from sending events to > either the gtk or TK interface. Someone suggested _createfilehandler but > Im not sure what that is... Does anyone have any suggestions for such a > problem? you'll probably want to look at the threading module. to learn about threads, you can look at the slides on Aahz page: http://www.pythoncraft.com/ whith threads you can have a loop in one thread and the other is still serving the GUI. you might want to look at the Queue module too, as it provides an easy solution to savely pass data from one thread to an other. (from the comm thread to the GUI and back) chris -- Chris From markus.vonehr at ipm.fhg.de Thu Jul 4 11:03:15 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 04 Jul 2002 17:03:15 +0200 Subject: sprites in Tkinter? Message-ID: <3D2463B3.A7CA6E1D@ipm.fhg.de> Hi out there, is there a possibility to create some sort of sprites in TkInter? Thnks for any comments, Markus From aleax at aleax.it Sun Jul 21 13:41:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Jul 2002 17:41:05 GMT Subject: Base classes or global functions References: Message-ID: Stephen Boulet wrote: > I have two classes, Class1 and Class2. Class1 contains a list of Class2 > objects, but no inheritance is involved > > Both classes use some functions I wrote. What's the best way of making the > functions available to the classes? > > -- Stephen, who's trying to develop good programming habits Put those functions you wrote into their own module, say myfuns.py. Import that module from each of the modules implementing Class1 and Class2, at the start of the module, i.e., have: import myfuns early in each of the class1.py and class2.py modules. Then whenever in those importing modules you need to call a given function, say, givefu, defined in myfuns.py, call myfuns.givefu(). Alex From marklists at mceahern.com Thu Jul 11 15:27:40 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 11 Jul 2002 14:27:40 -0500 Subject: writing output to file In-Reply-To: Message-ID: > Inspired by an existing Perl script, I wrote this chunk of code, > but instead of writing the result to the screen, I would like > to write output to a another file. f = file(output_filename, "w") # use "a" if you want to append f.write(data) # to your heart's content f.close() You can also spell file as open, but file is preferred since that matches the returned object's type. Play around with the file descriptor in Python's interactive shell to see other methods: $ python >>> f = file("junk", "w") >>> dir(f) etc. // m - From mwh at python.net Fri Jul 26 09:03:54 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 13:03:54 GMT Subject: Guide to the python interp. source? References: Message-ID: "Tim Gahnstr?m /Bladerman" writes: > Hi > <> > Is there a guide or a recomended way to "get to know" the source > code to the python interpreter? Don't think so. I've had thoughts of writing one, but never got far enough into it for it to be worth showing anyone else. It seems to be difficult pedagogically to explain one area without requiring knowledge of areas not yet covered. OTOH, the interpreter source is mostly clearly layed out, well written C. There are dragons in some areas (bits of the import process, coercions), but not many. > <> > I am creating a new language and an IDE intended for beginners. This is my > CS master thesis. I plan to use Python as primary language and the Python > interpreter as my interpreter. I will probably need to make quite a few > changes to the the interpreter to make the language behave the way I want, > and I will need to monitor the state of the interperter for debugging > purposes Oh, and the compiler's not that nice either. What sort of changes are you thinking of? You may be better off using the compiler package in the standard library, or at least leveraging it. > <> > Python is, I think, a verry intuitive language for beginners, with some > modifications it can be even better. Especially with a good IDE. That is > what I have set out to create. I have designed the language I want to creat > and I have made the first draft of the IDE using Tkinter but I have a big > problem with the python source. It is quite extensive and I am not one of > those people that can have a look at a million lines of code and se the > connections. The Python source also has the property that you don't need to read all of it to get the big picture. > The best would be, ofcourse, some UML documentation Of course? Um, dissent from here... > but I would also be happy if I found a small description och what > code is where, Well, the interpreter mainloop is in Python/ceval.c, object type implementations are in Object/*.c, ... > how to compilem, compiling is easy, at least on Unix or Win32. > design thoughts Reading Include/object.h (and maybe other headers -- objimpl.h?) might give some clues. > or anything like that. A lot of projects have "a small guide for > wannabe developers" but I havn't found anything like that for this > project. There's http://www.python.org/dev/, but there's nothing of the sort you're asking for here, really. > Not on the website and not in any FAQ. > Things I want to change is for example, everything should be "call by > refferense", That may be very hard. If you want things like this: def f(x): x += 1 i = 2 f(i) i --> 3 then you have problems. > it shall not by case sensitive, Easy. > redirect output, Probably easy. Not quite sure what you mean here. > better errormesages, Examples? Feel free to contribute these back to the project... > etc, etc. > > < question>> > I have given it some thought and think that I can make alot of my changes by > preprocessing the code and turn it into correct python code before I send it > to the interpreter but that is not viable for everything so I will need to > look into the sources anyway. For instance the graphics libary I plan to > create I can do all in Python (speed is not an issue). > Any thoughts on the subject is ofcourse more then welcome and I am sure I > will come back with other questions but the first thing I need is a guide to > the Python interpreter sources. Have you written any Python extensions in C? That gives you a pretty good idea of what is going on in a certain, important area. Cheers, M. -- I never realized it before, but having looked that over I'm certain I'd rather have my eyes burned out by zombies with flaming dung sticks than work on a conscientious Unicode regex engine. -- Tim Peters, 3 Dec 1998 From gleki at gol.ge Mon Jul 1 06:35:36 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 01 Jul 2002 12:35:36 +0200 Subject: QT->XML->Pmw->GUI Message-ID: <3D203078.577C501E@gol.ge> Hi all! As we surely know, an excellent GUI builder, QT designer primarily produces XML-based UI file. My question is: -Is there any available script in Python transforming the .ui file in Tk+Pmw based .py file? And if not, what do you think, would it be meaningful to make such a script? E.g., sort of uip compiler along with the uic compiler... Greetings, Giorgi From andreas at kostyrka.priv.at Tue Jul 30 17:31:20 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 30 Jul 2002 23:31:20 +0200 Subject: HTMLGen in Zope (Update) In-Reply-To: <3D3BC69A.8010509@mxm.dk> References: <3D3BC69A.8010509@mxm.dk> Message-ID: <1028064678.5015.24.camel@vaio2> Am Mon, 2002-07-22 um 10.47 schrieb Max M: > Just put HTMLgen in /lib/python/ > > and then, asuming it is a normal module: > > import HTTMLgen > > ... etc. > > There is no need to call allow_module or anything special to use a > module in Zope. And you certainly should not install it as a product as > it does no through the web management. Well this probably wouldn't work for PythonScripts, which have strictly limited namespace. (Basically the same namespace that DTML methods do have.) Andreas From donn at u.washington.edu Tue Jul 9 12:44:24 2002 From: donn at u.washington.edu (Donn Cave) Date: 9 Jul 2002 16:44:24 GMT Subject: sending a file through sockets References: <3D277DDC.1040705@nowhere.org> <1026007094.566332@yasure> <3D280B4B.8020008@nowhere.org> <3D29FBA5.7080707@nowhere.org> Message-ID: Quoth Bryan Olson : | Donn Cave wrote: ... |> They certainly ought to |> be much more robust than the present example needed to be, since it |> really was more introductory. What perhaps is really harder than it |> looks, is deciding "how much is enough". Part of my job is to decide |> how robust an application needs to be, and while it may be good to |> err on the side of safety, that doesn't excuse me from making the call. | | For an internet application, it turns out to be more than most people | think. It's a rough network out there. I'm going to try one last time to clarify my point here: it _depends_ _on_ _the_ _application_. Some applications need to be as bomb-proof as possible, but many others don't. That isn't because they're not "professional", or not "real", it's because the risk is a tolerable trade-off for the complexity of a bomb-proof solution. Python's network client modules are that kind of trade-off. If you can develop alternative implementations that are as portable, as simple to use and maintain, but are more robust, then I'm sure we're all ears. | [...] |> The signal issue with httplib.py is another matter. It isn't so much |> about sockets, as C stdio via file objects. I wouldn't have written |> it that way myself, because of liabilities like this. recv(2) will |> return EINTR, and socketobject.recv() will accordingly raise an exception, |> so there is no ambiguity. fileobject.read() ignores the error. The |> example used recv(), so it didn't put its foot in that hole to start with. |> But that's another trade-off - the authors of those modules apparently |> felt that the simplicity of a file object solution was worth the lossage. | | I have to disagree. The trouble with signals is their global-ness. The | modules don't handle the exception on EINTR. One module using an alarm | can break others. On the other side, the sockets module (on some | platforms) calls signal to ignore SIGPIPE. That could come as a | surprise to other modules or users, and it's possible someone else might | set it back. There are more problems than that with signals. Python does what it can with them, but as an interpreted language it is at a natural disadvantage. If it were my job to write the distribution socket clients, I wouldn't handle EINTR either - some applications might want it to interrupt a read, and unless the API is going to support alternative options on this matter, it's the best one. That's one of the issues you're going to have to deal with in your improved socket clients, right? More complicated API. What is ``I have to disagree'' about? Are you saying that you have a plan to make file objects work fine with sockets and signals? I don't think I agree with ignoring SIGPIPE, but we seem to be wandering from the topic of introductory socket examples. | I welcome you to send a byte count. I didn't even say it was bad | advice; just that it's not really needed, and since the protocol | didn't check it, we might as well take it out. To me, this one looked | like a job for HTTP/0.9. If you ever get your hands an actual application that sends a byte count but doesn't look at it on the other end - leave it alone. A couple of revisions down the line, some instance of the other end will check that byte count, and you won't have to break all the others when you put it in. | For a flexible protocol I would not recommend sending a single byte | count as a prefix, because in many cases the sender doesn't know how | much data he'll be transmitting. It's a huge pain to have to buffer the | entire transmission to see how big it is. So we'd want a chunked | representations, or a maybe a second control connection. Even better, let's use XML and make the server parse everything. Ha, ha. If you want to divide your data into several sends, that's OK, just send a byte count with each and some indication that either this one is or is not the last. Donn Cave, donn at u.washington.edu From ianb at colorstudy.com Sat Jul 13 18:21:52 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Jul 2002 17:21:52 -0500 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: References: <3D2FAE89.21082.361CABA@localhost> Message-ID: <1026598912.3148.341.camel@lothlorien.colorstudy.net> On Sat, 2002-07-13 at 12:34, Roy Smith wrote: > My fear is that if I could just collapse the body of a compound > statement with a single click, it would be too tempting to write huge > monolihic functions that go on for hundreds of lines. I think it would be the other way around -- when you have short functions, you end up having lots of functions. To understand what's going on, you need to look at the larger picture more often -- an overview of all the functions and their signatures. This would allow you to do that more easily. I'm not sure about the importance of collapsing control structures, as opposed to just functions and classes -- *that* seems like it might be abused to hide excessive complexity. But I usually figure abuse is up to the individual programmer -- just like you can access private variables in Python fairly easily, I see no reason to force people to program right. They'll pick that up for their own reasons anyway, if they are smart. Ian From jepler at unpythonic.net Mon Jul 15 19:59:24 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 15 Jul 2002 18:59:24 -0500 Subject: Maximizing observations from Sparse matrices In-Reply-To: <72F73B808A78D511A73600034771D9FF717E14@dc_exchange2.howrey.com> References: <72F73B808A78D511A73600034771D9FF717E14@dc_exchange2.howrey.com> Message-ID: <20020715185924.B987@unpythonic.net> I'm going to first try to re-state your problem. You are given a set of observations. Each observation is in a particular region and has several variables. class Observation: def __init__(self, region, variables): self.region = region self.variables = variables A "None" value is used in the variables list when the observation is not available. A Dataset is a list of Observations. In each observation in a dataset, the indices of the variables are assumed to correspond. The score of a dataset is def score(dataset): return (len([ob for ob in dataset if not None in ob.variables]) * len(dataset[0].variables)) I don't see why it's necessary to eliminate Regions, since a region with no complete observations yields 0 to the score in any case. So you're left with choosing the subset of "var" columns. You could use VariablePicker to choose only a subset of variables from an Observation: def VariablePicker(ob, columns): return Observation(ob.region, [ob.variables[column] for column in columns]) def prune(dataset, columns): return [VariablePicker(ob, columns) for ob in dataset] With the preliminaries out of the way, the question is for what value of columns is score(prune(dataset, columns)) maximized Well, there are 2**len(obs.variables) different values to pick for "columns". I don't see an obvious way in which a greedy approach can be guaranteed to find the best answer. (eg start with an empty list of columns. At each step, append to the list the column that maximizes the score, terminating when no "nearby" list is better) Consider a configuration like: V1 V2 V3 X X X X X X X In the greedy algorithm I just described, column v3 would be chosen first (score 3), and then no better column would be found. Actually, the best score comes from choosing [v1, v2] (score 3). If I had to suggest an approach, I'd start with some randomized subset and then while it gave me a better score I would take a "random walk" to nearby subsets, those formed by adding or removing a small number (or just 1) of elements from the subset. After picking several random starting points, I'd just go with the best answer I'd seen so far. However, I don't see how it's possible to exhaustively search the whole problem space or otherwise be sure you've found the best answer. Maybe somebody with a better background in this kind of algorithm question could speak up. You might have better luck asking in a language-neutral group that knows about the problem domain and then figuring out how to implement the algorithm in Python. Jeff PS if this dataset is really big, you're probably using Numeric to process it. In that case, my program snippets above won't directly help, but they were helpful to me in thinking about the problem... From fakeaddress at nowhere.org Tue Jul 9 04:31:57 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 09 Jul 2002 08:31:57 GMT Subject: Clean Exit from Socket/Program References: Message-ID: <3D2A9F81.50702@nowhere.org> Larry wrote: > Hi: > > I have a program running where data is being continuously fed into a socket > connection. It seems when I exit the program (control c from keyboard), I > lose a lot of the data that was in the socket buffer. I know this is the > wrong way to shut down...but right now, I know no other way. > > I am used to VB where when I shut down a program from a form, my unload > event triggers and I can clean up. I am fairly new to python, and I am not > sure how to trigger a shutdown signal which would then allow my program to > catch up and clean up before exiting. > > Can anyone give me some tips on... > 1. How to shut down a python program cleanly Much the same as in VB. Every module needs to get the shutdown message, and end it's own task cleanly. > 2. How to ensure that my socket buffer is empty before closing. First, your protocol must coordinate the termination of the sender and the receiver. To terminate socket transmission cleanly, each side should do sock.shutdown(1) which terminates sending, and then read until the termination of the other's transmission, which you can detect by a recv() that successfully returns zero bytes. Then you can close() or destroy the socket. Contrary to popular belief, doing a shutdown(0) (of the receive side) before a close() is unimportant. --Bryan From bokr at oz.net Sun Jul 14 03:09:26 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2002 07:09:26 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308c96_8@news.newsgroups.com> Message-ID: On Sat, 13 Jul 2002 22:32:32 +0200, JB wrote: [...] > >f will be *slow*. The list entries are tuples and the tuple >entries are strings. Then f is "in" for strings, that is it >checks, if one string contains another one. What I want to >implement, is a list view with incr4emental search. There What kind of incremental search? Just matching leading characters? Or matching additional words anywhere? Or arbitrary word fragments? Or? >will be up to 250000 entrie in the list view at the moment >(for example all headers of the news group >alt.binaries.mp3.classical) and this number is going to >increase in the future as news servers become bigger and >bigger. I thought that when f is slow, then at least the >merging should be as fast as possible. This sounds like the data changes fairly infrequently compared to how often it's searched. Would a costly indexing job run infrequently be worth while if it paid off in search speed? There are probably better ways to generate a selection than brute scanning of python lists with strings, but just to get the requirements down, does this do the kind of incremental search you are interested in? -- >>> class IncSrch(object): ... def __init__(self, master_list): ... self.master = master_list ... self.curr = [] ... def new_search(self, patt): ... self.curr = [x for x in self.master if x[1].find(patt)!= -1] ... def inc_search(self, patt): ... self.curr = [x for x in self.curr if x[1].find(patt)!= -1] ... def __repr__(self): ... return '\n'.join([`x` for x in self.curr]) ... Here we just generate a list of example tuples with ids and random-suffix strings: >>> import random >>> r = random.Random() >>> master1 = [(i,'item_%s%s' % (r.choice('ABCD'),r.choice('XYZW'))) for i in xrange(10)] >>> master1 [(0, 'item_AZ'), (1, 'item_BX'), (2, 'item_BY'), (3, 'item_BZ'), (4, 'item_AZ'), (5, 'item _BW'), (6, 'item_BW'), (7, 'item_DY'), (8, 'item_BY'), (9, 'item_CY')] (Is this like your data? Or how does it differ?) Here we initialize a search object with a master starting list and nothing selected >>> is1 = IncSrch(master1) >>> is1 >>> `is1` '' I.e., there is nothing selected to the curr list yet. Here we do a first search based on containing substring 'D': >>> is1.new_search('D') Just typing the name calls repr to print the current state of the search object: >>> is1 (7, 'item_DY') That wasn't much to do a secondary search on, so we do a new search on the master list for 'B': >>> is1.new_search('B') >>> is1 (1, 'item_BX') (2, 'item_BY') (3, 'item_BZ') (5, 'item_BW') (6, 'item_BW') (8, 'item_BY') That got a few, so we incrementally search for 'Y': >>> is1.inc_search('Y') >>> is1 (2, 'item_BY') (8, 'item_BY') And so forth. Is that the kind of thing you want to do? I presume you have to pass a list of items in some form to the display widget, and that you will not want to pass more than say MAX_FOR_WIDGET items for a reasonable scrolling display, and you may(??) need the items as a list of strings, not tuples, so you might want to add a first_for_widget() and next_for_widget() method to the class as part of the definition (but I'll do it separately here since I have some state above to use): >>> def first_for_widget(self): ... self.first = 0 ... return ['id:%s -- %s' % (x[0],`x[1]`) for x in self.curr[0:MAX_FOR_WIDGET]] ... >>> def next_for_widget(self): ... self.first += MAX_FOR_WIDGET ... return ['id:%s -- %s' % (x[0],`x[1]`) for x in self.curr[self.first:self.first+MAX_FOR_WIDGET]] ... >>> MAX_FOR_WIDGET = 4 Here we'll dynamically add in the methods above that normally would be defined in the class: >>> IncSrch.first_for_widget = first_for_widget >>> IncSrch.next_for_widget = next_for_widget Let's get the bigger first search results again: >>> is1.new_search('B') >>> is1 (1, 'item_BX') (2, 'item_BY') (3, 'item_BZ') (5, 'item_BW') (6, 'item_BW') (8, 'item_BY') Now the first items for a widget: >>> is1.first_for_widget() ["id:1 -- 'item_BX'", "id:2 -- 'item_BY'", "id:3 -- 'item_BZ'", "id:5 -- 'item_BW'"] That was MAX_FOR_WIDGET (4) items, now get some more: >>> is1.next_for_widget() ["id:6 -- 'item_BW'", "id:8 -- 'item_BY'"] That used them up without making a full four. Try for next: >>> is1.next_for_widget() [] Nothing left. Now do the incremental search again, but let's go for the W's: >>> is1.inc_search('W') >>> is1 (5, 'item_BW') (6, 'item_BW') Get the first part of the list for the widget >>> is1.first_for_widget() ["id:5 -- 'item_BW'", "id:6 -- 'item_BW'"] That was all of it: >>> is1.next_for_widget() [] If you will comment on what this simple class does and doesn't do that you need functionally, that will establish unambiguous requirements. Then we can make it fast one way or another. Regards, Bengt Richter From gerhard.haering at gmx.de Fri Jul 26 05:33:07 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 26 Jul 2002 09:33:07 GMT Subject: redirect to > and to console ? References: Message-ID: "Shagshag13" wrote: > hello, > > i use many python script like that : ./myscript.py file_in > file_out > > i wish i would sometimes like to force output to be redirect to console > instead of file file_out, is there any way of doing that? (for example to > display errors message while file_in will contain only data processed) [...] Unix and Windows consoles have two different output streams: the standard output one and the error stream. Standard output is accessible from Python as sys.stdout, the error stream as sys.stderr. To write to the error stream, either one of sys.stderr.write("foobar\n") and print>> sys.stderr, "foobar" will work fine. I'd use the print>> form, because it has the advantage that it annoys the Martellibot, among others ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From renzo.tomaselli at tecnotp.it Tue Jul 16 14:05:59 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 16 Jul 2002 11:05:59 -0700 Subject: inheriting from C types Message-ID: <878dc260.0207161005.6fec78ec@posting.google.com> Hi all, I'm looking at tips & tricks about inheriting from a C type. It works (almost), but from any derived class I'm not able to see any base class method. Say I implemented a C-type "ype" having Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE flags as well as tp_dealloc, tp_getattr slots. Allocators, constructors etc. are usual defaults. Now, in Python: import ype class k(ype.ype): pass k1 = k() I cannot see/invoke any method on base class ype from k1, while I can see all of them after direct creation of a base instance, say k2 = ype.ype(). I noticed that invoking any such method on k1 ends up in calling PyObject_GetAttr, which finds slot tp_getattro on the derived class k; this in turns calls PyObject_GenericGetAttr which fails. Almost surprisingly there is no attempt to climb the base class hierarchy. Any help is appreciated, Renzo Tomaselli From jblazi at hotmail.com Sat Jul 13 16:42:39 2002 From: jblazi at hotmail.com (JB) Date: Sat, 13 Jul 2002 22:42:39 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: <3d308ef3_2@news.newsgroups.com> Alex Martelli wrote: > JB wrote: > ... > >> remains sorted, that is, the entries from >> should be inserted to the right positions in . >> When is defined by >> n := max(len(list1),len(list2)), >> then should work in O(n) time. >> >> Any hints of how to do this (as fast as possible)? > > Hmmm, I hadn't seen the O(N) constraint. The approach > previously posted by Emile and commented on by me does > not guarantee meeting that constraint: it CAN happen to > become O(N log N) when most of list2 ends up appended > to list1. For an O(N) guarantee, I think you must use > a merge-like linear scan on the lists -- also requiring > O(N) temporary auxiliary storage, of course. > > > Here's a fancifully-expressed solution...: > > au = [None] * 2 > it = iter(list1) > au[0] = [ it.next(), 0, it, [] ] > it = iter(list2) > au[1] = [ it.next(), 1, it, [] ] > > while True: > m = min(au) > i = m[1] > if i and f(m[0]): i = 0 > au[i][3].append(m[0]) > try: m[0] = m[2].next() > except StopIteration: break > > # now, either list is exhausted > # if any tail is left in the first list, copy it > au[0][3].extend(au[0][2]) > # if any tail is left in the second list, distribute it > for x in au[1][2]: > au[not f(x)][3].append(x) > > # finally, copy the results back > list1[:] = au[0][3] > list2[:] = au[1][3] > > > OK, OK, NOT the most lucid code I ever posted, I agree. > > But I get it by reasoning back from the GENERAL case of > mergesort (for any number of streams) and specializing > for 2 streams AND adding the subtle asymmetry beteween > the first list (whose items must all go to the first > auxiliary list) and the second one (whose item must go > to the first auxiliary list iff they satisfy predicate > f, otherwise to the second auxiliary list). I bet you > can do better by exploiting the specifics of this case!-) > > Still -- this IS O(N) in time and space! Thx. I shell try to understand this to-morrow. I am working on a list view item. Deoending on a string (that even may be a regular expression), some of the entries of the list view are shown and some of them are not. I thought, I should use two lists for that: A list of the visible entries and a list of the invisble entries. The original QListView (I use PyQt, that is wonderful by the way) is not very suitable for this as it is too slow. If I do everything myself, I can be much faster as I only implement zje functionality I need. Later I can do everything in C++ and assembly language, if I have the time for this. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From fakeaddress at nowhere.org Tue Jul 9 19:09:54 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 09 Jul 2002 23:09:54 GMT Subject: Clean Exit from Socket/Program References: <3D2A9F81.50702@nowhere.org> Message-ID: <3D2B6D49.9020903@nowhere.org> Larry wrote: > The problem here is that I cannot communicate with the other socket. In > other words, when I connect, data starts to flow. And data never stops > until the other side sees that I am not there anymore. Is the other side's programming under your control at all, or is there any definition of what things would make it stop sending? --Bryan From gerhard.haering at gmx.de Tue Jul 2 02:39:48 2002 From: gerhard.haering at gmx.de (=?ISO-8859-1?Q?Gerhard=20H=E4ring?=) Date: Tue, 2 Jul 2002 08:39:48 +0200 (Central Europe Daylight Time) Subject: Python language dedicated Wiki In-Reply-To: References: Message-ID: <20020702063736.A44AD4B2@gargamel.hqd-internal> Klaus Reinhardt wrote: > Am 01.07.02 22:04:41, schrieb "David LeBlanc" : > > I've always thought it would be a nice idea to put PythonDoc into a wiki, > > not only on a website, but also as part of the distribution. > --------------------------------------------------------------------- > Hi > What does mean Wiki; no acronym found. > K at Rdt > --------------------------------------------------------------------- Google, first hit: http://c2.com/cgi/wiki This is where it all started :) Gerhard From chris.gonnerman at newcenturycomputers.net Sat Jul 13 00:32:01 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 12 Jul 2002 23:32:01 -0500 Subject: hiding command line input References: <3D2FA84F.7080002@doit.com> Message-ID: <000f01c22a26$4100f1e0$0101010a@local> ----- Original Message ----- From: "destr0" > Is there another python function > that will get input in the manner raw_input() does, but mask the > input from the user, or am I going to have to roll my own > function. Found in the Library Reference: 6.12 getpass -- Portable password input Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From gerhard.haering at gmx.de Tue Jul 9 04:13:39 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 10:13:39 +0200 Subject: Table Widget (without Installation) In-Reply-To: <3D2A9948.5090304@thomas-guettler.de> References: <3D2A9948.5090304@thomas-guettler.de> Message-ID: <20020709081339.GA1252@lilith.my-fqdn.de> * Thomas Guettler [2002-07-09 10:05 +0200]: > Hi! > > I am searching for a table widget to > use with python. Is it still true that > tkinter has none? > > I need it for an application on win32 > which should not be installed. All > libraries will be in one directory. > > pyFox, pygtk, wxpython are options. The wxPython grid and list controls are excellent. I'd recommend you download wxPython and click thru all the examples in the demo application. This will show you what is possible and how to do it. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 24.8 ?C Wind: 2.2 m/s From tjreedy at udel.edu Thu Jul 4 10:25:03 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Jul 2002 14:25:03 GMT Subject: Forward Declaring Py_complex References: Message-ID: <3VYU8.600843$Oa1.37637572@bin8.nnrp.aus1.giganews.com> "Mark Charsley" wrote in message news:memo.20020704104527.604A at a.a... ... > for it, and don't treat it as a syntax error" then I can avoid having to > force all my class's clients from having to pull in a lot of header files > that most of them don't care about. This will have two benefits: > 1) build times won't be hit by having to process unnecessary headers for > each cpp file > 2) my workmates won't spend the next week moaning that I've broken their > build and asking which directories they have to put in their project's > include path to fix it. Given these desiderata, I would consider handcrafting a minimal 'mypyplex.h' include with just the stuff needed, even knowing that it might break and need editing for some future version of Python. Terry J. Reedy From b.maryniuk at forbis.lt Thu Jul 4 08:51:07 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 14:51:07 +0200 Subject: sending a file through sockets In-Reply-To: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> Message-ID: <200207041451.07268.b.maryniuk@forbis.lt> On Thursday 04 July 2002 14:17, Guyon Mor? wrote: > Who knows how to send and receive a file(binary data) through sockets? At least you can convert it to MIME base64 first... -- Sincerely yours, Bogdan M. Maryniuck As usual, this being a 1.3.x release, I haven't even compiled this kernel yet. So if it works, you should be doubly impressed. (Linus Torvalds, announcing kernel 1.3.3 on the linux-kernel mailing list.) From maxm at mxm.dk Fri Jul 5 03:58:47 2002 From: maxm at mxm.dk (Max M) Date: Fri, 05 Jul 2002 09:58:47 +0200 Subject: Memory ? References: Message-ID: <3D2551B7.30206@mxm.dk> Shagshag13 wrote: > Hello, > > i'm still looking for a way to check which are the best ways to save memory because i work on many GB with float, etc. so is there a > way to check how many bytes needs an object, a tuple, a list, a dict of objects and so on ? (something like itemsize for array - in > fact array should be great if they weren't boxed) With no kind of authority I would guess that Numpy is what you need. http://sourceforge.net/projects/numpy regards Max M From chitales123 at rediffmail.com Thu Jul 25 04:00:55 2002 From: chitales123 at rediffmail.com (shilpa chitale) Date: 25 Jul 2002 08:00:55 -0000 Subject: VERY URGENT : Python 2.2 Installation on Solaris 2.5 Message-ID: <20020725080055.8462.qmail@mailweb34.rediffmail.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 11:17:46 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 10:17:46 -0500 Subject: How to find out if february has 29 or 28 days ? In-Reply-To: <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> (Marcus Vinicius Laranjeira's message of "Tue, 30 Jul 2002 12:08:59 -0300") References: <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> Message-ID: >>>>> "Marcus" == Marcus Vinicius Laranjeira writes: Marcus> I use the mx.DateTime package, and I need to know if in Marcus> one particular year has a february with 28 or 29 days ? I Marcus> don't know how to do that ! Here's one way.... import mx.DateTime def is_leapyear(year): try: d = mx.DateTime.DateTime(year,2,29) return 1 except mx.DateTime.mxDateTime.RangeError: return 0 print is_leapyear(2000) print is_leapyear(2002) From edream at tds.net Thu Jul 25 11:14:42 2002 From: edream at tds.net (Edward K. Ream) Date: Thu, 25 Jul 2002 15:14:42 GMT Subject: Speed up Python by up to 5% ? Message-ID: It may be possible to speed up the Python interpreter 3% to 5% with a trivial modification. When stripped of conditionals, the main loop of the Python 2.2.1 interpreter is as follows. (I've added comments to show C code equivalent to the expansions of the macros. Actual expansion may be slightly different.) [begin code] why = WHY_NOT; err = 0; w = NULL; x = Py_None; /* Not a reference, just anything non-NULL */ for (;;) { if (things_to_do || --tstate->ticker < 0) { /* handle periodic things */ } opcode = NEXTOP(); // opcode = *next_instr++ if (HAS_ARG(opcode)) // if (opcode >= HAVE_ARGUMENT) { oparg = NEXTARG(); // next_instr += 2; // oparg = ((next_instr[-1] << 8) + // next_instr[-2]) } switch (opcode) { /* opcode cases */ } if (why == WHY_NOT) if (err == 0 && x != NULL) continue; /* Normal, fast path */ } // end for [end code] BTW, many common cases end with "continue", so even the trailing code following the opcode switch doesn't necessarily contribute that much to program running time. In short, this is a very tight loop. But can't it be improved? The byte code is littered with SET_LINENO opcodes. Has anyone considered moving the test: if (things_to_do || --tstate->ticker < 0) { /* handle periodic things */ } // not usually executed. out of the main loop an into the case for SET_LINENO? The code might be executed slightly less regularly, but would that matter? This would seem to be a real improvement precisely because the main loop is already so tight. The only problem I can think of is that there would be some loop that does not involve any SET_LINENO opcode at all. Can anyone come up with such an example? Is there any other reason for moving the "periodic things" test out of the main loop? Even if there were places where a loop contains no SET_LINENO opcode, it might be worthwhile to have the compiler insert an DO_PERIODIC_THINGS opcode in the bytecode for the loop. How much time might we expect to save? Let us look at the most favorable case first. As it happens, the SET_LINENO case of the main loop takes about the _least_ amount of time to execute (on average) so the speedup relative to this case will be the _greatest_. Here is the code that typically gets executed: case SET_LINENO: f->f_lineno = oparg; if (tstate->c_tracefunc == NULL || tstate->tracing) continue; // typically _is_ executed. // typically _not_ executed. As a rough estimate, let us just count C instructions in the loop through this case: if (things_to_do || --tstate->ticker < 0) { /* typically not executed. */ } opcode = *next_instr++ if (opcode >= HAVE_ARGUMENT) { next_instr += 2; oparg = ((next_instr[-1] << 8) + next_instr[-2]) } switch (opcode) { case SET_LINENO: f->f_lineno = oparg; if (tstate->c_tracefunc == NULL || tstate->tracing) continue; // typically _is_ executed. // typically not executed. } Depending on how you count, there are 8-10 instruction here, so saving the line: if (things_to_do || --tstate->ticker < 0) might save up to 10% to 15% of the time through this loop. This is a very rough estimate, and the actual value may be less. Notice that code marked "typically not executed" has little effect on "amortized" time. Are typical opcodes much more expensive than the simplest SET_LINENO case? I wrote a simple program based on dis to count the static occurrences of bytecodes. The results of running this program on most of the modules of Leo are as follows: 18686 LOAD_FAST 14276 SET_LINENO 9635 LOAD_CONST 9555 POP_TOP 6721 LOAD_GLOBAL ** 5890 CALL_FUNCTION ** 5657 STORE_FAST 3957 JUMP_IF_FALSE 3473 RETURN_VALUE 2887 JUMP_FORWARD 2777 COMPARE_OP 2229 LOAD_ATTR ** 1109 INPLACE_ADD 887 BUILD_TUPLE 876 BINARY_SUBSCR 839 BINARY_ADD 818 POP_BLOCK 756 JUMP_IF_TRUE 730 JUMP_ABSOLUTE 729 SETUP_LOOP 283 UNARY_NOT ... total 96454 ** denotes "heavy hitter" Dynamic execution frequencies will not match these static frequencies exactly, but I see no reason to suppose they will be wildly different. If anyone has real dynamic data, I would like to see it :-) Typical "fast" opcodes are LOAD_FAST and LOAD_CONST. The code for them is as follows: case LOAD_FAST: x = GETLOCAL(oparg); // x = fastlocals[oparg] if (x == NULL) { // if (x == NULL) ... /* Typically not executed. */ } Py_INCREF(x); // x->ob_refcnt++ PUSH(x); // *stack_pointer++ = x if (x != NULL) continue; break; // Typically not executed. case LOAD_CONST: x = GETCONST(oparg); // x = f->f_code->co_consts->ob_item[oparg] Py_INCREF(x); // x->ob_refcnt++ PUSH(x); // *stack_pointer++ = x continue; Again we can see that eliminating: if (things_to_do || --tstate->ticker < 0) from the main loop might save up to 10% of the time taken to execute these instructions. Some opcodes _will_ take much longer than others to execute. I have marked the "heavy hitters" above with **. Suppose we say that the heavy hitters will take at least 10 times longer than the other opcodes to execute, so we shall add 10 times their total count to the total count of 95454 shown above. The new total then becomes roughly 300,000 rather than 100,000, so perhaps by this very rough estimate we might save 3-5% rather than 10-15%. Still, this might be a real savings. What do you think? Edward P.S. The code needed to execute the "periodic" tasks in the SET_LINENO case might be simpler than the code in the main loop, because we would execute the periodic tasks _every time_ the SET_LINENO is seen. The "do periodic things" code is: @ Doing this every time through the loop would add too much overhead, so we do it only every Nth instruction. We also do it if ``things_to_do'' is set, i.e. when an asynchronous event needs attention (e.g. a signal handler or async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. @c tstate->ticker = tstate->interp->checkinterval; if (things_to_do) { if (Py_MakePendingCalls() < 0) { why = WHY_EXCEPTION; goto on_error; } } #if !defined(HAVE_SIGNAL_H) || defined(macintosh) /* If we have true signals, the signal handler will call Py_AddPendingCall() so we don't have to call sigcheck(). On the Mac and DOS, alas, we have to call it. */ if (PyErr_CheckSignals()) { why = WHY_EXCEPTION; goto on_error; } #endif #ifdef WITH_THREAD if (interpreter_lock) { /* Give another thread a chance */ if (PyThreadState_Swap(NULL) != tstate) Py_FatalError("ceval: tstate mix-up"); PyThread_release_lock(interpreter_lock); /* Other threads may run now */ PyThread_acquire_lock(interpreter_lock, 1); if (PyThreadState_Swap(tstate) != NULL) Py_FatalError("ceval: orphan tstate"); } #endif It's not clear how expensive this code will be when executed. It depends on preprocessor options and run-time variables. Again, dynamic data would be helpful. E.K.R. -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From jdhunter at nitace.bsd.uchicago.edu Tue Jul 9 15:55:24 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 09 Jul 2002 14:55:24 -0500 Subject: New newbie question. References: Message-ID: >>>>> "SA" == SA writes: SA> Can you read a pdf with Python? I know you can read a text SA> file with: SA> Inp = open("textfile", "r") SA> Will the same thing work on pdf files: SA> Inp = open("pdffile", "rb") You can do this, but you'll get the binary If you are on a linux system, you may have pdftotext already installed, and can call that command from python with # Example usage: # python ~/python/examples/pdf_demo.py HunterEtal2000.pdf import os, sys filename = sys.argv[1] command = os.popen('pdftotext %s -' % filename) for line in command.readlines(): print line, You may want to have a look at these two python apps that for working with pdfs: http://www.reportlab.com/index.html - emphasis on pdf generation http://pdfsearch.sourceforge.net - search pdfs Cheers, John Hunter From jostein.berntsen at sensewave.com Wed Jul 24 08:33:09 2002 From: jostein.berntsen at sensewave.com (Jostein Berntsen) Date: Wed, 24 Jul 2002 14:33:09 +0200 Subject: Fwd: Re: good books Message-ID: <200207241433.09435.jostein.berntsen@sensewave.com> ---------- Forwarded Message ---------- Subject: Re: good books Date: Wed, 24 Jul 2002 13:45:06 +0200 From: Jostein Berntsen To: Percy Tambunan A book I have used much is this one: Python Essential Reference - David M. Beazley http://www.amazon.com/exec/obidos/ASIN/0735710910/qid=1027510682/sr=1-3/ref=s r_1_3/103-0614004-5992611 Nice and tidy and straight to the point. Regards, Jostein On Tuesday 23 July 2002 08:13, Percy Tambunan wrote: > what is a good book in python, If i can only afford to buy just one book? ------------------------------------------------------- From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 02:40:23 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 21 Jul 2002 23:40:23 -0700 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: <7xr8hwnu3s.fsf@ruckus.brouhaha.com> martin at v.loewis.de (Martin v. Loewis) writes: > You can put a callable object in sys.modules. Module objects > themselves are not callable. Is this documented somewhere? I don't see it in the obvious places. > > If there's not a way to do this already, maybe it's a reasonable > > addition. > > Maybe not. Why do you need this? Just to not have to say "foo.foo()" or "from foo import foo". If the main purpose of the module is to provide one function, I think it's cleaner to be able to import the module and call the function without special tricks. From johan at weknowthewayout.com Fri Jul 19 09:34:25 2002 From: johan at weknowthewayout.com (Johan Holst Nielsen) Date: Fri, 19 Jul 2002 15:34:25 +0200 Subject: PDF creating again! References: <3D37D1A9.1030909@weknowthewayout.com> Message-ID: <3D381561.8090405@weknowthewayout.com> >>interested in TKinter but I can ony use bitmaps font, and I need Type1 >>fonts at least (maybe other too). >> >>Isn't there any kinds of libraries that can do this for me? Output have >>to be PS or PDF... > > > http://www.reportlab.com/toolkit/index.html I have looked at T1Python with PIL? Anyone have any kind of experience with that? Else I will take a closer look at ReportLab Toolkit too :) -- Best Regards - Venlig hilsen Johan Holst Nielsen From marcoxa at cs.nyu.edu Fri Jul 12 14:22:00 2002 From: marcoxa at cs.nyu.edu (Marco Antoniotti) Date: 12 Jul 2002 14:22:00 -0400 Subject: Calling Python from Allegro Lisp References: <3D2EC4B5.1070605@thomas-guettler.de> Message-ID: Thomas Guettler writes: > Hi! > > I have an old application which needs to call python. > The old app is written in allegro lisp. > > I tried the following: > (defparameter hlib "c:\\winnt\\system32\\python22.dll") > (probe-file hlib) > (ct:defun-dll Py_Initialize() > :return-type :void > :library-name hlib > :entry-name "Py_Initialize") > (ct:defun-dll PyRun_SimpleString((s :char *)) > :return-type :long > :library-name hlib > :entry-name "PyRun_SimpleString") > > (Py_Initialize) > (setq foo "print 'foo'") > (PyRun_SimpleString (cref (ct:char *) foo 0)) > > But get: > """ > The first element (CREF (CHAR *) foo 0) of a function > application is not a function name > """ > Apart from what I said in my previous response, given ACL FFI interface manuals, you should be able to just say (PyRun_SimpleString "print 'foo'") Cheers -- Marco Antoniotti ======================================================== NYU Courant Bioinformatics Group tel. +1 - 212 - 998 3488 719 Broadway 12th Floor fax +1 - 212 - 995 4122 New York, NY 10003, USA http://bioinformatics.cat.nyu.edu "Hello New York! We'll do what we can!" Bill Murray in `Ghostbusters'. From coventry at one.net Mon Jul 1 00:02:50 2002 From: coventry at one.net (- c o v e n t r y -) Date: 30 Jun 2002 21:02:50 -0700 Subject: old thread: SSL support for socket module for server sockets Message-ID: I was reviewing the archives and ran accross this patch submited for python 2.0, but too late to make it in... Is there a way to create a SSL server socket in 2.2, or did this slip through the cracks? >>> I don't think anybody has posted a patch for this, so I will. The SSL support in the socket module doesn't support server sockets (ones where you call s.accept() on them). This patch creates a function in the socket module named sslserv which is analogous to the ssl function except this one will work for server sockets. *** /home/drew/build/Python-2.0b1/Modules/socketmodule.c Wed Aug 16 10:18:30 2000 --- socketmodule.c Fri Sep 22 16:25:24 2000 *************** *** 2045,2048 **** --- 2045,2131 ---- } [[SNIP]] <<< From 102030405 at gmx.net Thu Jul 11 15:01:53 2002 From: 102030405 at gmx.net (Ralf Claus) Date: Thu, 11 Jul 2002 21:01:53 +0200 Subject: html login with python? Message-ID: Hello, my Problem : to check out the onlinestatus of my router, i need a script to login into the webinterface of my router. How can i automatically log in. Sorry, i hope you understand the problem From tjreedy at udel.edu Tue Jul 2 12:14:51 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Jul 2002 16:14:51 GMT Subject: Performance question about math operations References: Message-ID: <%jkU8.242612$_j6.12052578@bin3.nnrp.aus1.giganews.com> "Andrew P. Lentvorski" wrote in message news:mailman.1025589663.1583.python-list at python.org... > I have a VLSI layout editor written in Python. At its core, it has to > redraw a lot of polygons. This requires a lot of coordinate conversion > mathematics. Essentially the following loop: ... > That's about a factor of 30 (1.5 / .05) difference even if I cancel out > the loop overhead. I could handle factor of 2 or 4, but 30 seems a bit > high. > > What is eating all that time? Among other things, boxing and unboxing the floating point numbers (as PyObjects) and determining that +-*/ are floating point operations rather than anything else. > And can I do anything about it? Use numerical Python extensions which works with arrays of unboxed floats and which only has to interprete +-*/ once each for entire array and then calls c code for entire array. Or check out SciPy which includes numPy and more. Or even PyGame which interfaces to c-coded transforms and which would aid graphical display of layout. Terry J. Reedy From mfranklin1 at gatwick.westerngeco.slb.com Fri Jul 12 12:28:02 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 12 Jul 2002 16:28:02 +0000 Subject: tk/tkinter radiobutton in grid bug? In-Reply-To: <3D2EF186.4CB25463@tds.net> References: <3D2EF186.4CB25463@tds.net> Message-ID: <200207121531.g6CFVn717110@helios.gatwick.geco-prakla.slb.com> On Friday 12 Jul 2002 3:11 pm, Edward K. Ream wrote: > Hi, > > If b is a radiobutton, b.select() (b -select) does not work when b is > embedded in a grid, and works just fine when packed. In either case, > the radio buttons work, but in the grid case the proper button is not > initially selected. None of the various alternatives to b.select work > either. > > Is this a known bug? I have a dim memory of this being discussed > somewhere...Does anyone know a workaround that still uses grids (I'd > like to embed the radiobuttons in a labeled frame, and grids are the > only way I know to do that.) > Edward, This _seems_ to work do you have an example that does not? import Tkinter root=Tkinter.Tk() variable=Tkinter.StringVar() l=Tkinter.Label(root, text='On or Off?').grid(row=0, col=0) rb1=Tkinter. Radiobutton(root, variable=variable, value='On', text='On') rb1.grid(row=0, col=1) rb2=Tkinter. Radiobutton(root, variable=variable, value='Off', text='Off') rb2.grid(row=0, col=2) rb2.select() root.mainloop() Regards Martin From max at alcyone.com Fri Jul 5 05:40:42 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 05 Jul 2002 02:40:42 -0700 Subject: Why self? References: Message-ID: <3D25699A.679B0404@alcyone.com> Jesper Olsen wrote: > Why is it necessary to use a "self" argument to class methods in > python? > > To me it seems a bit like doing object oriented programming in C... > > Why not make it implicit like "this" in C++? Explicit is better than implicit. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From aleax at aleax.it Wed Jul 24 13:33:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 17:33:03 GMT Subject: Numeric data question References: <%Nz%8.15893$A72.86385@news1.mts.net> Message-ID: terry wrote: ... > I'm guessing now (from lack of real experience) that being a > 'typeless' language that I would be forced into contriving a > method for handling money such that I could never code something > straightforwardly like: > TotalCost = Quantity * UnitCost > (where Quantity is integer and the others money). If you were working with a typeless language, that might be the case. Fortunately, Python is strongly typed, so that's no problem, of course. This statement would probably be equivalent to something like: TotalCost = type(UnitCost).__rmul__(Quantity( for example (or UnitCost.__class__.__rmul__ if UnitCost was an instance of an old-fashioned class, but that comes to much the same thing). Just code your __rmul__ (and __mul__, etc) methods and voila, whatever numeric type you want is there. http://starship.python.net/crew/aahz/Decimal.py is an example, though Aahz still doesn't consider it finished. > Am I loonie, or is Python just not inherently suitable for > accounting applications for this reason? If you're saying that Python is "typeless", then I guess "loonie" might be applicable, yes. Alex From hancock at anansispaceworks.com Mon Jul 22 09:35:29 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 22 Jul 2002 06:35:29 -0700 Subject: calendar lameness! Message-ID: <3D3C0A21.1EB8A671@anansispaceworks.com> I was shopping around the Python standard library for interesting modules to incorporate in future projects. (Got to test the batteries before you can use 'em). "calendar" is pretty neat -- except it has pretty annoying arbitrary limits on the date: 1900-1/1 to 2038-1/18 I can see that this is adequate for a business planner, but for historical or astronomical uses, it's really inadequate. (e.g. "What day of the week was the US Declaration of Independence signed on?" I'm sure I could look that up, but gee it would've been nice to just type: calendar.weekday(1776, 7, 4) ). It's less useful to get: calendar.prmonth(2153, 9) unless of course, you're an SF writer, and you want to be accurate. Anyway, I'll be pretty old in 2038, but hopefully not dead. This is Python 2.1. Anyway -- any chance these got fixed in a later release? Why the range? Is this some kind of overflow problem? Actually, it looks like maybe it's "mktime" that is the limiter here (?). How hard would it be to replace that call with something smarter? It seems like Python longs would make it unnecessary to have such arbitrary limits. Thanks, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From heikowu at ceosg.de Mon Jul 29 12:42:20 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 29 Jul 2002 18:42:20 +0200 Subject: PythonCard question Message-ID: <1027960941.2946.5694.camel@d168.stw.stud.uni-saarland.de> Hi people! I'm happily using PythonCard to develop a configuration framework for my web application server. Funny thing happening though: I've derived a class from CustomDialog (no, I haven't given it buttons with ID 5100 and 5101, and I don't want to!), and now when one button is pressed, I'm trying to close the window, but the code raises the exception that CustomDialog.close() doesn't exist. (My class doesn't implement it anyway :)). In the samples that are provided, they always use 5100 as the button ID of the OK button, and I presume that this ID will close the dialog automatically... Anybody know of a quick solution to this instead of giving the OK button the ID 5100? Yours, Heiko W. From tjreedy at udel.edu Fri Jul 26 11:54:17 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Jul 2002 15:54:17 GMT Subject: extract elements of n char from a list References: Message-ID: "Shagshag13" wrote in message news:ahrchl$v4n9l$1 at ID-146704.news.dfncis.de... > i want to efficiently extract elements of n char from a list : ... > but i think that some clever guru could use a map() / reduce() or something like that to speed up the process (which is what i really need...) You are looking for pass_list = filter(predicate, candidate_list) # equivalent and maybe faster (test) to pass_list = [item for item in candidate_list if predicate(item)] >>> l = ['this', 'is', 'an', 'example'] >>> nl=filter(lambda i: len(i) == 2, l) >>> nl ['is', 'an'] Terry J. Reedy From claxtonr at beer.com Wed Jul 17 12:36:57 2002 From: claxtonr at beer.com (hejduk) Date: Wed, 17 Jul 2002 12:36:57 -0400 Subject: starting other programs from within python References: <20020716.171155.619290071.333@beer.com> <3D349AA0.1AE34452@engcorp.com> Message-ID: <20020717.123645.824272813.337@beer.com> In article <3D349AA0.1AE34452 at engcorp.com>, "Peter Hansen" wrote: > hejduk wrote: >> >> However, when I monitor the memory usage of the interpreter it appears >> that when this outside application is closed that not all the memory >> resource is returned, ie: >> >> before: 7248 k >> during: 18624 k >> after: 12284 k > > Analysing memory usage like this with a single run is never a good idea. > Run it multiple times (start, exit, start, exit) and monitor the usage. > You may find that it "settles out" after two times and does not, in > fact, leak resources. You may also find it climbs and falls in a cycle, > which is one of several possible effects you might see, since the > operating system is probably doing an awful lot of sophisticated stuff > you aren't even noticing. > > In any event, you didn't mention a number of important facts, like what > operating system you are using, how you are monitoring memory usage, > what version of Python you have, and so on. Without that it may be > difficult to draw any useful conclusions. > > -Peter I'm using python 2.2, on slak linux using gnome, and i'm monitoring the memory usage with gtop. my main concern really is whether i'm starting the processes in the right manner. would spawnv or something else be better? i'm new to threads so i don't know whether they need to be stopped manually or whether they'll shut down automatically. From robert_kuzelj at yahoo.com Thu Jul 4 03:40:30 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 4 Jul 2002 00:40:30 -0700 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: > What is implicit about it? It is explicitly saying "if it's a new-style > class or an old-style class". it is implicit cause i dont want to ask what kind of class that is but if it is an instance. that is is is it an object created by an instantiation-action (aka x = X()) this is very clearly distinglishable im my code from creating a class-object (class X:...). anyway i think we should stop this thread. nobody else seems to be bothered by this except for me and there is a workaround (that i dont like but do not have to) ciao robertj From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 11:49:40 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 10:49:40 -0500 Subject: how to ask google, altavista or another search engine... References: Message-ID: >>>>> "Shagshag13" == Shagshag13 writes: Shagshag13> hello, i'm looking for a python script able to ask to Shagshag13> a web search engine (google, altavista or another Shagshag13> search engine) and/or able to parse a result page. Shagshag13> any other helps / advices / urls are welcome... Shagshag13> thanks in advance, Shagshag13> s13. If you register (free) with google at http://www.google.com/apis/ you can use pygoogle http://diveintomark.org/projects/#pygoogle Here's a simple example script (add your own license key) import google # Get your own from http://www.google.com/apis/ google.LICENSE_KEY = 'youRliCenseKEYHere' data = google.doGoogleSearch('python') # Search time #print data.meta.searchTime # Meta attributes #print dir(data.meta) print 'Found %d results' % len(data.results) for result in data.results: print 'Title: ', result.title print 'URL: ', result.URL print 'Summary: ', result.snippet print # Result attributes #print dir(result) # Spelling suggestion: #print google.doSpellingSuggestion('pithon') From daskalious at softhome.net Mon Jul 1 11:09:07 2002 From: daskalious at softhome.net (Andreas Daskalopoulos) Date: 01 Jul 2002 18:09:07 +0300 Subject: python + simple graphics (lines, circles etc.) Message-ID: What modules are avalaible for drawing simple things like lines, circles etc.? I searched the documentation for a module but i didnt find something. Thank you for reading my article. From phr-n2002b at NOSPAMnightsong.com Wed Jul 17 21:32:10 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 17 Jul 2002 18:32:10 -0700 Subject: socket.gethostbyaddr() is slower than Christmas References: Message-ID: <7xlm89u8h1.fsf@ruckus.brouhaha.com> That sounds similar to something that happens with Emacs on some systems. >From the Emacs PROBLEMS file: ================================================================ * Slow startup on Linux-based GNU systems. People using systems based on the Linux kernel sometimes report that startup takes 10 to 15 seconds longer than `usual'. This is because Emacs looks up the host name when it starts. Normally, this takes negligible time; the extra delay is due to improper system configuration. This problem can occur for both networked and non-networked machines. Here is how to fix the configuration. It requires being root. ** Networked Case First, make sure the files `/etc/hosts' and `/etc/host.conf' both exist. The first line in the `/etc/hosts' file should look like this (replace HOSTNAME with your host name): 127.0.0.1 HOSTNAME Also make sure that the `/etc/host.conf' files contains the following lines: order hosts, bind multi on Any changes, permanent and temporary, to the host name should be indicated in the `/etc/hosts' file, since it acts a limited local database of addresses and names (e.g., some SLIP connections dynamically allocate ip addresses). ** Non-Networked Case The solution described in the networked case applies here as well. However, if you never intend to network your machine, you can use a simpler solution: create an empty `/etc/host.conf' file. The command `touch /etc/host.conf' suffices to create the file. The `/etc/hosts' file is not necessary with this approach. From ianb at colorstudy.com Mon Jul 15 17:46:58 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 15 Jul 2002 16:46:58 -0500 Subject: "Tickets" and XML-RPC authentication In-Reply-To: References: <0FiY8.16023$p56.5181944@newsb.telia.net> Message-ID: <1026769619.701.327.camel@lothlorien.colorstudy.net> On Mon, 2002-07-15 at 16:05, Magnus Lie Hetland wrote: > As for attackers listening in -- I guess you mean that I might want to > have one secure (ssl) login-call, and then do the rest in the open? > I'm not completely sure why I then wouldn't want to wrapp it all in a > secure connection... If you wanted to transfer a large bit of content, or do lots of small transactions, the overhead of SSL could be significant (maybe). XMLRPC requires encoding that already makes it less efficient for transferring large amounts of content, so that's probably not worth it (or you'd want to ditch XMLRPC entirely for traditional HTTP). So it's probably just in case of a very chatty situation where you might want to avoid SSL overhead -- my understanding is that SSL adds a significant amount of latency to a connection. If, for instance, you had an interactive UI where you didn't want to do caching (e.g., the site was being updated very actively), then SSL might be a problem (unless both sides supported keep-alive connections, which might be the best solution). -- Ian Bicking Colorstudy Web Development ianb at colorstudy.com http://www.colorstudy.com 4869 N Talman Ave, Chicago, IL 60625 / (773) 275-7241 From gcordova at hebmex.com Wed Jul 3 15:27:57 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 3 Jul 2002 14:27:57 -0500 Subject: Creating Subclassable Objects?? Message-ID: > > I've been trying to 'update' some extension objects for my > python modules. I couldn't find any documentation on this, > so I've been trying to follow along from the other object > sources inside python. > > At this point you are able to subclass the objects, the > problem is they just don't work. If my new class has an > __init__ method, it seems i cannot properly instance the > objects (since it needs some args). If i don't have > an __init__ method, i can instance the new class, but none > of the new methods i add to it work (AttributeError). > > Anywhere I can look to get all the steps in place? > Well, "a little bit of source-code help's the messages go down" like the flying lady (Mary Poppins) said. Without code, we can't know what you mean. You *could* do some things like, say, you wanna add this method to your functions: >>> def SomeMethod(self, one, two, three): print one, two, three, id(self) (hey, it's just an example). So, you could do: self.__class__.MethodName = SomeMethod and presto, "self" has access to a new method called "MethodName", which references the function "SomeMethod". You could also create a new bound method, with: import new self.MethodName = new.instancemethod(SomeMethod, self, self.__class__) and presto, you have a new bound method. Good luck. -gustavo From loewis at informatik.hu-berlin.de Wed Jul 17 07:56:01 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Jul 2002 13:56:01 +0200 Subject: string encoding - how to make it work References: Message-ID: "Henry Baumgartl" writes: > Is there a way, using standard string methods, to write code that will > always generate the same output? No. You have to know what encoding the terminal uses. Some terminals have no programmatic way to find out. So this isn't just possible in Python; it is impossible in any language. Regards, Martin From marklists at mceahern.com Tue Jul 23 10:10:52 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 23 Jul 2002 09:10:52 -0500 Subject: Multikey dictionary In-Reply-To: <3d3d596e.357860250@news.skynet.be> Message-ID: > What datatypes can one use as key in a dictionary? Look here for __hash__--that might help: http://www.python.org/doc/current/ref/customization.html > Can I use for example two longs as key (kind of a double key)? If you want to keep it simple, why not just use a tuple? d = {} d[(1,2)] = "foo" // mark - From aleax at aleax.it Fri Jul 26 04:15:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 08:15:54 GMT Subject: Numeric data question References: Message-ID: <_y709.121243$Jj7.2823038@news1.tin.it> James J. Besemer wrote: ... > E.g., in the stock market, 1/8 "point" is $0.125. Also you quickly run > into scale problems with non-US currencies, e.g., 2 billion Lira is too > harsh an upper limit. (My last hotel bill in Venice was over L > 1.000.000). Not a problem any more since Jan 1. Unless you travel to Turkey, obviously, where a million (Turkish) liras will NOT buy you a night at a hotel, even though it's a cheap (and wonderful) country. > Basically 12 pennies to the shilling, and 20 shillings to the pound, or > 240 pennies per pound. THAT was when money was worth something, when you > minted coins worth 1/16 of a cent or 1/3840th of your basic monetary > unit! A pound was originally a pound (roughly half a kilogram; same for 'lira', coming from 'libra', meaning 'scales' and also 'a pound') of SILVER -- hardly a "basic monetary unit", more like an accounting abstraction. Starting from roughly equal valuations in the 8th/9th century (wherever Charlemagne reigned, plus places, such as Britain, where he didn't but his writ still had prestige), currency then underwent wild gyrations, best narrated imho in the works of Carlo Cipolla (mostly in English, don't worry -- although Italian, he taught in the US for most of his career). Inflation was slow and sluggish in Britain (mostly because, as Cipolla shows, British economy was in turn dormant and deeply feudal), up to wild and furious in the booming Italian merchant-republics (exactly because their centuries-long mercantile boom demanded far more currency than the then-limited supplies of species could satisfy). Then of course the whole system was forever uprooted in the 16th century as unprecedented amounts of gold and silver flowed into Europe (outpacing for the first and only time the growth rate of the real underlying economies). It IS a tribute to Charlemagne's lasting influence on Europe that his "pound", "lira" or "livre" still remained at least in name (and in some cases in the classic 1:20:12 ratios, at least in Britain) despite all of these turmoils (French noblemen still accounted their rents in "livres" to the late 18th century, even if no currency of that name had been minted for many centuries). But of course the whole field of numismatics is chock full of such fascinating fossils -- starting from "money" itself (and its counterparts "moneta", "monnaie") from the attribute of Goddess Juno Moneta (Juno the Warning-giver -- the famous sacred geese were apparently in Juno's temple) in whose temple the Roman Republic's mint (same root) was established in the 3rd century BC. -- all the way to "dollar" with its strange connection to Joachimstal (today called J?chymov)... Alex From aleax at aleax.it Sat Jul 20 03:44:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 07:44:27 GMT Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: Justin Shaw wrote: >> Basicely I have two lists, one containing the future string-names >> and one containing the values I want to give them. The order is >> identical in both. Right now I'm solving this by a dictionary, but >> I would really prefer to have straight strings as a result of my >> operation. > > I like the idea of keeping your namespace clean. But if what you really > want is to assign the values to your local namespace I have two solutions. > > 1. Ugly one-liner > eval ';'.join(['='.join(x) for x in zip(names, [str(v) for v in values])]) Can't work -- eval only works on expressions, not statements. I guess you mean exec (shudder). > 2. Update locals() > locals().update(dict(zip(names,values))) Wont' work in typical functions -- treat locals() as read-only, mods to it won't necessarily "take" anyway. I'd like locals() to return a R/O dict proxy -- errors should not pass silently, and this one definitely IS an error. Working on a dict is BY FAR the best idea, cleanest and fastest. If the OP is truly intent on damaging code quality while making performance substantially worse, something like your first suggestion with exec in instead of eval might work (you probably want to s/str/repr/ too). *shudder*. The lengths to which people will go seeking self-destruction...!-( Alex From loewis at informatik.hu-berlin.de Tue Jul 30 04:58:59 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2002 10:58:59 +0200 Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 References: Message-ID: sdrake at knology.net (Steve Drake) writes: > I am having a problem using PyXML with tutorial code that I got at > http://www.ibm.com/developerWorks. Although this code works on > Windows with python-2.2.1, and works on RH 7.3 with python-1.5.2, I > get an error when attempting to use python-2.2.1 on RH 7.3. I tried > installing python-2.2.1 and PyXML-0.7.1 from source, but I get the > same error as when using rpm packages. Please install from sources, and make sure that the pyexpat extension is built; do so by adding --with-pyexpat to the setup.py command line. Then double-check that it it is really build - you need to find pyexpat.so in your build directory. Reinstall, then retry your test. It is a bug in PyXML 0.7.1 that setup.py won't build pypexpat when it should. Regards, Martin From cliechti at gmx.net Sat Jul 20 10:35:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jul 2002 16:35:01 +0200 Subject: Lists & two dimensions References: Message-ID: "Duncan Smith" wrote in news:ahbqkn$gn3$1 at newsg1.svr.pol.co.uk: >>>> b = [[-1] * 3 ] >>>> b > [[-1, -1, -1]] # a list containing a list >>>> b * 3 > [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]] > or better: b = [[-1]*3 for i in range(3)] otherwise the 3 lists are references to a single list and when you modify one, the other two change too (as they are one list...) anyway for a flat list of 9 elements i would use b = [-1]*(3*3) chris -- Chris From johnboik at sbcglobal.net Tue Jul 2 15:54:53 2002 From: johnboik at sbcglobal.net (John Boik) Date: Tue, 02 Jul 2002 19:54:53 GMT Subject: newbie question on Fredrik Lundh's simple script Message-ID: Hello. I am new to Python and Tkinter and was trying out the Fredrik Lundh scripts from "An Introduction to Tkinter", and ran across a problem. BTW, I am running the latest version of Python on a windows XP system. His simple Hello2.py script does not act as it should on my machine, I think. The script is: # File: hello2.py from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() Here is the problem. The frame pops up OK, but when I press the Quit button nothing happens. When I press it twice, Python shuts down. According to the script (command=frame.quit), the Quit button is only supposed to close the frame, not shut down Python. Any ideas on what may be happening? Thanks. John From eric.brunel at pragmadev.com Fri Jul 19 03:36:03 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 19 Jul 2002 07:36:03 +0000 Subject: Tkinter vs. wxPython References: Message-ID: Darrell wrote: [snip] > PMW which wraps Tkinter seems impossible to wrap as an exe. Pmw can be wrapped into an exe. It's a bit complicated since Pmw natively uses dynamic loading, but it's possible (I've done it). See: http://pmw.sourceforge.net/doc/dynamicloader.html paragraph "Freezing Pmw" HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From pinard at iro.umontreal.ca Sun Jul 28 10:11:18 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 28 Jul 2002 10:11:18 -0400 Subject: How to detect the last element in a for loop In-Reply-To: <49S09.13011$9U4.7618@nwrddc01.gnilink.net> References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: [Tom Verbeure] > > For a simple solution, how about: > > > > for a in myList[:-1]: > > do_stuff(a) > > special_stuff(myList[-1]) > No, I still want to do 'do_stuff' for the last element also. This may be, > say, 10 lines of code. Too much to duplicate it outside the loop, not > enough for a separate function... I did not follow this thread, I may be missing something, but why not: for a in myList: do_stuff(a) special_stuff(a) taking advantage on the fact that `a' keeps the last value it received? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From max at alcyone.com Tue Jul 2 20:28:59 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 02 Jul 2002 17:28:59 -0700 Subject: creating a file from python References: Message-ID: <3D22454B.ECAD5327@alcyone.com> gollem wrote: > I want to create a file from inside a running python script. > I can do that using commands and touch but it won't work if the > intended > name of the file is the value of a python variable. The file is > created as > the variable name instead of the variable value. Why not open(fileName, 'w').close() ? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From janeaustine50 at hotmail.com Thu Jul 25 16:03:50 2002 From: janeaustine50 at hotmail.com (Jane Austine) Date: 25 Jul 2002 13:03:50 -0700 Subject: [Re] euid/egid eaten up by os.popen Message-ID: >I bet you're running Linux. My suggestion is to try popen2, and Yes, Red Hat 7.3 >specify the command as a list of arguments. For example, if you >have been writing > fp = os.popen('id') >then try > fp, ignore = popen2.popen2(['id']) Have done that and it didn't work still. > >The same goes for system(), incidentally - spawnv() will work better. > >The problem is evidently caused by bash. If you contrive to run >bash to interpret the command string on some other platform, it >will happen the same way - it's only a Linux bug because Linux uses >bash here. > >Donn Cave, donn at u.washington.edu It seems like when popen forks for a new shell, euid is all cleared. From dkuhlman at rexx.com Wed Jul 3 17:18:15 2002 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 03 Jul 2002 14:18:15 -0700 Subject: GoTo considered missing References: Message-ID: David LeBlanc wrote: >> >> OK. I'm a spaghetti-coder from way back, new to Python. >> I didn't even realize there was no "goto" till I tried to rewrite >> a big C program in Python. >> [snip] > > Care to share what you're working on? It might be that you're > using "basic think" and not considering Python's advanced > features. > Right. And, the *really* lazy among us would wrap that sucker with SWIG, declare victory, and go home. Seriously, one of the important features of Python is that we can turn C and C++ code into modules that can be imported by Python. Advantages are (1) avoid debugging by reusing code that is already debugged, (2) retain the speed of C/C++ code, (3) avoid a laborious and error prone re-write. OK, you already new all that. But, it good to remind ourselves, especially in the face of someone who is re-writing C code. Why is the OP re-writing that C code? As a learning excercise, perhaps. If not, then hand-coded or SWIG generated wrappers are something that should be considered. - Dave -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman From tim.one at comcast.net Mon Jul 22 14:44:53 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 22 Jul 2002 14:44:53 -0400 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: <6qy9c339oe.fsf@abnoba.intevation.de> Message-ID: [Anders J. Munch] > Python uses floating point to check for integer arithmetic overflow. [Bernhard Herzog] > Not any more. This change was introduced in 2.1 IIRC. This is complicated. First, scratch "integer arithmetic overflow", because it's too broad. Only integer multiplication is relevant here. Python used to use float arithmetic to detect int mult overflow, but that didn't work correctly on some 64-bit boxes. It got replaced by over 100(!) lines of all-integer int mult overflow-checking code, and I believe that's still in 2.1.3. But that had an obscure endcase bug too, and it get replaced in 2.2 by a new float method that doesn't make unwarranted assumptions about the relative sizes of C longs and C doubles, and usually gets out quickly -- provided float arithmetic isn't pig slow. And that's where things stand in current CVS Python too. From gtalvola at nameconnector.com Mon Jul 15 18:45:02 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Mon, 15 Jul 2002 18:45:02 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty Message-ID: <61957B071FF421419E567A28A45C7FE514A5C3@MAILBOX.nameconnector.com> Queue doesn't seem to support the operation "if the queue is empty, raise the Empty exception, otherwise remove and return an item from the queue". There is Queue.get_nowait but unfortunately, that sometimes raises the Empty exception even if the Queue is not empty. Sure smells like a bug to me, but this topic has come up before and Tim Peters sort of declared that it was the way it's supposed to work: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=ddd2f958ddd08f95&rnum= 2 Leaving aside the question of whether this is reasonable behavior, suppose that I actually did want the behavior I described above -- a reliable "if the queue is empty, raise the Empty exception, otherwise remove and return an item from the queue". How would I write it? Do I need to busy-loop like this (untested): def get_nowait_reliable(self): while 1: try: return self.get_nowait() except Empty: # Let's see if it's really empty. If not, try again. if self.empty(): raise or is there a better way? - Geoff From skip at pobox.com Fri Jul 26 17:11:30 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Jul 2002 16:11:30 -0500 Subject: ?Module re documentation bug, error, or misunderstanding? In-Reply-To: <3D41B265.AD56FF90@email.sps.mot.com> References: <3D41B265.AD56FF90@email.sps.mot.com> Message-ID: <15681.47874.446657.686812@12-248-11-90.client.attbi.com> Norman> So, what am I missing below as both searches "should" succeed? "r". >>> import re >>> re.search("(.+) \1", '55 55') >>> re.search(r"(.+) \1", '55 55') <_sre.SRE_Match object at 0x402665a0> -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From opengeometry at NOSPAM.yahoo.ca Sun Jul 7 23:11:08 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 8 Jul 2002 03:11:08 GMT Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > William Park writes: >> > http://www.nightsong.com/phr/python/setclock.py >> > >> > I find it pretty useful for adjusting my computer clock every >> > now and then, without the hassle of setting up a real NTP system. >> >> Thanks for the pointer, Paul. Exactly what I needed. Do you know any pure >> shell script that does the same thing? I don't have Python installed on >> every machine. > > I don't know about shell but it should be simple to write the same > thing in Perl or even in C. I've found a partial solution. I'm now using, ntpdate time.apple.com time.windows.com time.nrc.ca ntp1.cmc.ec.gc.ca where 'ntpdate' comes from NTP package. Still, shell solution would be desireable, because I sometime don't have access to Perl, Python, or NTP packages. But, I do have access to shell all the time. I'll update when I find solution. :) -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From aleax at aleax.it Wed Jul 24 04:12:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:12:10 GMT Subject: passing a tuple of floats to C++ References: <3D3D761B.7925CC36@mill.co.uk> Message-ID: Joe Connellan wrote: > How would I go about passing a tuple of floats of an arbitrary (but > large) size to C++ - would I use PyArg_ParseTuple()? Fastest and most general is to start with: PyObject* seq = PySequence_Fast(thetuple, "ain't a sequence!") which gives you the same object as thetuple when thetuple is indeed a tuple, or list, but also lets you pass other sequences and then converts them to lists internally. After this, seq will be NULL if thetuple was not a sequence, so the next statement should be: if(!seq) return 0; to propagate the exception. Once you do have seq, use the macros PySequence_Fast_GET_SIZE to get its length (so you know how large a C++ std::vector to make -- not crucial, but .reserve()ing the right size DOES make things much faster!) and loop using another macro, PySequence_Fast_GET_ITEM, to access the items and put them into the std::vector. Remember to decref seq when done! Not sure if this is documented in the Python docs -- it IS well documented in Include/abstract.h in the source distribution (not a few things regarding the C API's are only documented in the sources -- not sure if this is one of them -- anyway, you DO want to skim the Python sources for instruction and examples if you're at all serious about interfacing Python with C & the like). Alex From syver-en+usenet at online.no Sun Jul 28 18:15:05 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sun, 28 Jul 2002 22:15:05 GMT Subject: pythoncom from jython References: <46585325.0207080040.1ac2fffd@posting.google.com> <46585325.0207090228.7b5fc9e2@posting.google.com> <155dc67d.0207230957.69ff0ed8@posting.google.com> Message-ID: daniel.hughes at usa.net (Dan) writes: > Check out "Jacob" Java/COM Bridge. > > It's free. > > http://danadler.com/jacob/ I've made a very simple python wrapper round both the jawingen and jacob Java/COM bridges, it's nowhere as complete as win32com is but it might be worth a look. If anybody are interested I will make it available for download. -- Vennlig hilsen Syver Enstad From max at alcyone.com Thu Jul 18 19:28:13 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 Jul 2002 16:28:13 -0700 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <3D374F0D.99974221@alcyone.com> OtisUsenet wrote: > Python newbie question. How does one do something like this in > Python: > > # assign the value of j to i and then increment j by 1 > i = j++ That should be i = j j += 1 # or: j = j + 1 (Ignore my previous message, wasn't thinking.) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From aleax at aleax.it Mon Jul 22 01:58:02 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Jul 2002 05:58:02 GMT Subject: A better self References: Message-ID: Delaney, Timothy wrote: >> From: Alex Martelli [mailto:aleax at aleax.it] >> >> The point is that SelferMeta.__new__ gets to look at all of >> class Myself's dictionary *and tamper with it as needed* before >> delegating the rest to class type. Specifically, it would get ... > Wouldn't work in Jython ... (when Jython gets to 2.2 ...). Or more precisely: the bytecode manipulations needed will be specific to the underlying virtual machine. I.e., unless a VM is designed in really crazy ways, it will probably be possible to use exactly the same technique (metaclass computing what bytecode is needed to achieve the desired results and substituting it in place of the bytecode as given), but the details of the transformations will change. Source-to-source transformations would be more general, but getting at the relevant sources is not trivial. When Python is run with -O you lose the line-numbers; when it's run with -OO you even lose the docstrings, so hiding semantically crucial info there is not fully kosher either. Unfortunately, the metaclass gets ahold of things only AFTER the class body is done. I suspect the only techniques that would let you use the same metaclass independently of underlying VM and runtime options are those that boil down to putting the source in string attributes of the class object, e.g.: class Selfish(SourceSelfer): __slots__ = "x y z".split() amethod = """(t, u, v): return x*t + u*y + z*v """ Alex From baf at texas.net Thu Jul 4 08:20:28 2002 From: baf at texas.net (Ben Fairbank) Date: Thu, 04 Jul 2002 12:20:28 GMT Subject: [Newbie] How to output dictionary sorted on content (not keys) Message-ID: <3d243af0.465960@news.texas.net> I have several long (thousands of entries) dictionaries of words used in plays; associated with each word is the number of times it is used in the play. I have had no problem printing the words alphabetically (send keys to a list, sort the list, access dictionary by the sorted key list), but I have not found an elegant way to sort by frequency of use. The best I have been able to do is a workable but inelegant kluge that looks more like Basic than Python. Is there a "Python Way" of doing that? Thanks for any ideas. BAF From ld at nospam.com Mon Jul 8 18:57:24 2002 From: ld at nospam.com (Larry) Date: Mon, 08 Jul 2002 22:57:24 GMT Subject: Clean Exit from Socket/Program Message-ID: Hi: I have a program running where data is being continuously fed into a socket connection. It seems when I exit the program (control c from keyboard), I lose a lot of the data that was in the socket buffer. I know this is the wrong way to shut down...but right now, I know no other way. I am used to VB where when I shut down a program from a form, my unload event triggers and I can clean up. I am fairly new to python, and I am not sure how to trigger a shutdown signal which would then allow my program to catch up and clean up before exiting. Can anyone give me some tips on... 1. How to shut down a python program cleanly 2. How to ensure that my socket buffer is empty before closing. Thanks, Larry From python at dohao.org Thu Jul 11 21:31:34 2002 From: python at dohao.org (Wenshan Du) Date: 11 Jul 2002 18:31:34 -0700 Subject: supplement Message-ID: It comes from the IDLE of Python 2.2.1 Fulltext search was supported. From fperez528 at yahoo.com Tue Jul 9 12:55:19 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 09 Jul 2002 10:55:19 -0600 Subject: leastSquaresFit References: Message-ID: Alex Tournier wrote: > >>>> # The data to be fitted to. > ... data = [(100, 4.999e-8), > ...?????(200,?5.307e+2), > ...?????(300,?1.289e+6), > ...?????(400,?6.559e+7)] > this is a list of tuples, not an array. Many numeric functions _do not_ implicitly convert lists to arrays (though some can operate on lists as well as arrays). Try data = Numeric.array(data) and see what happens. f From max at alcyone.com Wed Jul 17 02:27:50 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 16 Jul 2002 23:27:50 -0700 Subject: simultaneous iteration of lists References: Message-ID: <3D350E66.F62691F0@alcyone.com> Dave Harrison wrote: > Looking for advice on simultaneous iteration of two lists. > > I have two lists of equal length (guaranteed) , and I want to iterated > over both at the same time without having to write myself a little > counter thingo cause it seems slightly unpythonic. This is what zip is for: for i, j in zip(l, m): ... -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From whisper at oz.net Thu Jul 18 14:38:55 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 18 Jul 2002 11:38:55 -0700 Subject: [Announce] Gnosis (XML) Utils 1.0.3 In-Reply-To: <20020718172419.GB2112@lilith.my-fqdn.de> Message-ID: WFM David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Gerhard Haring > Sent: Thursday, July 18, 2002 10:24 > To: Pythonistas > Subject: Re: [Announce] Gnosis (XML) Utils 1.0.3 > > > * David Mertz, Ph.D. [2002-07-18 13:08 -0400]: > > It may be obtained at: > > http://gnosis.cx/download/Gnosis_Utils-1.0.3.tar.gz > > 404 > > > The current release is always available as: > > http://gnosis.cx/download/Gnosis_Utils-current.tar.gz > > 404 > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda > x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) > > > -- > http://mail.python.org/mailman/listinfo/python-list From timr at probo.com Thu Jul 25 01:27:16 2002 From: timr at probo.com (Tim Roberts) Date: Wed, 24 Jul 2002 22:27:16 -0700 Subject: Mastering Regular Expressions 2nd Ed. References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> <7xn0si9o2o.fsf@ruckus.brouhaha.com> <7934d084.0207232110.635049a7@posting.google.com> Message-ID: amuys at shortech.com.au (Andrae Muys) wrote: >Paul Rubin wrote in message news:<7xn0si9o2o.fsf at ruckus.brouhaha.com>... >> Tim Roberts writes: >> > The multi-thousand byte full expression to match a valid RFC822 e-mail >> > address was practically worth the price all by itself! >> >> Argggh! That sounds like regular expressions aren't really the best >> way to match RFC822 addresses. > >More like matching RFC822 addresses isn't worth the price of >admission. Exactly. "This multi-line ""behemoth"" is a perfectly valid" <"RFC822 e-mail"@address.com(really and truly)> I'll bet Outlook doesn't handle it... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From henk_derudder at hotmail.com Tue Jul 23 09:26:57 2002 From: henk_derudder at hotmail.com (henk_derudder at hotmail.com) Date: Tue, 23 Jul 2002 13:26:57 GMT Subject: Multikey dictionary Message-ID: <3d3d596e.357860250@news.skynet.be> Sory for reposting this, I forgot to mention a subject in my first post :-) Hi, What datatypes can one use as key in a dictionary? Can I use for example two longs as key (kind of a double key)? If not, are there examples on how to achieve this? thanks, Henk From bokr at oz.net Sat Jul 27 17:01:11 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2002 21:01:11 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 26 Jul 2002 14:45:34 +0100, Jonathan Hogg wrote: >On 26/7/2002 12:33, in article Ora09.122577$Jj7.2838699 at news1.tin.it, "Alex >Martelli" wrote: > >> (BTW, I've been programming for over _25_ years now -- more than >> half of my life...). > >Hmmm... over 18 years, about 2/3rds of my life. Never thought of it that way >before. Hmm... over 42 years, about 2/3rds of my life ... ;-) > >I don't recall ever intending to be a computer programmer... > I like to think of it as one of the things I like to do, not as my identity ;-) Regards, Bengt Richter From sheershion at mailexpire.com Wed Jul 3 09:19:38 2002 From: sheershion at mailexpire.com (Robert Amesz) Date: Wed, 03 Jul 2002 13:19:38 -0000 Subject: Syntax Error at end of file References: <3D22BD53.7020507@thomas-guettler.de> <3D22C1C6.1020109@thomas-guettler.de> Message-ID: Thomas Guettler wrote: > Found the error: It was an open >'''<. Would it be very difficult > if the error message could say what it was suspecting (''') and > tells me where the matching start is? Get a good editor with syntax colouring, and you'll never again be caught out like that. Robert Amesz -- P.S.: I prefer the SciTE editor. From jonathan at onegoodidea.com Tue Jul 30 04:31:24 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 09:31:24 +0100 Subject: beginner's question References: <66o19.694966$352.150300@sccrnsc02> Message-ID: On 30/7/2002 4:54, in article 66o19.694966$352.150300 at sccrnsc02, "jano" wrote: > /usr/lib/python2.1/site-packages/Ft/Lib/TestSuite does exist, and I am > uncertain why python does not see this. I would expect python to check in > the /usr/lib/python2.1/site-packages directory to look for 'Ft', but it > doesn't seem to be doing this. I am probably making a silly mistake, and > any help would be appreciated. Try checking first that you're running the right Python (or the test script is) - just in case you have two copies installed. Then try invoking Python (the right one ;-)) and do: >>> import sys >>> sys.path [ .... ] >>> to see where it's looking for modules. Jonathan From tim.one at comcast.net Fri Jul 12 04:31:42 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Jul 2002 04:31:42 -0400 Subject: A better self In-Reply-To: <3D2E8F10.B9B4EFD2@alcyone.com> Message-ID: [Peter Hansen] > Since you post without smileys, I can only assume you are serious? [Erik Max Francis] > Yes, that's right. Any post that doesn't contain a smiley is always > absolutely dead serious. Yes, that is the rule. There's a subtler one, too: whenever you read a post without a smiley, you're entitled to interpret its meaning in any way that strikes your fancy, and its author must concede that your reading is the intended one in all respects, and was probably intended with malice aforethought too. There are no exceptions. without-strong-rules-usenet-would-become-chaotic-ly y'rs - tim From jonathan at onegoodidea.com Wed Jul 3 10:27:23 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 03 Jul 2002 15:27:23 +0100 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: On 3/7/2002 14:55, in article eaef2e43.0207030555.1a63fe10 at posting.google.com, "Robert Kuzelj" wrote: > one could imagine an object that is a mix between a factory and > a prototyperegistry. > > class ProtoFactory: > def __init__(self): > self.SourceObjects = {} > def register(self, name, source): > self.SourceObjects[name] = source > def create(self, name): > source = self.SourceObjects(name) > if isinstance(source, types.Instance.Type): > return copy.copy(source) > else: > return source() Hmmm. Well I can think of a couple of possibilities: 1. Reverse the test and check to see if something is an instance of 'type' of 'types.ClassType', i.e., a new-style class or an old-style class. if isinstance(source, type) or isinstance(source, types.ClassType) return source() else: return copy.copy( source ) 2. If you know that the instances you are creating will not have '__call__' methods, then you can differentiate classes and instances by the fact that classes are callable: if callable( source ): return source() else: return copy.copy( source ) This works equally well for old- and new-style classes. Conveniently it also works functions that create objects and callable instances masquerading as classes or functions that create objects (hoo hah). > this is just an example. i am sure, that this can be done > differently. the real reason why i want to do this is something > i realy dare not to say in this forum ;-) Oh, you can tell us. No matter what crimes your contemplating, you can take comfort in the fact that they can probably be made more horrifying with metaclasses ;-) Jonathan From tim.one at comcast.net Mon Jul 15 03:47:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 15 Jul 2002 03:47:19 -0400 Subject: sorting many arrays from one... In-Reply-To: Message-ID: [Alex Martelli, on list.sort() special cases] > Right. The only extra case I've often wished it handled (defining > "often" as "more than once":-) is when the FIRST element is out of > order and all the rest are OK. That happens in mergesorting huge > streams, Is the number of streams also large? Just curious. > in the core merge loop: > > while streams: > yield streams[0][0] > try: > streams[0][0] = streams[0][2]() > except StopIteration: > del streams[0] > else: > streams.sort() # this is the first-maybe-OOO sort Understood, and that's reasonable. I expect the best a general sort method can do with this is worst-case N+log2(N) comparisons, give or take 1 or 2, where N=len(streams), the bulk of that because it has to establish that only one is out of order (it takes N-1 comparisons just to establish that an already-sorted list is already sorted). I have in mind a simple way to achieve that, so hold your breath . By arranging the streams in a min-heap yourself, you can guarantee worst-case log2(N) comparisons. If the number of streams can be large, that's a monster-big improvement; it's already a factor-of-3 improvement over N+log2(N) for N as small as 7. > The "streams" auxiliary list is originally built from the sequence X > of already-sorted streams as: > > streams = [ [X[i].next(), i, X[i].next] for i in range(len(X)) ] Ooh! In 2.3 you'll be able to say streams = [[s.next(), i, s.next] for (i, s) in enumerate(X)] It grows on you. > Normally N==len(streams) isn't all that big, and I COULD make each > leg of the "while streams:" loop O(N) anyway by using knowledge > about _which_ special cases method sort is so good at -- changing > the else clause into: > > else: > streams.append(streams.pop(0)) > streams.sort() # the maybe-OOO item is now *LAST*... > > but that's not all that pleasant -- I'd do it only in emergencies... That would indeed get you out with N+log2(N) comparisons, N of which you know aren't needed, but which list.sort() can't know aren't needed. If it is an emergency someday , I'd try else: s = streams.pop(0) bisect.insort(streams, s) instead. The smallest N for which that pays depends on how expensive element comparisons are, but the crossover point is generally small. The main loop can also be recoded naturally with less fiddly chained indexing then: insert = bisect.insort while streams: value, i, fetch = streams.pop(0) yield value try: value = fetch() except StopIteration: pass else: insert(streams, [value, i, fetch]) This kind of thing goes faster if streams is made a list of 3-tuples instead of 3-lists, if you're concerned about micro-optimization here. From jblazi at hotmail.com Sat Jul 13 17:49:13 2002 From: jblazi at hotmail.com (JB) Date: Sat, 13 Jul 2002 23:49:13 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308dcd_2@news.newsgroups.com> Message-ID: <3d309e8e_3@news.newsgroups.com> Bengt Richter wrote: Your idea sound very clever. I always make the mistake of describing my problem too abstractly. So following your idea with the None placeholders, I simply travel through list1. If an entry is celected by f, I copy it into list2, otherwise I do not. At the same time I maintain a counter for each lists for counting the entries that are not None. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From gerhard.haering at gmx.de Tue Jul 9 23:16:01 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 10 Jul 2002 05:16:01 +0200 Subject: How to grab a part of web page? In-Reply-To: <_ZJW8.46998$n4.11321007@newsc.telia.net> References: <_ZJW8.46998$n4.11321007@newsc.telia.net> Message-ID: <20020710031600.GD1965@lilith.my-fqdn.de> * Fredrik Lundh [2002-07-09 23:04 +0000]: > "A" wrote: > > Is it possible to download only a part of web page? > > Say I need to find out an information about a customer that starts > > at 1500 byte position and ends at 2000 byte position. If the whole > > page has about 100 kb it seems to me waste of time to load all the > > page. > > import urllib > > file = urllib.urlopen(DATA) > data = file.read(2000) > file.close() > > print data[1500:2000] What about implementing seek() on the file-like object? Wasn't this hotly discussed already a few month (years) ago? I wonder why it hasn't ended up in urllib, yet. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.5 ?C Wind: 1.7 m/s From fredrik at pythonware.com Thu Jul 18 14:05:47 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Jul 2002 18:05:47 GMT Subject: raw_input References: <3D36C5F1.9C966A8F@millfilm.co.uk> <3D36F9C4.A23D481A@millfilm.co.uk> Message-ID: <%rDZ8.16497$p56.5361636@newsb.telia.net> Eric Texier wrote: > Yes this is not what I am looking for. I was just hoping that it was > a little module somewhere that will let me edit a line of command > in the console, you know a bit like tcsh. sounds like you want raw_input: http://www.python.org/doc/current/lib/built-in-funcs.html raw_input([prompt]) ... If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features. (but if this doesn't work for you by default, chances are that your Python install doesn't support readline) From donn at drizzle.com Sat Jul 6 21:58:17 2002 From: donn at drizzle.com (Donn Cave) Date: Sun, 07 Jul 2002 01:58:17 -0000 Subject: sending a file through sockets References: <3D277DDC.1040705@nowhere.org> Message-ID: <1026007094.566332@yasure> Quoth Bryan Olson : | brueckd at tbye.com wrote: |> I actually spend |> most of my days writing network agents in Python (so I do know how to do |> it "right" or whatever), but I was just posting some code from memory to |> help the guy out; I think it's pretty obvious that you don't cut code from |> a Usenet post and paste it into your production system and expect no |> problems. | | O.K., and if you read my first post, I was entirely matter-of-fact in | pointing out the issues. No reason to get defensive. Do you actually | believe use of INADDR_ANY in connect() is doing it right? I read your first post, and I thought it was kind of inappropriate. For "my first Internet application" (the original poster's, that is), this was a mighty generous hint and more than adequate. One would imagine that in the end, the parameter to connect() would have to be filled in by the original poster. |>> On pull-the-plug a recv won't detect the connection loss until the local |>> system tries a keepalive probe, which is typically two hours. |> |> Apparently we're talking about different things because I just tried it |> and got a socket.error exception ('connection reset by peer') on Windows. | | On the recv() side? Sure doesn't work that way for me. Any idea how it | knew? Sure we're literally shutting the power off? That certainly wasn't what I meant, but I gather it is what you have in mind. Donn Cave, donn at drizzle.com From shalehperry at attbi.com Tue Jul 16 13:17:06 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 16 Jul 2002 10:17:06 -0700 (PDT) Subject: Making code faster In-Reply-To: <3d3450f2_6@news.newsgroups.com> Message-ID: >>> >>> i = -1 >>> print 'loading file' >>> def tmp1(s): >>> global i >>> i += 1 >>> return QSimpleViewItem(i,self.sv.lv.newColor,eval(s)) >>> you use a global --> time hit >>> tmp = myfile.readlines() readlines is highly optimized >>> print 'lines loaded' >>> datei.close() >>> self.sv.lv.rows = map(tmp1,tmp) >>> self.sv.lv.visible = range(len(self.sv.lv.rows)) >>> print 'lines decoded',self.sv.lv.rows[0].col[0] >>> >>> Any ideas? It is astonishing that loading the lines from >>> external storage takes much less time than the mapping >>> itself! >> Have you actually used a profiler on the code to see where the time was going? Could your call to eval() not be where the time is going? From anthony at interlink.com.au Tue Jul 30 09:32:13 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 30 Jul 2002 23:32:13 +1000 Subject: python 2.1.3 with tkinter support on Solaris 9 In-Reply-To: Message-ID: <200207301332.g6UDWD718556@localhost.localdomain> >>> Marc Petitmermet wrote > I still cannot compile python 2.1.3 with tkinter support on Solaris 9. I > have configured the environmental paths LD_LIBRARY_PATH, LD_RUN_PATH, > the Modules/Setup file and even adjusted the /var/ld/ld.config with crle > to include the libraries of tcl and tk libraries. > > The problem ist that setup.py still complains that it cannot find > libtk8.3.so although the it is located in /p1/local/tcltk/tk-8.3.4 as > configure Modules/Setup (see below). Can anybody tell me what I'm doing > wrong? Try 'ldd python' and see what it says. Adjust LD_LIBRARY_PATH (don't forget to 'export' it, depending on shell). Alternately, add -R/p1/local/... to the link line to force the ld run path. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From d2002xx at yahoo.co.uk Wed Jul 17 13:32:05 2002 From: d2002xx at yahoo.co.uk (d2002xx) Date: 17 Jul 2002 10:32:05 -0700 Subject: Problem with installing PyQt! References: Message-ID: > Hi, > I have installed python2.2.1 and Qt Non commercial(evaluation 3.0.4) for > windows. And I try to install PyQt3.2.4 in my computer, but just got > Example, Tutorial and Documentation, no executed application PyQt in it. > Why? PyQT is not a executed program, it's mainly a library. If you have run "python setup.py install", it should install the library(s) in subdir "site-packages" in python library directory. From chris.gonnerman at newcenturycomputers.net Thu Jul 11 08:35:19 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 11 Jul 2002 07:35:19 -0500 Subject: COCOMO - appropriate for languages like Python? (fwd) References: <200207102307.g6AN72822540@panix1.panix.com> <3D2D779D.D988C6F0@mitre.org> <006d01c228d6$753f72c0$0101010a@local> Message-ID: <007c01c228d7$6bed7900$0101010a@local> ----- Original Message ----- From: "Chris Gonnerman" To: "Mike Brenner" > Here's a ruler for you. You need to be using a monospace font for this to > be > useful; I generally use Lucida Console. > > 0123456789 0123456789 0123456789 0123456789 > 0123456789 0123456789 0123456789 > 0123456789 Well, that's a puzzler. Does the mail/news gateway rewrap lines? It seems to allow about 73-74 character lines in the text above. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From fredrik at pythonware.com Sat Jul 27 18:05:38 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 22:05:38 GMT Subject: wxPython TextCtrl overwriting References: Message-ID: "Chris" wrote: > I'll give that a try. BTW, any idea why python usually crashes so > horrendously while running my GUI in windows? It seems like if I > click on my python window or anything like that while the GUI is up, > everything crashes fierce are you running a wxPython program from inside IDLE? if so, it's probably the usual problem: IDLE runs your program inside it's own process, which is already running a Tkinter GUI. when both libraries fight over who's in charge of the underlying Window APIs, all sorts of things can happen. the solution is to run the program from the command line, or get an environment that knows how to run programs in an ex- ternal process (such as IDLE-FORK and most commercial IDEs). From nathan at cjhunter.com Fri Jul 12 13:28:01 2002 From: nathan at cjhunter.com (Nathan Cassano) Date: Fri, 12 Jul 2002 10:28:01 -0700 Subject: Linking to Python 2.2 Message-ID: <001401c229c9$79d2f930$2901a8c0@amos> Hi folks, I am having trouble linking to the Python library for development purposes. Does anyone know the correct way to link to Python version 2.2? Should I just try a different version of Python? Thank for your help. Here's that action. gcc -g -O2 -o program main.o -Xlinker --export-dynamic -Wl,-E -L/usr/lib/python2.2/config -lpython2.2 -ldl -lpthread -lutil /usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function `posix_tmpnam': /usr/src/packages/BUILD/Python-2.2.1/./Modules/posixmodule.c:4501: the use of `tmpnam_r' is dangerous, better use `mkstemp' /usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function `posix_tempnam': /usr/src/packages/BUILD/Python-2.2.1/./Modules/posixmodule.c:4451: the use of `tempnam' is dangerous, better use `mkstemp' /usr/lib/python2.2/config/libpython2.2.a(floatobject.o): In function `float_pow': /usr/src/packages/BUILD/Python-2.2.1/Objects/floatobject.c:578: undefined reference to `pow' /usr/lib/python2.2/config/libpython2.2.a(complexobject.o): In function `_Py_c_pow': /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:140: undefined reference to `pow' /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:144: undefined reference to `exp' /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:145: undefined reference to `log' /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:147: undefined reference to `cos' /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:148: undefined reference to `sin' collect2: ld returned 1 exit status Python 2.2.1 Suse 8.0 Linux 2.4.18 Gcc 2.95.3 From dark_phenix_98 at yahoo.fr Wed Jul 24 11:27:23 2002 From: dark_phenix_98 at yahoo.fr (ferreira jorge) Date: Wed, 24 Jul 2002 17:27:23 +0200 Subject: error code References: Message-ID: <3d3ec90c$0$28132$afc38c87@news.easynet.fr> In your example you write the Exception code . for example : try : server = smtplib.SMTP('XXXXXXX') except : print "error : %s --> %s " % ( sys.exc_value , sys.exc_type) If I put a bad host , I have the error : "error : host not found --> socket.error" I suppose that the error "host not found" have a caracteristic number . how can I get it ? "Mark McEahern" a ?crit dans le message de news: mailman.1027523168.10025.python-list at python.org... > > I want to get the code of an error . > > > > how can I do that ? > > > > With "sys.exc_value" and "sys.exc_type" I have a String . > > But I want a Integer > > This probably isn't what you want, but given the vagueness of your question, > how the heck would I know that? > > class MySpecialError(Exception): > > code = 100 > > try: > raise MySpecialError > except Exception, e: > if hasattr(e, "code"): > print "Code: %d" % e.code > > // mark > > - > > From gcordova at hebmex.com Tue Jul 9 09:42:38 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Tue, 9 Jul 2002 08:42:38 -0500 Subject: Table Widget (without Installation) Message-ID: Try this, hope it helps. Just download tktable from sourceforge and install it. It's not totally finished, so any and all bug reports will be much appreciated. Salutations. -gustavo > -----Original Message----- > From: Thomas Guettler [mailto:zopestoller at thomas-guettler.de] > Sent: Tuesday, July 09, 2002 3:05 AM > To: python-list at python.org > Subject: Table Widget (without Installation) > > > Hi! > > I am searching for a table widget to > use with python. Is it still true that > tkinter has none? > > I need it for an application on win32 > which should not be installed. All > libraries will be in one directory. > > pyFox, pygtk, wxpython are options. > > pyQt not since it is not allowed for commercial > applications. > > Which could be the easiest? > > thomas > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: TkTable.py Type: application/octet-stream Size: 17731 bytes Desc: not available URL: From jepler at unpythonic.net Wed Jul 17 08:47:14 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 17 Jul 2002 07:47:14 -0500 Subject: Exploit for a security hole in the pickle module for Python versions <= 2.1.x Message-ID: <200207171247.g6HClEu04202@fromage.dsndata.com> """ Exploit for a security hole in the pickle module for Python versions <= 2.1.x Pickle is the name of a Python module for object persistence. It can convert arbitrary Python objects into byte streams and back. Though the documentation for Python 1.5.2 read The pickle module doesn't handle code objects, which the marshal module does. I suppose pickle could, and maybe it should, but there's probably no great need for it right now (as long as marshal continues to be used for reading and writing code objects), and at least this avoids the possibility of smuggling Trojan horses into a program. it was always generally considered that a carefully-crafted "pickle" could execute arbitrary code. In Python 2.0, one hole was closed which was due to the use of eval() to unpickle a string. This hole could be exploited with a pickle string like "S''*__import__('os').system('echo 0wn3d')\np0\n." In Python version 2.2, a new restriction was added to unpickling of instances: when unpickle would have called a constructor, the class must define an attribute __safe_for_unpickling__ with a true value, or an exception will be raised. Because a "class constructor" is simply a callable object, a pickle can be written that names any function and gives it arbitrary arguments. Thus, a specially crafted pickle might contain the instruction instantiate the class os.system with the argument "echo r00t::0:0::/:/bin/sh >> /etc/passwd" Many major Linux distributions still ship with Python 1.5.2, which is vulnerable to both of these types of exploits. Some ship with 2.0 or 2.1, usually in addition to 1.5.2. These versions are vulnerable to the second type of exploit. I don't know of a Linux distribution which ships with only python 2.2, which is free from both these problems. However, I know of no particular uses that lead to a direct security breach. """ import pickle, new def nasty(module, function, *args): return pickle.dumps(new.classobj(function, (), { '__getinitargs__': lambda self, arg = args: arg, '__module__': module }) ()) # Create the evil pickle t = nasty("__builtin__", "open", "/tmp/pickle-bug", "w") # Show the user how it looks print repr(t) # Now, load the pickle -- creates the file /tmp/python-is-buggy (by calling # the builtin open() function, then raises an exception. But the damage is # done... pickle.loads(t) From see_reply_address at something.invalid Wed Jul 3 00:53:28 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 03 Jul 2002 16:53:28 +1200 Subject: is attribute access a hash-lookup by name? References: <66715c02.0207021737.b488f07@posting.google.com> Message-ID: <3D228348.1070201@something.invalid> Steven Shaw wrote: > As I understand it, in Python, an object is an associative array or > hash. I imagine this means that every attribute access is a > hash-lookup by name. Yes. > Does the implementation optimise this away > somehow? Currently, the only optimisation is that variable names mentioned in code are interned, so their hash function is only computed once, and they can be compared for equality with a pointer comparison. > Is there a way to have structs/records in Python where the members of > the struct are looked up by offset (not by name)? Yes -- use a list or tuple. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jonathan at onegoodidea.com Thu Jul 4 16:46:06 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 21:46:06 +0100 Subject: replacing instance __setattr__ References: <6qfzyzxxfx.fsf@abnoba.intevation.de> Message-ID: On 4/7/2002 17:36, in article 6qfzyzxxfx.fsf at abnoba.intevation.de, "Bernhard Herzog" wrote: > I'm not sure about the new style classes as I haven't had the time to > really look at them yet, but for old style classes that's not quite > true. > > For instance, __getattr__ does *not* define how attributes are looked > up. It's only called by the interpreter when the normal attribute lookup > fails. Yeah, I knew I was taking liberties when I wrote the posting, since the whole thing is done at the C level. The __*attr__ python methods don't actually get called until later in the process. The '__getattribute__' special method lets you hook into attribute lookup at an earlier point so I should have used that as an example, but it only works with new-style classes. On 4/7/2002 18:09, in article mailman.1025803028.29763.python-list at python.org, "Tim Peters" wrote: > The object dict (x's dict in the above, which has nothing to do with > object's dict) is never searched for methods, and not in any version of > Python. Methods can only come from classes in Python. If the name > "somemethod" isn't found in x's class or any of its base classes, then > "somemethod" is not a method of x. "somemethod" may well be a data > attribute of x that's bound to a function that "acts like" a method, or > close enough to acting like a method that your app doesn't care about the > difference, but even so it's not a method of x if you're careful with words. > An object's (as opposed to the builtin class named object) dict in Python > can only supply data attributes. Hmmm. >>> class foo: ... def bar( self ): ... print 'bar' ... >>> f = foo() >>> f.bar > >>> type( f.bar ) >>> f.bar() bar >>> >>> def baz( self ): ... print 'baz' ... >>> import new >>> f.baz = new.instancemethod( baz, f, foo ) >>> f.baz > >>> type( f.baz ) >>> f.baz() baz >>> Looks like a method, walks like a method - and surely, in the brave new world of types and metaclasses, that's the only definition that counts ;-) Jonathan From pwanon at web.de Mon Jul 22 17:09:43 2002 From: pwanon at web.de (Peter Wichert) Date: Mon, 22 Jul 2002 23:09:43 +0200 Subject: newbie problems with Tkinter Message-ID: Hi group, I installed python 2.2.1 on my freebsd4.5 and tried some examples from my new python-book. But I couldn't get it running. 1) Using module "Tkinter" is the first problem. Doing it twice seems to be better: >>> import Tkinter Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? ImportError: No module named _tkinter >>> import Tkinter >>> 2) After that, the book says "tk=Tkinter.Tk()", but I get >>> tk=Tkinter.Tk() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Tk' >>> That's all. Please help me. Peter -- Peter Wichert pwanon at web.de From aleax at aleax.it Fri Jul 5 16:17:38 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 5 Jul 2002 22:17:38 +0200 Subject: adding methods on the fly In-Reply-To: <200207051918.g65JIALM018771@ratthing-b246.strakt.com> References: <200207051918.g65JIALM018771@ratthing-b246.strakt.com> Message-ID: <02070522173800.28485@arthur> On Friday 05 July 2002 21:18, Laura Creighton wrote: > > > > For an example, see > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 > > (or, better, the expanded and clarified version in the printed > > Python Cookbook, ed. Martelli and Ascher, but that's only due out > > in 3 weeks, so, meanwhile, the original online version will do:-). > > > > Hmmm, how much work will there be to make the on-line version > compatible with the book? Is that the intention? I wouldn't mind, but it's out of the question that I can find the time until I'm done with the Nutshell. I don't know what are the plans of ActiveState -- if they have any resources allocated to fund that substantial effort (the site is ActiveState's, after all). Alex From Simon.Foster at smiths-aerospace.com Tue Jul 9 08:50:19 2002 From: Simon.Foster at smiths-aerospace.com (Simon.Foster at smiths-aerospace.com) Date: Tue, 9 Jul 2002 13:50:19 +0100 Subject: Splitting a string every 'n' Message-ID: <001727B6.C22236@smiths-aerospace.com> What is the idiomatic way to split a string into a list containing 'n' character substrings? I normally do something like: while strng: substring = strng[:n] strng = strng[n:] But the performance of this is hopeless for very long strings! Presumable because there's too much list reallocation? Can't Python just optimise this by shuffling the start of the list forward? Any better ideas, short of manually indexing through? Is there something like: for substring in strng.nsplit(): From ak at silmarill.org Sat Jul 6 15:28:39 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Sat, 06 Jul 2002 19:28:39 GMT Subject: signal.alarm() for less than one second? Message-ID: Hello python folks, It looks like signal.alarm takes 1+ seconds as argument. I need something lower, like 0.5 second or so. I'm making a text user interface where you have to pick an item from a list by typing its number. Normally you'd have a raw_input() call but in this case it's a UI for picking tracks from a list in an mp3 player - something you may want to do many times in a row and I want to save a one keypress for each command. You see a list of 15 songs and you type in '13'. It goes to song #13 immediately. Then you type in '1' - it waits for ~.5 sec waiting for further input, then goes to 1st song if none given. SIGALRM seemed perfect for this, here's the way I put it together: from signal import * import avk_util t = avk_util.Term() s = "" Complete = "Got the num!" def handler(signum, frame): if s: print "there is s!" raise Complete try: while 1: signal(SIGALRM, handler) alarm(1) a = "" try: a = t.getch() except OSError: pass alarm(0) s += a print "s is", s except Complete: print "GOT RESULT: '%s'"% s getch() here gets one number at a time (using my own util module avk_util). Here's the rub: if I put alarm(0.5) in here, it won't work at all. What else can I do here? Use threads? Thanks, - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jayant at tam.cornell.edu Tue Jul 23 20:03:57 2002 From: jayant at tam.cornell.edu (Jayant Kulkarni) Date: Tue, 23 Jul 2002 20:03:57 -0400 Subject: Adding Modules to precompiled installation of Python References: Message-ID: "Chris Liechti" wrote in message news:Xns9254A000DE623cliechtigmxnet at 62.2.16.82... > "Jayant Kulkarni" wrote in > news:ahiii8$4u2$1 at news01.cit.cornell.edu: > > > My problem I guess is very specific so I doubt if somebody has run into > > it before but any general help would be appreciated. > > > > I am using the finite-element package Abaqus which comes with > > precompiled Python (ver 1.5). I want to interface this with Matlab using > > Pymat. (PyMat utility by Sterian). The problem is that as the python is > > precompiled I do not know how to import new modules.. > > > > Additional info: > > The PyMat utility comes with PyMat.cpp and Pymat.pyd. > > I am on a Windows OS. (Though I have access to Linux, and I can work on > > that system as well.. So solution to the problem in any OS should be of > > help) > > have you tried to copy those file to the current directory an type (or make > a script with): > > import PyMat > > either it works or you'll get an exception from python. if you get an > exception, add it to you next msg. note that pyd must be compiled for a > specific python (major) version (i.e. 1.5/2.0/2.1 etc.). so you'll need > Pymat.pyd for 1.5 > > chris > -- > Chris Thanks for the suggestions. I changed the PYTHONPATH so that it points to the pymat.pyd file. I then tried >>> import PyMat And I get the following error: ImportError: dynamic module does not define init function (initPyMat) If I try >>> import pymat I get the error: Fatal Python error: PyThreadState_Get: no current thread Any light that can be shed would be of help! Thanks! jayant kulkarni From akuchlin at ute.mems-exchange.org Mon Jul 1 07:44:52 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 01 Jul 2002 11:44:52 GMT Subject: I'd give up Perl tomorrow if only... References: Message-ID: In article , Richard Jones wrote: > I recently stepped up to the plate, but got zero response from catalog-sig. > I'll be contacting authors of the various half-finished systems directly if I > get no response soon. Don't expect a response from the SIG readership. Jason Petrone posted a BSD ports-like system: no comments. Ciphon was announced: no reaction. Just go ahead and implement something, and tell people to live with it; that seems the only way anything will ever get done. --amk (www.amk.ca) Small though it is, the human brain can be quite effective when used properly. -- The Doctor, in "The Two Doctors" From erochest at arches.uga.edu Sun Jul 7 10:37:46 2002 From: erochest at arches.uga.edu (Eric Rochester) Date: Sun, 07 Jul 2002 10:37:46 -0400 Subject: StandaloneZODB on Python 2.2.1/Windows? References: Message-ID: <3D28523A.8080204@uga.edu> David LeBlanc wrote: > Neither the bundled 1.0 distro or the latest CVS seem to want to work for me > on Windows 2kpro sp2 with Python 2.2.1 > > Crashes with a pointer exception on trying to run anything. > > Anyone had any success with this platform? > > David LeBlanc > Seattle, WA USA > > > I've downloaded Standalone ZODB from CVS on June 28, and it seems to work fine on Win2kpro sp2. I'd be happy to put the binaries up on the web, if you'd like. -- Eric Rochester English Department The University of Georgia Athens, Georgia 30602 ---- I have a cunning plan! --Baldric From JoeSalmeri at comcast.net Mon Jul 29 09:55:07 2002 From: JoeSalmeri at comcast.net (Joe Salmeri) Date: Mon, 29 Jul 2002 13:55:07 GMT Subject: Python + Win32ALL + ASP = Problems accessing Request/Response/Session/Application objects References: <_ko%8.247434$iB1.13124073@bin4.nnrp.aus1.giganews.com> <3D3E6BCD.4010809@mxm.dk> <3D3F8DF3.9060807@skippinet.com.au> Message-ID: <%Ob19.344049$iB1.17531353@bin4.nnrp.aus1.giganews.com> Thanks Mark! I'll use the ax object, one parm is better than having to pass each of the objects in a separate parm, plus that way they are all available even if I originally only need one of them. "Mark Hammond" wrote in message news:3D3F8DF3.9060807 at skippinet.com.au... > Joe Salmeri wrote: > > > Hopefully Mark Hammond will see this, I'm sure he will be able to provide > > the answer (he always does!) > > OK :) > > It is all a bit nasty I'm afraid. In a nutshell, these objects are just > COM objects that exist in some global namespace. (They are actually > pyscript.ScriptItem objects, added as globals in > pyscript.PyScript.RegisterNamedItem()) > > Each "engine" has a global namespace. The "engine" is defined by the > application (ie, ASP), and "named items" along with the user specified > "script code" are added to this engine. > > ASP obviously could have many Python engines open at once - one for > every different connection to a page with Python content. Your external > module may be used by any number of other ASP connection/scripts, so you > really can't consider these script objects as "global" in any sense of > the word. > > So while you may be able to devise a scheme for yourself, there really > isn't much the ActiveScripting framework can do to help - nothing here > is "global", so nothing is exposed as such. > > You could just pass the "ax" object around - it should have all the > globals as attributes - eg, "ax.session" may work. > > Mark. > From whisper at oz.net Mon Jul 8 23:13:38 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 8 Jul 2002 20:13:38 -0700 Subject: Idle setup install falis on Win2k In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Tim Peters > Sent: Monday, July 08, 2002 17:38 > To: Python-List at Python. Org > Subject: RE: Idle setup install falis on Win2k > > > [David LeBlanc] > > Idle.py assumes that it's scripts are in the same directory as itself > > It assumes they're on sys.path. This is normally true. > > > and they're not after install. > > As opposed to what, "before install"? I can't tell what you're > getting at. > All of Idle is installed under Tools\idle\ on Windows, and the Start menu > shortcut reads (assuming the default install path): > > C:\Python22\pythonw.exe "C:\PYTHON22\Tools\idle\idle.pyw" > > > Idle.pyw just silently fails if they're not in the same dir as itself. > > > > This is PythonLabs Python 2.2.1 binary on Win2k with the included > > distribution of Idle. > > Where do you think Idle got installed? Don't get paranoid, but this is > another thing that works for everyone but you . BULLSHIT! RTFC! If you run /python22/tools/idle/setup.py install see what happens!!! HINT: TAKE A LOOK AT /python22/scripts/idle.py! Then, please tell me how: #!J:\Python22\python.exe import PyShell PyShell.main() is going to magically figure out that PyShell.py got put in /python22/lib/site-packages/libidle? If /python22/tools/idle/setup.py shouldn't be run on Windows, WHY IS IT THERE? Strange as it might seem to you, some Windows developers use a command line and, at least in theory, if you install Idle, you should be able to run it from a command line. (BTW, it did install in the python22 group of the start menu.) AS for things that "only work for me", I have reinstalled C++, Python and re-built standaloneZODB and it STILL compiles and crashes. I personally suspect all the weird and funny games that are played by SAZODB when it loads. Why, for example, does it import things and then delete them? (site-packages/zodb/__init__.py). Just because I'm the only one experiencing a problem DOES NOT mean that there's not a problem with your (Zope's) code! I'm glad you declared the problem solved and then just walked away. Dave LeBlanc Seattle, WA USA From dreed at capital.edu Mon Jul 8 17:03:57 2002 From: dreed at capital.edu (Dave Reed) Date: Mon, 8 Jul 2002 17:03:57 -0400 Subject: List assignment, unexpected result In-Reply-To: <7xd6tyoswp.fsf@ruckus.brouhaha.com> (message from Paul Rubin on 08 Jul 2002 13:40:06 -0700) References: <7xd6tyoswp.fsf@ruckus.brouhaha.com> Message-ID: <200207082103.g68L3v526612@localhost.localdomain> > From: Paul Rubin > > The intent is clear i.e. fill the diagonal with 0,1,2,3; but the > > result is somewhat different. Could anyone explain why this doesn't > > work as expected - and even better, come up with an assignment for > > 'grid' that would work. > > grid = [['.' * 4] for i in range(4)] > > is one way. I think: grid = [['.',] * 4 for i in range(4)] is what you need otherwise you get: [['....'], ['....'], ['....'], ['....']] and grid[1][1] gives you and index error Dave From mwh at python.net Mon Jul 22 10:50:40 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 22 Jul 2002 14:50:40 GMT Subject: unsigned ints and operator.rshift References: <3D3C1802.948E2D99@mill.co.uk> Message-ID: Joe Connellan writes: > I'm storing info in an int (32bits) that I'm wanting to shift left and > right using operator.[l|r]shift the problem is that because the int is > signed rshift fills in 1's rather than 0's on negative numbers - is > there any way to store the 32bits as an unsigned int do get around this? Use longs and keep masking? There's no guarantee that Python int's are 32 bits -- they're 64 bits on alphas f'ex. Cheers, M. -- LINTILLA: You could take some evening classes. ARTHUR: What, here? LINTILLA: Yes, I've got a bottle of them. Little pink ones. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From gumuz at looze.net Thu Jul 4 08:17:01 2002 From: gumuz at looze.net (Guyon Morée) Date: Thu, 4 Jul 2002 14:17:01 +0200 Subject: sending a file through sockets Message-ID: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> Who knows how to send and receive a file(binary data) through sockets? thanx, Guyon From brian at sweetapp.com Wed Jul 10 20:15:41 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 10 Jul 2002 17:15:41 -0700 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <1026288146.20796.63.camel@lestat.howden.press.net> Message-ID: <000201c22870$1a679780$bd5d4540@Dell2> Here is some XML-RPC IP-based authentication code that works: import sys, os, gzip, smtplib, SimpleXMLRPCServer, string class AuthenticatingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPC RequestHandler): class UnknownIP(Exception): pass def _dispatch( self, method, params ): ip, port = self.client_address if ip not in ["144.178.233.83","144.178.234.189", '127.0.0.1'] : raise self.UnknownIP, "Client IP Is Not Authorised" else: SimpleXMLRPCServer.SimpleXMLRPCRequestHandler._dispatch(self, method, params) def GetFiles(FileRequest): print FileRequest RetrFile = open(FileRequest,"r") FileContents = "Not Found" for FileLine in RetrFile: if FileContents == None: FileContents = FileLine else: FileContents = FileContents + FileLine return FileContents if __name__== "__main__": XMLRPCServer = SimpleXMLRPCServer.SimpleXMLRPCServer ( ("127.0.0.1",8000), AuthenticatingSimpleXMLRPCRequestHandler ) XMLRPCServer.register_function(GetFiles) XMLRPCServer.serve_forever() > Thanks again for your help and patience. If we ever meet in person, you owe me many beers :-) Cheers, Brian From whisper at oz.net Sun Jul 21 13:55:59 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 21 Jul 2002 10:55:59 -0700 Subject: XSLT processor In-Reply-To: Message-ID: > I know that. But extension elements/functions is not the thing I > need. I want to register my own function as a template. Instead of the > content of the element being executed, the registered > function should be called. > > Bye Stefan exslt has that capability, but I don't know that it's been implemented in Python yet - technically, I think it needs Javascript. 4Suite implements most of the exslt spec (but not this feature), as does libxslt (don't know what part(s) it implements). Dave LeBlanc From spam at ob_scure.dk Sun Jul 7 07:14:24 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 13:14:24 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> Message-ID: <3D282290.1050101@ob_scure.dk> Anders Dahlberg wrote: [snip] > Considering it's compiling down to java-bytecode which are then run with a > java-vm - It should scale as well as any java solution (or atleast ~90%). > Links could be: > > http://java.sun.com ;) > http://www.bea.com/products/weblogic/jrockit/index.shtml - very good server > vm. (optimised for intel) [snip] > disclaimer: This is just what I believe - if you want to base your case on > this I believe you should contact other companies using java with > multiple-cpus! I am quite certain that scaling (well) to multiple CPU requires one to use threading at least. Scaling to several physical machines might be (relativly) easy with Java, but imagine it must require some coding, or? -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From fredrik at pythonware.com Tue Jul 16 13:41:47 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Jul 2002 17:41:47 GMT Subject: select.select for non-sockets in win2k References: <930dfcf0.0207131436.153edc47@posting.google.com> Message-ID: Martin Sj?gren wrote: > > Is there still no select.select function that works with non-sockets > > like the object returned by os.popen()? > > AFAIK, this is a limitation (for better or for worse) in Windows. It's > not a limitation in Python. it's a limitation in the select implementation on Windows. Windows has other mechanisms for asynchronous I/O, but it would probably take a rather extensive rewrite of Python's I/O system to be able to take full advantage of them. (dunno how much of this the win32 extensions support, but I'm sure Mark knows...) From brueckd at tbye.com Tue Jul 2 03:54:48 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 2 Jul 2002 00:54:48 -0700 (PDT) Subject: New style classes as exceptions (Was: exception handing) In-Reply-To: <20020702000737.J10625@prim.han.de> Message-ID: On Tue, 2 Jul 2002, holger krekel wrote: > Aahz wrote: > > In article , > > Denis S. Otkidach wrote: > > > > > >New style classes don't work when used as exceptions. I guess it > > >should be considered as a bug. > > > > Nope, that's just the way it currently works. > > what's your definition of a bug, then? A bug is when behavior fails to match the spec and/or the spec leaves something out. As the formality of a spec approaches non-existence, everything becomes an enhancement request. ;-) -Dave From roy at panix.com Fri Jul 5 10:40:07 2002 From: roy at panix.com (Roy Smith) Date: Fri, 05 Jul 2002 10:40:07 -0400 Subject: Why self? References: Message-ID: holger krekel wrote: >> I do not find it usefull that I can give it my own name. > > which, in fact, hardly anybody ever does. Other than in an obfuscated python contest, I can't think of any reason why anybody would *ever* use any variable name other than "self" as the first formal parameter of a method. Have you ever seen an example that does? From aleax at aleax.it Fri Jul 26 12:43:34 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 16:43:34 GMT Subject: Derivative of string as a name of list or dictionary (or class?) References: <82fe0bb.0207260749.3059e20a@posting.google.com> Message-ID: John Hunter wrote: ... > If you want to set variable names in the global namespace, I am > reasonably sure you can do a similar thing by manipulating a global > object, but I don't know what it is. You can always use exec, but you > will probably have people frown at you Sure, but the frown is first of all against the very task that the OP wants to perform: setting arbitrary names in the global space. What if one of the name is 'print'? Boom. Python has a couple of dozen keywords -- what ensures against attempts to redefine one? Python has dozens of useful builtins -- what if one of the arbitrary names to be injected happens to overlap with one of the builtins the program is using? Potentially even worse and subtler bugs, as the exec statement will succeed, but any later arbitrary point of the program may fail mysteriously. It's a fool's errand, and the only sensible answer to "how do I set arbitrary global names?" is "don't: you'll regret it". Setting arbitrary *attributes* on any object of your choice is a far superior approach by any measure (you still do have to take care that the names don't clash with Python keywords, IF you expect to have Python code using them as attribute names, but that, too, can most often be avoided). Using the exec statement has even more downsides, such as likely horribly slowing down the function that uses it and making your program totally vulnerable to malicious users. But I guess any program that WANTS to trample all over any arbitrary names of its global namespace is self-destructive enough that such issues may be seen as pluses... Alex From logiplexsoftware at earthlink.net Wed Jul 3 21:07:45 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: 03 Jul 2002 18:07:45 -0700 Subject: File Locking (or any similar file mutex) in Windows OS??? In-Reply-To: <3d238ca3$0$333$e2e8da3@nntp.cts.com> References: <3d238ca3$0$333$e2e8da3@nntp.cts.com> Message-ID: <1025744866.5412.10.camel@localhost.localdomain> On Wed, 2002-07-03 at 16:45, Ron Horn wrote: > I would like some simple and robust way to know if one of the clients is > currently using the file, but my question could apply to any shared resource > the various client instances could want to share. It seems that the various > file locking features of os.open(), and anydbm.open(), etc. are not working > right on Windows? > > Any suggestions on how to make this work in python running on windows > clients/server would be appreciated. You could write a "lock-server": a process that runs on the server (or any single PC, for that matter) that listens on a TCP port. When a client wants to lock a file, it can pass the filename of the file to the lock server and if the lock server returns a certain value (0, 1, 'r', 'w', etc), the client knows whether it is safe to access the file (or resource). When the client is finished it simply disconnects from the server and the server frees up that resource (freeing on disconnect is good as it allows the resource to be freed in case of a client crash as well). This approach doesn't enforce locking (it requires that the clients honor the status returned by the server), but it should be fairly simple to implement. I'd consider using Pyro or something similar to simplify it even more. Regards, Cliff From theller at python.net Wed Jul 10 07:43:02 2002 From: theller at python.net (Thomas Heller) Date: Wed, 10 Jul 2002 13:43:02 +0200 Subject: Pyrex and Distuils: an enhanced build_ext command References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> <3d799735.0207100216.4eb8a9cd@posting.google.com> Message-ID: "Graham Fawcett" wrote in message news:3d799735.0207100216.4eb8a9cd at posting.google.com... > # compiling with mingw32 gets an "initializer not > a constant" error > # > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp > # doesn't appear to happen with MSVC > # so if we are compiling with mingw32, massage the > Pyrex-generated > # C files to compile properly > Isn't this problem (initializer not a constant) solved by compiling the file in C++ mode (with .cpp extension)? Thomas From me at michaelbauers.com Thu Jul 11 07:07:14 2002 From: me at michaelbauers.com (Michael Bauers) Date: Thu, 11 Jul 2002 06:07:14 -0500 Subject: Lunar lander source Message-ID: Some people asked about the source code and mentioned pygame. The original version was text based only. But seeing as pygame seemed not too hard to learn, I wrote a verion in that as well. Text based lunar lander: www.michaelbauers.com/lunland.py Pygame based: www.michaelbauers.con/pg2.py Sorry about the poorly chosen name for the pygame version. (pg2 = pygame2 :) ) From jeffrey.b.layton at lmco.com Sun Jul 21 11:00:54 2002 From: jeffrey.b.layton at lmco.com (Jeff Layton) Date: Sun, 21 Jul 2002 11:00:54 -0400 Subject: Scope of instantiated class Message-ID: <3D3ACCA6.7030002@lmco.com> Hello, If I instantiate a class in a function, leave the function via a return and then go back to the same function, will the instantiation of the class still be there or is it local to the function so it is "destroyed"? (Does this make any sense?) TIA, Jeff From cliechti at gmx.net Tue Jul 23 11:28:59 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 17:28:59 +0200 Subject: Make me beautiful (code needs help) References: Message-ID: Mark wrote in news:HVd%8.6582$I4.1825 at nwrddc03.gnilink.net: > Ok, I have the following data: > > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] is there a special reason to store it in a dict? just use a variable "a" and "new"... if you need it in a dict, then assign it to a key in the dict at the end. that makes your loop faster. > That is, I want to get the successive differences into their proper > place. I don't care what is in the question mark spot. I'll figure > that out later. > > Here's my current code: > > for i in range(len(data["A"])): > try: > data["new"].append(data["A"][i] - data["A"][i-1]) > except OutOfBounds: > data["new"].append("?") > > Now, the other problem, is that in general, I want to fill data["new"] > with an arbitary function of the values in data["A"]. As a dumb > example, I might want to fill data["new"] with copies of the mean > (average) of data["A"]. So, in some cases, the new values are > relative to the current location (ie i and i-1) and in other they are > absolute (ie all of them). > > I can certainly hack through this, but I'm looking for something > pretty. I know python is up to it. well, "pretty" is in the eye of the beholder... differences (maybe use operator.sub, this is for Py2.2): >>> map(int.__sub__, a+[0], [0]+a)[1:-1] [1, 2, 6, 40] you can have that in a list comprehension too: >>> [a-b for a,b in zip(a+[0], [0]+a)][1:-1] [1, 2, 6, 40] mean: >>> reduce(int.__add__, a)/float(len(a)) 13.4 converting to float isn't needed when you use "form __future__ import division" chris -- Chris From whisper at oz.net Mon Jul 1 16:04:41 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 1 Jul 2002 13:04:41 -0700 Subject: Python language dedicated Wiki In-Reply-To: Message-ID: I've always thought it would be a nice idea to put PythonDoc into a wiki, not only on a website, but also as part of the distribution. A website pythondoc wiki could be a common place to annotate/enhance the community brain, and, as part of the distribution, creates a central place to also annotate and save snippets for oneself. I personally favor TWiki and wish it was written in Python... David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Daniel Dittmar > Sent: Monday, July 01, 2002 9:38 > To: python-list at python.org > Subject: Re: Python language dedicated Wiki > > > >> It seems to me that C.l.py is too overloaded today. > >> Wouldn't it be nice if someone(not me - I think I don't have > >> resources for it) bothered to setup a wiki for discussion about > >> python language? > > Two topics which would benefit from having a Wiki (because the information > is constantly changing): > > - GUI programming and toolkits > - Web programming > > I'm thinking along the lines of > - comparisons > - cookbook/snippets > - initial meeting ground for new projects > > There are some brave souls trying to summarize this on web pages, > but a Wiki > makes it possible to distribute the work. > > I don't know whether it would be better to have one large Python > Wiki or to > have topics such as these split into seperate Wikis. > > I'm sure there are other topics as well > - how can I implement this PEP in current Python > - functional/logical/whatever programming in Python > - autocoding (just joking - too late, I made the kill file) > > Daniel > > > > -- > http://mail.python.org/mailman/listinfo/python-list From rs at onsitetech.com Mon Jul 8 13:42:00 2002 From: rs at onsitetech.com (Robb Shecter) Date: 08 Jul 2002 17:42:00 GMT Subject: Why self? References: Message-ID: <3D29CE9D.4000802@onsitetech.com> Matt Gerrans wrote: > In Python, I think the required "self" reference in methods is a case where > the solution is worse than the problem it solves. Since indentation is the > method of scoping in Python, this addition of five characters to each > instance variable is particularly annoying -- a one-line statement that > contains several instance variables can easily become unmanageable. I completely agree, but I think the situation's even worse than you described: A'typical' case of standard OO programming is made the most tedious to write: References to instance variables from methods: self.__velocity = self.__factor1 * self.__factor2 etc. I find this totally unreadable (7 extra characters per referenced instance variable). Robb From maxm at mxm.dk Wed Jul 3 09:33:00 2002 From: maxm at mxm.dk (Max M) Date: Wed, 03 Jul 2002 15:33:00 +0200 Subject: baffling bug in this bit of code! References: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> Message-ID: <3D22FD0C.10509@mxm.dk> Daniel Jaeggi wrote: > if (y > max_y): > print "updating max_y" > max_y = y > Why does max_x get located and not max_y? Or, more specifically, why > does max_y get correctly updated in the first iteration and not > subsequently?! Are you shure you are not comparing apples and oranges here ??? erhh I mean strings and integers ... Ie. max_y = '8' y = 42 if (y > max_y): etc. Could be very confusing, and difficult to see in a printout. Try repr() to see if this is the problem. regards Max M From philippe.gendreau at savoirfairelinux.com Wed Jul 24 11:55:02 2002 From: philippe.gendreau at savoirfairelinux.com (Philippe Gendreau) Date: Wed, 24 Jul 2002 11:55:02 -0400 Subject: syntax questions Message-ID: <20020724115501.A19443@xmailer.ods.org> Hi! I'm fairly new to python and there a thing I don't understand in the syntax. What is it with the "_". I have seen it used in many places for what seems to be different puposes like: from x import _ Also, I'd like to understand this syntax: "((_(name),))" here's an example where it's used: # stuff a list for dir in os.listdir('/usr/share/themes'): row = self.theme.append ((_(dir),)) self.theme.set_row_data (row, dir) More precisely, what are the comma and underscore for? Thanks -- Philippe Gendreau From whisper at oz.net Thu Jul 18 21:11:17 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 18 Jul 2002 18:11:17 -0700 Subject: HTML DOM parser? In-Reply-To: <7x8z48czfd.fsf@ruckus.brouhaha.com> Message-ID: > The exception might be legitimate, because of the 403 error. Try > www.yahoo.com instead of www.nightsong.com. www.nightsong.com really > does return a 403. > -- Nope - it's the call to ie.document that chokes. ie.navigation does open www.w3.org just fine, but trying to get to the DOM isn't working. It looks like there's no attribute "document" for this interface... Dave LeBlanc From guillaume.rumeau at wanadoo.fr Thu Jul 4 11:26:36 2002 From: guillaume.rumeau at wanadoo.fr (Guillaume Rumeau) Date: 04 Jul 2002 17:26:36 +0200 Subject: gtk event handler Message-ID: <87n0t7wm37.fsf@wanadoo.fr> Hi, Please excuse me if I'm out of topic (but I don't think so). I would like to have a handler-function common for a lot of widgets (buttons). But my problem is I would like to know what widget produce the event I caught. For example, I have a handler-function : def on_button_clicked (source = None, event = None) : print "Button pressed" print str(source), dir(source) print str(source._o), dir(source._o) print str(event), dir(event) When any of the button are clicked, the result is that : Button pressed ['_o'] [] None [] My problem is I would like to have the reference to the button wich was clicked to make the adequat treatment, for example to change the label. I have probably missed something, but I don't see what (of course). Could you help me or let me pointed over the doc ? I know a bit more Tkinter, but not much gtk-python. Thank you for helping. -- GR From tim at bladerman.com Mon Jul 29 04:29:41 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Mon, 29 Jul 2002 08:29:41 GMT Subject: Guide to the python interp. source? References: <1027848147.20536.125.camel@vaio2> Message-ID: "Skip Montanaro" skrev i meddelandet news:mailman.1027890583.16934.python-list at python.org... > > >> I noticed, but thought that I just had missed it. I thought there > >> must be some where for such a large project. But the problem is > >> ofcourse ever present, "nobody likes to do documentation" > > Something occurred to me last night... How about a PyVM Wiki? Once the > content is there we could see about organizing it in a suitable form for > inclusion in the standard document set. > > I started things off with some notes I wrote a few months ago: > > http://manatee.mojam.com/pyvmwiki/ > To me this seems like a verry good idea. I will have a look at it when I come back home again in a few days and maybe post my thoughts. Thanks Tim From mgilfix at eecs.tufts.edu Wed Jul 24 17:51:18 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 24 Jul 2002 17:51:18 -0400 Subject: cmd, readline, and /path/filename completion In-Reply-To: <200207241627.04037.dcinege@psychosis.com>; from dcinege@psychosis.com on Wed, Jul 24, 2002 at 04:27:04PM -0400 References: <20020724140022.G10625@prim.han.de> <200207241627.04037.dcinege@psychosis.com> Message-ID: <20020724175117.B3904@eecs.tufts.edu> On Wed, Jul 24 @ 16:27, Dave Cinege wrote: > > More exactly, the OP needs to erase the '/' character from the delims list. > > e.g. > > > > readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>?') > > Yes! Thank you. Though I don't understand why this works...at least > I have some idea where to look in the readline docs. I began going through > them last night but didn't get much out of them. : P The readline library is sufficiently general such that it's meant to work on completion in a wide variety of situations. That obvious thing being said ( :) ), you need to tell readline what to consider as special tokens that it should use when divying up and understanding expressions. This tells it how to best sort out of the mess that is your expession and determine where the 'breaks' that you naturally consider to be the atomic words are. Maybe that makes sense? > > should work the way you want it. > > > > Are you implementing your own completion handler? > > I don't know if I going to need to. As I said I'm toying with this now. > > One thing still 'broken' is it will not complete against executables, in the > curdir or path. Can you comment on doing this? > > It does currently complete against builtin's, IE def do_XXXX(self,line): > methods. I once implemented an application where I wanted to complete against files in a 'current dir'. My solution was to gobble up a list of files in teh current directory (I assume you have that part down), and then set an attribute of "completion words". Now I wrote this particular app in Perl at the time, so I'm not sure if this attribute was specific to the Perl Readline module, but check if there's some sort of function that allows you to feed the readline module a list of words to check against when completing. Hope that helps you look in the right place. -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From tim.one at comcast.net Sun Jul 14 01:46:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 14 Jul 2002 01:46:56 -0400 Subject: sorting many arrays from one... In-Reply-To: Message-ID: [Jonathan Hogg] > Out of curiosity I took a look at the code and I could only think of one > optimisation: > > Index: listobject.c > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v > retrieving revision 2.114 > diff -r2.114 listobject.c > 775c775 > < args = Py_BuildValue("(OO)", x, y); > --- > > args = PyTuple_New(2); > 777a778,781 > > PyTuple_SetItem(args, 0, x); > > Py_INCREF(x); > > PyTuple_SetItem(args, 1, y); > > Py_INCREF(y); > > > This takes the difference between '.sort()' and '.sort(cmp)' for a list > of integers down from 6.5x slower to 4.5x slower on my machine > (300,000 element list). But the improvement is fairly marginal in my book > since, unless your comparison function is a C function, invoking the > bytecode interpreter makes it at least 10x slower (12x slower without > the above change). I've worked very much harder for very much less gain. Thanks! I checked in a variant of this (inside the core it's kosher to use the quicker PyTuple_SET_ITEM macro). > Beyond that I couldn't see much in the way of obvious changes > that could be made. It just fundamentally takes a non-zero amount > of time to make a PyObject_Call and if you make 5 million of them > in rapid succession then it adds up. It also adds up even if you do 5 million in slow succession . If your fingers are well-rested, get into a debugger and single-step through what happens when cmp gets called in this context. It's a revelation of apocalyptic dimension . From mh at esh-online.de Mon Jul 15 10:44:01 2002 From: mh at esh-online.de (Michael Hoffmann) Date: Mon, 15 Jul 2002 16:44:01 +0200 Subject: could not import mod_python.apache References: Message-ID: Uppps, sorry for this much postings, that OE6 with Error can't send, but it was sending, *great Billy* :-0 Michael From zbortolo at vt.edu Sat Jul 20 16:16:16 2002 From: zbortolo at vt.edu (Zachary Bortolot) Date: 20 Jul 2002 13:16:16 -0700 Subject: Renting CPU time for a Python script References: <25c15ddd.0207190852.2aecc26c@posting.google.com> Message-ID: <25c15ddd.0207201216.46eddd73@posting.google.com> Hi Fernando, Thanks for your very informative post! Unfortunately the bottleneck in my program lies with the PIL extension since I have to perform a lot of putpixel and getpixel operations, which are quite expensive in PIL. In the future I would like to rewrite sections of the code in C, but I have to admit that dealing with LibTiff greatly exceeds my C programming abilities. I really like your idea of building in restarting functionality, and I will add it when I get some free time. Thanks again! Zack Bortolot Fernando P?rez wrote in message news:... > Zachary Bortolot wrote: > > > Hello Everyone, > > > > I am a graduate student conducting research on using computer vision > > techniques to process digital air photos. As part of my research I am > > using a genetic optimization routine that I wrote in Python to find > > values for several key parameters. Unfortunately the genetic > > algorithm is quite CPU intensive, and each run requires anywhere from > > five to twelve days to complete on a 450MHz Pentium II. This is > > problematic since I have to run the program in a computing lab that is > > frequently used for teaching, which means that I am often unable to > > complete my runs. I would like to know if anyone has any suggestions > > on where I might go to rent CPU time that is Python and PIL friendly > > (the university I am at does have an AIX-based mainframe, but Python > > is not installed and users are only given 600k of disk space). Speed > > is not a major issue for me and the program does not use a lot of > > memory or disk space. However, stability is a definite must. Thanks > > in advance for any advice or suggestions! > > 5 to 12 days is a lot. Have you profiled this thing to find the bottlenecks? > At that point a few weeks spent on writing the time-critical parts in C would > be well spent time, I think. On the other hand if you've already optimized > this to death and 5 to 12 days is the best you can get, good luck. > > At any rate, any algorithm that takes that long to run should incorporate > checkpointing and restarting capabilities. That way if a machine crashes or > your lab stops your runs, you only lose a few hours of cpu time. If you can > save the state of the code in an object, you can even (using pickle) very > easily move a job from one machine to another in mid-run. The stability of > your environment should be a non-issue in terms of the survival of your runs. > > So I'd recommend: > > 1- code in automatic checkpointing and self-restarting abilities. It's fairly > easy to do, and saves a lot of headaches. > > 2- profile your code. See if there are bottlenecks in python left. Without > seeing your code I can't say, but if you have numerical bottlenecks, Numeric > might help. If not, look at weave (scipy.org). It's often enough and faster > than writing a full blown extension by hand. Pyrex is another option. Finally > writing the extension yourself isn't really that difficult, SWIG is pretty > good (weave can also help there quite a bit). > > 3- Once your code is optimized in C and self-restarting, you can distribute > runs over that lab without any problem. Just have your jobs get their state > from a server on the network so they can migrate automatically, and you > should be able to 'fire and forget'. With a central job manager keeping track > of what's been done, you can just set runs for a month and collect the > results at the end. > > Cheers, > > f. From maxm at mxm.dk Thu Jul 18 16:08:37 2002 From: maxm at mxm.dk (Max M) Date: Thu, 18 Jul 2002 22:08:37 +0200 Subject: Sorting list of objects on arbitrary attribute References: <3D36AD49.2020305@mxm.dk> Message-ID: <3D372045.9000303@mxm.dk> Fredrik Lundh wrote: > "Max M" wrote: >>If something like it isn't included in the standard library, how come? > "It's easier to write appropriate code from scratch in Python > than to figure out how to *use* a package profligate enough > to contain canned solutions for all common and reasonable > use cases." -- tim peters That's one side of the coin. The other one is that the standard library is like a common language, and the more of the language we share the easier it is to comunicate. I just found that this particular kind of code keeps showing up in so many other peoples code that it might be usefull enough to have a common implementation. Naturally there is a breaking point where something is general and usefull enough that it is worth adding to the library. The way it is now I just have to figure out how to use every single implementation that somebody do in their own code. Well it's not a big enough issue to raise a religious war over, I have made my own from scratch and will use that in my code ;-) regards Max M --------------------- Btw. I settled on this one instead: ----------- class sortClass: """ Sorts list on one or more attributes. If attribute is callable it sorts on the result """ def __init__(self, attributes, ignoreCase=1): self.attributes = attributes # list of attribute names self.ignoreCase = ignoreCase # ignore case of strings if true def _attrList(self, obj): # creates list of rendered attributes attrList = [] for attrName in self.attributes: attr = getattr(obj, attrName) if callable(attr): attr = attr() if self.ignoreCase and type(attr) == type(''): attr = attr.upper() attrList.append(attr) return attrList def __call__(self, obj1, obj2): return cmp(self._attrList(obj1), self._attrList(obj2)) if __name__ == '__main__': aList = SomeListWithObjects() sorter = sortClass(('name', 'age', 'rndNumber')) aList.sort(sorter) for item in aList: print item From brueckd at tbye.com Tue Jul 9 16:39:28 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 9 Jul 2002 13:39:28 -0700 (PDT) Subject: Why self? In-Reply-To: Message-ID: On Tue, 9 Jul 2002, Mark McEahern wrote: > > Tell you what. You're a smart guy (not sarcastic, I mean it). Why not > > apply your considerable knowledge to finding a solution to the issue of > > requiring "self." prefixes? It's apparent that lots of people would > > like to lose that requirement. I'm sure you can demolish my > > off-the-cuff suggestion at some point. I'm a bush-league amateur. But > > when you do that you will turn around to see that the issue itself is > > still there. What would you do? > > You say that lots of people would like to lose the requirement. My guess is > that's not true. It may appear true, since this topic does come up every so > often and the people who think it's a problem are often quite insistent > about it. > > What you don't see, of course, is all the people who are silent because > they're quite happy with self. prefixes And/or because they just got finished deleting all the messages from the last time this came up. <0.7 wink> > and consider this a pointless discussion usually kept alive by people > who refuse to learn the idioms of Python to their best advantage. Yup... the talk about finding a "solution" to the "issue" doesn't make sense to me because there is no issue or problem. It's like trying to find a "solution" to the no-block-delimiter "issue". -Dave From jdavis at empires.org Fri Jul 26 22:16:36 2002 From: jdavis at empires.org (Jeff Davis) Date: Sat, 27 Jul 2002 02:16:36 GMT Subject: performance problem in python 2.2 References: <260720021725073781%mday@apple.com> <7xbs8uymgw.fsf@ruckus.brouhaha.com> Message-ID: <8on09.28215$_M2.10279705@twister.socal.rr.com> Paul Rubin wrote: > Fernando Perez writes: >> Out of curiosity, why does this happen? I understand looking up >> global variables when in a function being expensive, since you first >> must go through the local dict (and fail). But when the code is >> itself global and there's no other scope in sight, why is it any >> slower? In a sense, for global code 'everything is local', so I >> don't quite understand why the difference. > > Global variables are accessed by a dict lookup in the global environment. > Local variables are accessed by looking directly at the appropriate > slot in the local stack frame. Ahh... more good information! Thanks so much, and to Tim as well for pointing that out initially. I've learned a lot about python today :) Regards, Jeff From flognat at flognat.myip.org Thu Jul 18 06:48:12 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Thu, 18 Jul 2002 10:48:12 GMT Subject: Problem importing in a cgi script References: Message-ID: / "Justin Shaw" wrote: | I printed out the tb info to help troubleshoot: | Traceback (most recent call last): | File "gnuplot_cgi.py", line 4, in ? | import cgi | ... | ... | File "/usr/local/lib/python2.2/socket.py", line 41, in ? | from _socket import * | Import Error: ld.so.1: /usr/local/bin/python: fatal: libgcc_s.so.1: open | failed: Seems like you need to either recompile your python, or install gcc on the new system. /Andy -- The eye of the beholder rests on the beauty! From Christopher.Saunter at durham.ac.uk Tue Jul 9 05:31:11 2002 From: Christopher.Saunter at durham.ac.uk (Christopher Saunter) Date: Tue, 9 Jul 2002 09:31:11 +0000 (UTC) Subject: Multi-threading on Multi-CPU machines References: Message-ID: Garry Taylor (gtaylor at lowebroadway.com) wrote: : Hello, : I am attempting to make a multi-threading function in one of my : programs in an effort to gain a speed increase, but I'm getting quite : the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten : me as to why, my code is below: Hi Gerry, As other people have said, 'native' Python code does not bennefit from multiple CPUs in one PC due to the GIL. Depending on what you are doing with your threads, you may be able to utilise more then one processor by splititng the threads into multiple programs, running them simultaneously and communincating between them somehow (MPI etc...) - from what I have seen it requires a little more effort, but can work well. This is mainly usefull for 'number crunching' threads etc. --- cds From skip at pobox.com Tue Jul 30 17:45:09 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Jul 2002 16:45:09 -0500 Subject: decoding XML-ified special chars such as " In-Reply-To: References: Message-ID: <15687.2277.746983.517030@localhost.localdomain> chris> from xml.sax.saxutils import escape chris> data = escape(orig_data) That goes the wrong way. I think the OP wanted to go from '"' to '"', not the other way around. chris> ... you might get by using urllib.unquote(data) That's for unquoting stuff that's been escape for inclusion into URLs, also not what the OP asked for. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From brueckd at tbye.com Wed Jul 10 12:00:19 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 10 Jul 2002 09:00:19 -0700 (PDT) Subject: Why self? In-Reply-To: <3D2B5331.7090104@onsitetech.com> Message-ID: On 9 Jul 2002, Robb Shecter wrote: > And, it according to consensus in this thread, this: > > >> > >> self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) > >> > > should really be written like this: > > self.__y = self.__x**2 * self.__t/self.__z + self.__a * FFT(self.__tseries) > > to be safe from accidental overwriting by subclasses. Only in theoretical la-la-land, because in practice that's overkill. When I first learned about the double-underscore-means-private syntax I adopted the philosophy of "I'll start to use that everywhere as soon as not using it gets me into trouble", and that hasn't happened yet. Occasionally I'll make some variable private, but I've yet to see anything that suggests doing it most of the time is a best practice. -Dave From cliechti at gmx.net Tue Jul 23 16:23:39 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 22:23:39 +0200 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: Mack wrote in news:ahkcj0$gcg$1 at green.tninet.se: >> That's a list comprehension, which wasn't available in 1.5.2. I think it >> first appeared in 2.0. Upgrading to a more recent Python version should >> fix this. > > Thanks. I just checked out the doc Whats new in 2.0 and found it. I > didn't think my redhat 7.1 was that old. I'll just upgrade then. i think they just have the default to python 1.5.2 either you can type python2 or python21 to get the new one. maybe you need to install another RPM, but chances are good that both are installed parallel. chris -- Chris From jonathan at onegoodidea.com Tue Jul 2 09:14:19 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 02 Jul 2002 14:14:19 +0100 Subject: New style classes as exceptions (Was: exception handing) References: <7V%T8.69851$F16.33443@atlpnn01.usenetserver.com> Message-ID: On 2/7/2002 12:44, in article bmgU8.84321$F16.2494 at atlpnn01.usenetserver.com, "Steve Holden" wrote: > I'm sure they'd welcome a patch on python-dev ;-) and I believe it's > Guido's intention that new-styles will eventually include Exception. In > fact, new-style classes will probably be all there is eventually Yeah, I know: Show Me The Code ;-) I'll add it to my list :-) Jonathan From martin at v.loewis.de Wed Jul 31 02:49:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Jul 2002 08:49:45 +0200 Subject: pyexpat error References: <3D471345.B373E240@orsys.com> Message-ID: Doug Stuart writes: > I am attempting to compile python with the Expat library included. I am > running Solaris 7 and python 2.2.1. Originally, I did the > 'configure-make dance' for python, then was told that I needed to add > the Expat library. I did the 'configure-make dance' for Expat (version > 1.95.4). I then went to redo my python doing a configure, make clean > and make. During the build of the pyexpat extension I get an warning > from line 1518 of Modules/pyexpat.c saying that subscript has type > char. It then removes the library because 'an error occurred." In the > setup.py script there is a setting for the EXPAT_DIR. I have tried > setting that to the directory where the Expat source files are located > and to the location of the library the Expat install creates. > > What am I missing here? Precise bug reporting. When it said 'an error occurred' - what precisely did it say? Could it be the case that you have compiled Expat as a shared library, and that your operating system won't find that shared library because the shared library is in /usr/local/lib? In that case, you need to set LD_LIBRARY_PATH, or apply one of the other 4 strategies to make Solaris find shared libraries. Regards, Martin From m.laranjeira at datacraft.com.br Tue Jul 16 17:15:34 2002 From: m.laranjeira at datacraft.com.br (Marcus Vinicius Laranjeira) Date: Tue, 16 Jul 2002 18:15:34 -0300 Subject: Dictionaries In-Reply-To: <20020716085041.A11455@glacier.arctrix.com> References: Message-ID: <5.1.1.6.0.20020716180826.00a08690@imap.datacraft.com.br> Hi folks, I got a big doubt... how python manages data in dictionaries ? for example: Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> dic = { 'R1': 1} >>> dic {'R1': 1} >>> dic['R2'] = 3 >>> dic {'R1': 1, 'R2': 3} >>> dic['R4'] = 2 >>> dic {'R4': 2, 'R1': 1, 'R2': 3} >>> I created a dictionary with one key 'R1' and a value of 1. Then, I inserted a new item with a key 'R2' and a value of 3... It worked like I though it would: appended the new item at the end of the dictionary. But why when I insert a new item with a key 'R4' and a value of 2 it inserts it in the begining of the dictionary ???????? How can I change the order of the items in a dictionary !?!?!? Thanks a lot, Marcus From cliechti at gmx.net Sat Jul 13 19:46:51 2002 From: cliechti at gmx.net (Chris Liechti) Date: 14 Jul 2002 01:46:51 +0200 Subject: Print a traceback from an extension? References: Message-ID: gb at cs.unc.edu wrote in news:u1ya7cj4b.fsf at cs.unc.edu: > Can I print a traceback from within a extension written in C? > > I know we're supposed to just keep returning NULL until we make it > back to the main loop. That normally works fine. > > But I'm calling Python code from a callback that is called by C > code. The Python code fails so PyEval_CallObject returns NULL. I want > to provide a helpful message at that point. > > Can this be done? If so, can someone suggest where to look for an > example? PyErr_Print() for example. look here whats possible otherwise: http://python.org/doc/current/api/exceptionHandling.html chris -- Chris From whisper at oz.net Tue Jul 9 19:42:58 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 9 Jul 2002 16:42:58 -0700 Subject: A better self In-Reply-To: <3D2B6EFB.4DA9A4DB@alcyone.com> Message-ID: Except, of course, "self" is not the name of the first argument, it's merely the identifier most often used for the first argument. This is essentially the same as the posted example: class foo: def __init__(this, me, me2, me3): this.a = me this.b = me2 this.c = me3 def bar(this): print this.a, this.b, this.c b = foo("ba", "bb", "bc") b.bar() I have no problem with "self" (or whatever) being equivelent to a leading '.', but '..' would be confused with "up directory" syntax of U*x - although it's tempting to suggest it as an alternative for global . I'm not sure what you meant by ".attribute should have an extra space...". David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Erik Max Francis > Sent: Tuesday, July 09, 2002 16:17 > To: python-list at python.org > Subject: Re: A better self > > > David LeBlanc wrote: > > > I notice that in every discussion of self, there's always a '.' in > > there. > > So, why not make a leading '.' mean self? AFAIK, it's otherwise > > currently > > illegal. The only drawback that I can think of is that it's less > > visible as > > a first argument for class defs. > > > > class foo(): > > def __init__(., me, me2, me3) > > .a = me > > .b = me2 > > .c = me3 > > def fee(.) > > print .a, .b, .c > > def bar(.) > > .fee() > > This doesn't totally revolt me, but I would prefer that the "self" > argument still be an explicit self: > > def __init__(self, me, me2, me3) ... > > so that the notation `.attribute' is just a shortcut for > `self.attribute'. Having the "self" argument written as . suggests that > accessing an attribute in it should involve an extra space, e.g. > `..attribute' which is clearly not what you meant. > > `self' as the name of that first argument is already so entrenched it's > really hard to come up with reasonable arguments about replacing it. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ See the son in your bad day / Smell the flowers in the valley > \__/ Chante Moore > Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ > A personal guide to Aliens vs. Predator 2. > -- > http://mail.python.org/mailman/listinfo/python-list From emile at fenx.com Wed Jul 10 07:52:56 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 10 Jul 2002 11:52:56 GMT Subject: expect module and/or functionality? Or SSH wrapper module? References: Message-ID: Michael Hudson > Cameron Laird > > If not, no, you can't Expect with pure Python; there's no > > practical way to get the pseudoterminal munging right without > > calls into the C run-time library that Python itself can't > > access. > > Huh? You have openpty, forkpty, ioctl, setsid, setpgrp, ... what more > do you need? > Only those... but also on win32, which would be the advantage of a pure python solution independent of platform. -- Emile van Sebille emile at fenx.com --------- From K.Rdt at TU-Berlin.DE Wed Jul 10 13:47:32 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Wed, 10 Jul 2002 19:47:32 +0200 Subject: HT download from activstate? Message-ID: --------------------------------------------------------------------- Hi I tried to get the python-module for ping, but run in a circle. What's my mistake? tia K at Rdt --------------------------------------------------------------------- From jonathan at onegoodidea.com Thu Jul 4 07:02:39 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 12:02:39 +0100 Subject: replacing instance __setattr__ References: Message-ID: On 4/7/2002 10:24, in article D1NxKLAkRBJ9Ew3i at jessikat.demon.co.uk, "Robin Becker" wrote: > well it seems Python not as dynamic as I believed. The object is > searched last which seems completely counter-intuitive to me, but there > you go. It makes sense when you think about it. The special __*attr__ methods are the mechanism by which one searches the instance and class dictionaries. You can't get to the instance dictionary without going through one of these methods first. When you do: >>> foo.bar it roughly translates in the interpreter to: >>> type(foo).__getattr__('bar') The default __getattr__ method (the one in 'object') looks something like (again, using Python pseudo-code - it's actually all C): def __getattr__( self, name ): if name in self.__slots__: index = self.__slots__.index( name ) return contents_of_slot( self, index ) elif has_dict(self) and name in self.__dict__: return self.__dict__[name] elif name in self.__class__.__dict__: return self.__class__.__dict__[name] else: raise AttributeError( "... no attribute '%s'" % name ) The __*attr__ methods aren't actually found through the class dictionary, they are stored in special slots in the type object and hit directly. The type of an object is about the only thing you can reliably query. Every object is guaranteed to have a type. So the interpreter always asks the type any complicated questions about an object, such as: please retrieve the following attribute. [Anyone feel free to jump in and correct my rather loose explanation of the internals.] Jonathan From heikowu at ceosg.de Mon Jul 29 12:28:18 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 29 Jul 2002 18:28:18 +0200 Subject: Newbie: How to touch "global" variables In-Reply-To: <3D4568D5.3254F968@lmco.com> References: <3D4568D5.3254F968@lmco.com> Message-ID: <1027960098.2942.5680.camel@d168.stw.stud.uni-saarland.de> Hi Jeff! On Mon, 2002-07-29 at 18:09, Jeff Layton wrote: > I want a module to be able to "touch" a variable defined > globally (from the main script). I don't necessarily want > to change the value ofthe variable, but to query it. For > example, get the length. How do I do this? You mean accessing a variable that is defined in another module? Just put the variable into the other modules scope by setting it. If you want to keep the two variables synchronized, use a list. Changing the list in one module changes the other modules list too. Example: ---------- main.py: # Define variable. x = ["hello"] # Import submodule and post variable to that scope. import sub1 sub1.x = x # Run sub1.print_x() sub1.print_x() # Change x. sub1.change_x() print x ---------- sub1.py: def print_x(): global x # Unnecessary I think...? print x def change_x(): global x # Unnecessary I think...? x[0] = "welcome" ---------- It will happily output (untested... ;p): ["hello"] ["welcome"] btw. Globals are actually a _nono_ for me! Better pass that parameter to functions or create a (sort of) module initializing function which you call from the base module after having imported the submodule, and passing in the parameter you wish to set (instead of changing namespaces directly). And better use classes anyway... ;) Hope this helps! Heiko W. From Christopher.Cox at honeywell.com Wed Jul 31 21:23:51 2002 From: Christopher.Cox at honeywell.com (Chris) Date: 31 Jul 2002 18:23:51 -0700 Subject: for loops longer on a P-IV??? Message-ID: <13bf971.0207311723.bbc3da@posting.google.com> I previously posted an oddity with what I thought to be a problem with the win32api.Sleep() function on a P-IV system. After some more investigation, it looks like the for loop we use in our function is causing a significantly larger amount of time to execute on out P-IV system than on our P-III system. This is our wait function: def wait(Seconds): loop = Seconds * 50 for i in range (0,loop): win32api.Sleep(20) if win32ui.PumpWaitingMessages(0,-1): win32api.PostQuitMessage() raise exceptions.SystemExit A 10 second wait on our P-IV seems to take 15 seconds as shown by the following miniscule test: import time import win32api def test(sec): print time.clock() wait(10) print time.clock() The results were consistently 50% longer than expected. I removed the if clause and it's statements and found the same result. I then rewrote the wait function as follows: def wait(second): win32api.Sleep(1000 * second) Running the test again with the updated version of the wait function, I got expected results of 10 second waits. I haven't tried using a while loop instead of the for loop yet, so I'm not sure if this applies to all loops or just the for construct. Am I missing something blatantly obvious, or is there some known issue with the way the P-IV optimizes code at runtime? From chris_mk at hotmail.com Tue Jul 30 17:28:51 2002 From: chris_mk at hotmail.com (Christopher) Date: 30 Jul 2002 14:28:51 -0700 Subject: decoding XML-ified special chars such as " References: Message-ID: Hey Gabe, Well, I'll assume that you have PyXML (really a must if you are going to do anything with XML in Python). If that is right, here you are... from xml.sax.saxutils import escape data = escape(orig_data) and there you are. Otherwise, you might get by using urllib.unquote(data). Hope that help. Chris "Gabe Newcomb" wrote in message news:... > Is there a module to take strings such as ", & and turn them > into the characters they normally represent (', &)? > > Gabe Newcomb > Software Test Automation Engineer > 425.372.2732 > Noetix Corporation > www.noetix.com > > after years of waiting, nothing came From aoeu at go.com Sun Jul 7 15:33:12 2002 From: aoeu at go.com (Thinkit) Date: 7 Jul 2002 12:33:12 -0700 Subject: the meaning of life Message-ID: <3eeda89d.0207071133.4c07a86e@posting.google.com> Take a break from python and realize the meaning of ALL conscious beings. MEANING --The meaning of a conscious being is to pursue one of two goals. Among the criteria listed below, only LOVE part 2 is achievable. In each goal, conscious beings: 1. Control reality. 2. Know reality. 3. Have mastery of potential reality. 4. Have mastery of the abstract plane. LOVE: 1. Exactly two conscious beings exist for all time and space. 2. A seed of love binds the two. POWER: 1. Exactly one conscious being exists for all time and space. From me at somewhere.com Mon Jul 29 19:38:34 2002 From: me at somewhere.com (Benji) Date: Mon, 29 Jul 2002 19:38:34 -0400 Subject: pretty basic: get variable name from list of strings? References: Message-ID: <3D45D1FA.2090800@somewhere.com> chris wrote: > in the specific, > > if I have a list > > animals = ['horse_0', 'horse_1'] > horsenames = ['smokey', 'silver'] > > how do assign variables with those strings as names? > > ie, I want > horse_0 = "smokey" > horse_1= "silver" > > but if I write animals[0] = "smokey", it replaces the value, it > doesn't assign it. What I want is like assign() or eval() in other > languages. > > you can imagine i am trying to iterate over large indexes of > animals[i] = 'horse_' + str(i) > and then assign them from a value list > > or even screw the variable list and instead iterate over the > value list > 'horse_' + str(i) = horsenames[i]. > > but i'm missing the key command to tell python "treat this string like > code and not a string." > > thx, > chris As Andrew pointed out, you probably would be better off using a dict, but if you must use variables, you could use the "globals" and "vars" builtin functions which both return a dict of objects and variables respectiveley. I'm not sure how they differ, but "vars" may return the dict of variables from the local namespace... ie: if you're in a function, "vars" may return the local variables while globals returns the global variables. This is just a guess though, anywy, here's how you could do it: vars()['horse_' + str(i)] = horsenames[i] or globals()['horse_' + str(i)] = horsenames[i] Again though, you should look into using a dict =), benji From fredrik at pythonware.com Sat Jul 27 03:48:47 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 07:48:47 GMT Subject: Two RE proposals References: Message-ID: David LeBlanc wrote: > 1. Add a substitution operator - in the example below it's "!<..>" > > word = r"\w*" > punct = r"[,.;?]" > wordpunct = re.compile(r"!!") > > The re compiler sees r"\w*[,.;?]" > Trivial example, but for fancier patterns it would be great IMO. > A substitution pass should be done over the substituted text for nesting: python already has string substitution. if it needs better string substitution, that should be solved outside the RE engine. besides, having library modules peek in your local namespace is really bad style. and your proposal will break existing code. ::: the following approach works in all existing versions of Python, gives you syntax highlighting in all existing Python editors, etc: def i(*args): return string.join(map(str, args)) word = r"\w*" punct = r"[,.;?]" wordpunct = re.compile(i(word, punct)) if = r"if" term = r"something" num = r"\d*" op = r"[-+*/]" factor = i(num, "\s*", op, "\s*", num) expr = i(term, factor) if_stmt = re.compile(i(if, "\s*\(?\s*", expr, "\s*\)?\s*:")) if you're doing lots of RE stuff, you can trivially extend this to support RE-oriented operations: if = literal("if") op = set("-+*/") factor = seq(num, ws, op, ws, num) (google for "rxb" for a complete implementation of that idea) > 2. Make r"(a|b)*" mean any number of a's or b's. it does mean any number of a's or b's. but no more than a single a or b will end up in the group. > This doesn't work, at least in some situations with the current > re compiler - the "any" op "*" doesn't seem to span over a parened > group for i in range(20): s = file.read(1) doesn't give you a 20 character string either (nor a 20 item list) fixing the read statement is of course trivial. fixing the RE is done in a similar fashion: make sure the group matches everything you want to put in the group: r"((?:(a|b)*)" if you want lists of matching things, use findall. From jdhunter at nitace.bsd.uchicago.edu Mon Jul 15 13:29:39 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Jul 2002 12:29:39 -0500 Subject: Generating .py from a .pyc: is it possible? References: Message-ID: >>>>> "Gabe" == Gabe Newcomb writes: Gabe> I screwed up and deleted a python script of mine. I still Gabe> have the compiled version, the .pyc. Is there anyway for me Gabe> to regenerate the .py from it, so I make changes? Try http://www.goebel-consult.de/decompyle From shagshag13 at yahoo.fr Thu Jul 25 10:44:09 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 25 Jul 2002 16:44:09 +0200 Subject: xml processing : too slow... References: Message-ID: > p.parse('%s' % line, 1) > > should be satisfactory for checking this kind of "sort of > well-formedness", unless there are yet more specs as yet > unexpressed. that's why i had done : >>> anotherline = '' + line + '' >>> p.Parse(anotherline, 1) Traceback (most recent call last): File "", line 1, in ? p.Parse(anotherline, 1) ExpatError: junk after document element: line 1, column 0 but it still don't work, as much has: >>> p.Parse('%s' % line, 1) Traceback (most recent call last): File "", line 1, in ? p.Parse('%s' % line, 1) ExpatError: junk after document element: line 1, column 0 > How would that help you diagnosed e.g. > of course not > as not being well formed? This is not well formed because > it lacks quotes around an attribute's value. Or: > &either > now THIS is not well formed because reference '&either' > is not terminated with a semicolon. Etc, etc. that's right i didn't address this kind of thing... :( > But _we_ can't know, unless you DO tell us the specs. that's was the meaning of my example : anything among words, numbers, punctuations and some symbols like $. space are separators. don't have entities like &entities; or consider it like a simple word. thanks, s13. From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 07:19:20 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 04:19:20 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D281526.6000007@ob_scure.dk> Message-ID: <7x1yafokef.fsf@ruckus.brouhaha.com> Thomas Jensen writes: > Yes and no. In my estimate, the primary reason for the slowness of the > current job is inefficient dataaccess and datahandling. > A few examples: > * Using "SELECT TOP 1 value FROM T_MyTable ORDER BY value DESC" to get > maximum value. > * linear seraches > * LOTS of SQL calls returning only oe row > > When the job was originally written a lot of factors were not known > and, well, it did it's job. > However now the amount of data requires better performance. It sounds like your applciation would speed up a lot by judiciously adding some indices to your tables. Talk to your DBA. > >>* Improved scalability - parallel processing on multiple > > machines/CPUs This might be more easily accomplished with Java, > > depending on exactly how you intend to implement it. Java is > > probably the best tool for distributed processing; in particular > > JINI is ideal for this kind of thing. > > I Don't know much Java I must admit. However for my needs I belive > XMLRPC will do just fine. It doesn't sound to me like you need anything like this. Reorganizing your database may completely solve your problem. From aleax at aleax.it Thu Jul 25 10:16:48 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 14:16:48 GMT Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> <3D40066E.2090809@mxm.dk> Message-ID: Max M wrote: > Alex Martelli wrote: > >> Therefore, I find your criticism totally unfounded. > > I beg to differ Sire! > > To understand the error message you need to understand the > implementation of the module. One of the reasons for having modules and > encapsulation is to minimize the need to know implementation details. To understand an error message that tells you that the argument you supplied, of type X, lacks attribute Y, you need to infer that part of the preconditions is that your argument MUST supply an attribute Y (there may be others, of course -- e.g., here, Y must be callable with two arguments, and return an object such that, etc, etc, but that's beside the point). > The message "Argument must be a string", while not technically correct, > is far easier to understand and in line with the Docs where argument 's' > is defined as a string. The docs lie, or, to be more accurate, they use ellipsis: most of the time they state something "must be an Y", they mean "must mimic a Y well enough for this function's use". When you want to mimic "well enough", you need accurate error messages telling you what went wrong (if anything) with your mimickry attempts. *Otherwise* you would need to study the library's sources, presumably just in order to acquire exactly those implementation details that you CLAIM you don't want to know. >>> print cgi.escape.__doc__ Replace special characters '&', '<' and '>' by SGML entities. Given THIS doc, and accidentally its appropriate use of the verb 'replace', I can't agree with criticism about "missing replace attribute" reminders in errors when you DO supply objects on which replace can't work. Alex From fperez528 at yahoo.com Fri Jul 26 18:19:46 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 16:19:46 -0600 Subject: extract elements of n char from a list References: Message-ID: Alex Martelli wrote: > Tim?Peters'?introduction > to the Algorithms chapter of "Python Cookbook" (the printed edition > that O'Reilly just launched) is invaluable in showing you exactly > how to perform such little benchmarks for accuracy and solidity. Well, partly in honor to the quality of your posts here I went ahead and purchased the Cookbook. It will make for nice reading, I look forward to enjoying it. However, I'd like to mention a _minor_ inaccuracy in the text you refer to by Tim. He says that on Unix machines, time.clock() returns the user time from your process. Technically that's not 100% true, as it returns the sum of (user+system) time consumed by your process. The clock.c sources confirm this (from glibc-2.2.5): /* Return the time used by the program so far (user time + system time). */ clock_t clock () { struct tms buf; if (__times (&buf) < 0) return (clock_t) -1; return buf.tms_utime + buf.tms_stime; } I know it's a minor point, but it may be worth noting if you are trying to do careful timings. The benchmark package I noted in my previous post implements 4 separate clocks to deal with this, allowing you to time - user - system - user+system - like time.clock() - user&system separately, returned in a tuple. It provides an interface for doing timings with repeated calls and averaging, and any one of the 4 above mentioned clocks. Just a minor point. Cheers, f. From yduppen at xs4all.nl Sun Jul 28 08:58:54 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Sun, 28 Jul 2002 14:58:54 +0200 Subject: TAB completion References: Message-ID: <3d43eeb4$0$12280$e4fe514c@dreader4.news.xs4all.nl> > My problem is: How can I call the default completion function that > comes with the python distribution? I think you should use the rcompleter module. YDD -- .sigmentation fault From mfranklin1 at gatwick.westerngeco.slb.com Fri Jul 12 11:13:45 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 12 Jul 2002 15:13:45 +0000 Subject: Pmw.Counter and Pmw.ScrolledCanvas questions In-Reply-To: <18692175.0207111554.4f09fac@posting.google.com> References: <18692175.0207102141.1d5279c1@posting.google.com> <18692175.0207111554.4f09fac@posting.google.com> Message-ID: <200207121417.g6CEHW711859@helios.gatwick.geco-prakla.slb.com> On Thursday 11 Jul 2002 11:54 pm, John McMonagle wrote: > > As for the ScrolledCanvas are you using the .scale() canvas method. If > > so the call looks somthing like > > > > mycanvas.scale("ALL", xorigin, yorigin, xscale, yscale) > > > > and setting xorigin and yorigin to the top left points from you 'zoom > > box' should do what you want, to get those I would bbox the rectangle I > > guess you are drawing when they do the button-3-press-move-release dance. > > Oh and don;t forget to call resizescrollregion() after zooming. > > > > This is an example that seems to work (for me!) > > Thanks for those suggestions Martin. > > Unfortunately I'm not using the scale method to zoom. I actually need > to redraw all the canvas objects because I'm mapping canvas xy coords > to eastings/northings on a map. So, from the size of the zoom box I > calculate a new scale factor at which to draw my map, I draw my map, > then I want the canvas to be scrolled to the point where the zoom box > began. > > What I've got now is my map is correctly drawn after the zoom box drag > but it's starting position is at the top left of the scrolled canvas. > After drawing items on a scrolled canvas and resizing the scrolled > region how do you programatically scroll the canvas to a desired > point. > > Any ideas ? Take a look at the Canvas '*view' methods and set their position. from pydoc Tkinter.Canvas | xview(self, *args) | Query and change horizontal position of the view. | | xview_moveto(self, fraction) | Adjusts the view in the window so that FRACTION of the | total width of the canvas is off-screen to the left. | | xview_scroll(self, number, what) | Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT). | | yview(self, *args) | Query and change vertical position of the view. | | yview_moveto(self, fraction) | Adjusts the view in the window so that FRACTION of the | total height of the canvas is off-screen to the top. | | yview_scroll(self, number, what) | Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT). Cheers From martin at strakt.com Mon Jul 8 09:24:21 2002 From: martin at strakt.com (Martin =?ISO-8859-1?Q?Sj=F6gren?=) Date: 08 Jul 2002 15:24:21 +0200 Subject: PKSC1 In-Reply-To: <200207081520.35063.b.maryniuk@forbis.lt> References: <200207081520.35063.b.maryniuk@forbis.lt> Message-ID: <1026134661.5486.0.camel@ratthing-b3cf> m?n 2002-07-08 klockan 15.20 skrev Bo M. Maryniuck: > On Monday 08 July 2002 14:27, Alex Martelli wrote: > > Assuming you mean PKCS1 (as per RFC 2437) > > Yes, exactly that. Sorry. ;-) There's always a race condition between your fingers while typing 'pkcs' isn't there? :-) Martin -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From marklists at mceahern.com Thu Jul 25 16:54:41 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 25 Jul 2002 15:54:41 -0500 Subject: Completion in emacs mode In-Reply-To: Message-ID: > Given that we are now in dodgy waters, is there an alternative to this > route? (perhaps post a complete version of the extension here :-) ;;; new-dabbrev.el --- dynamic abbreviation package ;; Copyright (C) 1985, 1986 Free Software Foundation, Inc. ;; Copyright (C) 1993, Lars Lindberg ;; Author: Don Morrison ;; Maintainer: Lars Lindberg ;; Created: 16 Mar 1992 ;; Version 3.0 ;; Keywords: abbrev expand completion ;; This file is NOT part of GNU Emacs. ;; GNU Emacs is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2, or (at your option) ;; any later version. ;; GNU Emacs is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs; see the file COPYING. If not, write to ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. ;;; Commentary: ;; The purpose with this package is to let you write just a few ;; characters of words you've written earlier to be able to expand them. ;; ;; To expand a word, just put the point right after the word and press ;; M-/ (dabbrev-expand) or M-C-/ (dabbrev-complete). ;; ;; There are powerful things in this package that aren't turned on by ;; default. I recommend you to do the following. ;; ;; Put the following 2 lines in your .emacs file: ;; (setq-default dabbrev-always-check-other-buffers t) ;; (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_") ;; ;; Dabbrev will now search in all buffers with the same major mode ;; for your expansions. It will also search for complete symbols, ;; the old dabbrev package only looked half-heartedly for symbols. ;; ;; You might also consider setting ;; (setq dabbrev-upcase-means-case-search t) ;; to get automatic case se-upcase-means-case-search t) ;; to get automatic case sensitive search when your abbreviation ;; contains uppercase characters. ;; ;; Check out customization below to learn about all the features ;; of this package. ;;; Change Log ;; 3.0 1993-12-09 ;; Freshed things up for the release. ;; 'dabbrev-completion' now doesn't have to use the minibuffer. ;; Thanks Alon Albert . ;; 2.3 1993-12-07 Lars Lindberg ;; 'dabbrev-abbrev-char-regexp' nil means old dabbrev style of ;; searching. ;; Added installation and customization commentary. ;; 2.2 1993-12-04 Lars Lindberg ;; Added 'dabbrev-upcase-means-case-search', which makes usage of ;; case-fold-search and case-replace customizable. ;; Added 'dabbrev-abbrev-char-regexp' for customizing the definition ;; of an abbreviation. ;; Requires "picture" when compiling. ;; Minor bug. ;; 2.1 1993-12-04 Lars Lindberg ;; Now doesn't consider the word that point is at, but rather ;; the symbol, also searches for symbols. ;; Works better with undo. ;; Now searches as if case-fold-search was nil when the ;; abbreviation contains at least one uppercase character. ;; Made it faster by just putting the extra found characters ;; in 'dabbrev--last-table', not the whole word. ;; Corrected bugs. ;; 2.0 1993-12-02 Lars Lindberg ;; Searches in other buffers for the expansion. ;; Works also for the minibuffer. ;; Added 'dabbrev-completion'. ;; More efficient code. ;; Found minor bugs. ;; 1.0 converted to Emacs Lisp by Spencer Thomas. ;; Thoroughly cleaned up by Richard Stallman. ;; 0.0 ;; DABBREVS - "Dynamic abbreviations" hack, originally written by ;; Don Morrison for Twenex Emacs. Converted to mlisp by Russ Fish. ;; Supports the table feature to avoid hitting the same expansion on ;; re-expand, and the search size limit variable. ;; Known bugs and limitations. ;; - Possible to do several levels of 'dabbrev-completion' in the ;; minibuffer. ;; ;; Future enhancements ;; Check the tags-files? Like tags-complete? ;;; Code: (provide 'new-dabbrev) (require 'cl) ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Customization variables ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- (defvar dabbrev-backward-only nil "*If non-NIL, `dabbrev-expand' only looks backwards.") (defvar dabbrev-limit nil "*Limits region searched by `dabbrev-expand' to this many chars away.") ;; I recommend that you set this to t, at least in programming modes. (defvar dabbrev-upcase-means-case-search nil "*The significance of an uppercase character in the abbreviation. nil = Doesn't affect the search, but preserves the case when replacing. t = The search becomes case-sensitive and the replace is exact. This variable is buffer-local.") (make-variable-buffer-local 'dabbrev-upcase-means-case-search) ;; I recommend that you set this to "\\sw\\|\\s_" (defvar dabbrev-abbrev-char-regexp nil "*A regexp that recognizes a character in an abbreviation or an expansion. Will be surrounded with \\\\( ... \\\\) when used. Set this to \"\\\\sw\" if you want ordinary words or \"\\\\sw\\\\|\\\\s_\" if you want symbols. You can also set it to nil if you want old-style dabbrev searching (the abbreviation is from point to previous word-start, the search is for symbols. The recommended value is \"\\\\sw\\\\|\\\\s_\".") ;; I recommend that you set this to t. (defvar dabbrev-always-check-other-buffers nil "*Should \\[dabbrev-expand] look in other buffers?\ nil = Don't look in other buffers.\n\ t = Look in other buffers.\n\ Otherwise ask the user if he want's to look in other buffers. The recommended values is t.") ;; I guess setting this to a function that select all C- or C++- ;; mode buffers wouldunction that select all C- or C++- ;; mode buffers would be a good choice for a debugging buffer, ;; when debugging C- or C++-code. (defvar dabbrev-friend-buffer-function 'dabbrev--same-major-mode-p "*A function that determines which buffers that should be searched. The function should take one argument, OTHER-BUFFER, and for instance compare it with the current buffer to decide if it's suitable for searching in. Have a look at 'dabbrev--same-major-mode-p' for an example. This variable is buffer local.") (make-variable-buffer-local 'dabbrev-friend-buffer-function) ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Internal variables ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;; Last obarray of completions in 'dabbrev-completion' (defvar dabbrev--last-obarray nil) ;; Table of expansions seen so far (defvar dabbrev--last-table nil) ;; Last string we tried to expand. (defvar dabbrev--last-abbreviation nil) ;; Location last abbreviation began (defvar dabbrev--last-abbrev-location nil) ;; Direction of last dabbrevs search (defvar dabbrev--last-direction 0) ;; Last expansion of an abbreviation. (defvar dabbrev--last-expansion nil) ;; Location the last expansion was found. (defvar dabbrev--last-expansion-location nil) ;; The list of remaining buffers with the same mode as current buffer. (defvar dabbrev--friend-buffer-list nil) ;; The buffer we looked in last. (defvar dabbrev--last-buffer nil) ;; The buffer we last did a completion in. (defvar dabbrev--last-completion-buffer nil) ;; Same as dabbrev-always-check-other-buffers, but is set for every expand. (defvar dabbrev--check-other-buffers dabbrev-always-check-other-buffers) ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Macros ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Get the buffer that mini-buffer was activated from (defsubst dabbrev--minibuffer-origin () (car (cdr (buffer-list)))) ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Exported functions ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;;###autoload (define-key esc-map "/" 'dabbrev-expand) ;;;###autoload (define-key esc-map [?\C-/] 'dabbrev-completion) ;;;###autoload (defun dabbrev-completion (&optional arg) "Completion on current word. Like \\[dabbrev-expand] but finds all expansions in the current buffer and presents suggestions for completion. If you call this function with prefix ARG, then it searches all buffers accepted by the function pointed out by 'dabbrev-friend-buffer-function' to find the completions. With no prefix ARG it tries to reuse the old completion list before making a new one." (interactive "*P") (let* ((dabbrev-always-check-other-buffers (and arg t)) (abbrev (dabbrev--abbrev-at-point)) (preserve-case-p (and case-fold-search (string= abbrev (downcase abbrev)))) (my-obarray dabbrev--last-obarray) init) (save-excursion (if (and (null arg) my-obarray (or (eq dabbrev--last-completion-buffer (current-buffer)) (and (window-minibuffer-p (selected-window)) (eq dabbrev--last-completion-buffer (dabbrev--minibuffer-origin)))) dabbrev--last-abbreviation (>= (length abbrev) (length dabbrev--last-abbreviation)) (setq init (try-completion abbrev my-obarray))) ;;-------------------------------- ;; This is a continue. ;;-------------------------------- (progn) ;;-------------------------------- ;; New abbreviation to expand. ;;-------------------------------- (dabbrev--reset-global-variables) (setq dabbrev--last-abbreviation abbrev) (let (compl) (setq dabbrev--last-abbreviation abbrev) (let (completion-list) ;; Find all expansion (setq completion-list (dabbrev--find-all-expansions abbrev preserve-case-p)) ;; Make an obarray with all expansions (setq my-obarray (make-vector (length completion-list) 0)) (or (> (length my-obarray) 0) (error "No dynamic expansion for \"%s\" found%s." abbrev (if dabbrev--check-other-buffers "" " in this-buffer"))) (mapc (function (lambda (string) (intern (concat abbrev string) my-obarray))) completion-list) (setq dabbrev--last-obarray my-obarray) (setq dabbrev--last-completion-buffer (current-buffer)) ;; Find the longest common string. (setq init (try-completion abbrev my-obarray))))) ;;-------------------------------- ;; Let the user choose between the expansions ;;-------------------------------- (or (stringp init) (setq init abbrev)) (cond ;; * Replace string fragment with matched common substring completion. ((and (not (string-equal init "")) (not (string-equal (downcase init) (downcase abbrev)))) (if (> (length (all-completions init my-obarray)) 1) (message "Repeat '%s' to see all completions" this-command) (message "The only possible completion")) (and dabbrev-upcase-means-case-search (setq init (substring init (length abbrev)))) (dabbrev--substitute-expansion nil abbrev init)) (t ;; * String is a common substring completion already. Make list. (message "Making completion list...") (with-output-to-temp-buffer " *Completions*" (display-completion-list (all-completions abbrev my-obarray))) (message "Making completion list...done"))) (and (window-minibuffer-p (selected-window)) (message nil)))) ;;;###autoload (defun dabbrev-expand (arg) "Expand previous word \"dynamically\". Expands to the most recent, preceding word for which this is a prefix. If no suitable preceding word is found, words following point are considered. If still no suitable word is found, then look in the buffers accepted by the function pointed out by variable 'dabbrev-friend-buffer-function'. A positive prefix argument, N, says to take the Nth backward _distinct_ possibility. A negative argument says search forward. If the cursor has not moved from the end of the previous expansion and no argument is given, replace the previously-made expansion with the next possible expansion not yet tried. The variable 'dabbrev-backward-only' may be used to limit the direction of search to backward if set non-nil. To make it more powerful, make sure that 'dabbrev-always-check-other-buffers' is set to t. Also check out 'dabbrev-abbrev-char-regexp' and \\[dabbrev-completion]." (interactive "*P") (let (preserve-case-p abbrev expansion old direction loc) ;; abbrev -- the abbrev to expand ;; expansion -- the expansion found (eventually) or nil until then ;; old -- the text currently in the buffer ;; (the abbrev, or the previously-made expansion) ;; loc -- place where expansion is found ;; (to start search there for next expansion if requested later) ;; preserve-case-p -- non-nil if should transform case when substituting. (save-excursion (if (and (null arg) dabbrev--last-abbrev-location (or (eq last-command this-command) (and (window-minibuffer-p (selected-window)) (= dabbrev--last-abbrev-location (point))))) ;;-------------------------------- ;; This is a redo. ;;-------------------------------- (progn (setq abbrev dabbrev--last-abbreviation) (setq old dabbrev--last-expansion) (setq direction dabbrev--last-direction)) ;;-------------------------------- ;; New abbreviation to expand. ;;-------------------------------- (dabbrev--reset-global-variables) (setq direction (if (null arg) (if dabbrev-backward-only 1 0) (prefix-numeric-value arg))) (setq abbrev (dabbrev--abbrev-at-point)) (setq old nil)) ;;-------------------------------- ;; Find the expansion ;;------------------- ;; Find the expansion ;;-------------------------------- (setq preserve-case-p (and case-fold-search (string= abbrev (downcase abbrev)))) (setq expansion (dabbrev--find-expansion abbrev direction preserve-case-p))) (cond ((not expansion) (dabbrev--reset-global-variables) (if old (save-excursion (search-backward old) (delete-region (match-beginning 0) (match-end 0)))) (error "No%s dynamic expansion for \"%s\" found." (if old " further" "") abbrev)) (t ;; Success: stick it in and return. (dabbrev--substitute-expansion old abbrev expansion) ;; Save state for re-expand. (setq dabbrev--last-expansion expansion) (setq dabbrev--last-abbreviation abbrev) (setq dabbrev--last-abbrev-location (point-marker))))) (message nil)) ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Local functions ;;;---------------------------------------------------------------- ;;;---------------------------------------------------------------- ;;; Checks if OTHER-BUFFER has the same major mode as current buffer. (defun dabbrev--same-major-mode-p (other-buffer) (let ((orig-mode major-mode)) (save-excursion (set-buffer other-buffer) (eq orig-mode major-mode)))) ;;; Extract the symbol at point to serve as abbrevitation. (defun dabbrev--abbrev-at-point () (save-excursion (save-excursion (forward-char -1) (or (looking-at (concat "\\(" (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_") "\\)+")) (error "Not positioned immediately after a word."))) ;;bug in re-search-backward? ;;(re-search-backward (concat "\\(" dabbrev-abbrev-char-regexp "\\)+") ;;(setq dabbrev--last-abbrev-location (match-end 0)) ;;(buffer-substring (match-beginning 0) (match-end 0))) (setq dabbrev--last-abbrev-location (point)) (buffer-substring (point) (if dabbrev-abbrev-char-regexp (progn (backward-sexp) (while (not (looking-at dabbrev-abbrev-char-regexp)) (forward-char 1)) (point)) (progn (forward-word -1) (point)))))) ;;; Initializes all global variables (defun dabbrev--reset-global-variables () ;; dabbrev--last-obarray and dabbrev--last-completion-buffer ;; must not be reset here. (setq dabbrev--last-table nil dabbrev--last-abbreviation nil dabbrev--last-abbrev-location nil dabbrev--last-direction nil dabbrev--last-expansion nil dabbrev--last-expansion-location nil dabbrev--friend-buffer-list nil dabbrev--last-buffer nil dabbrev--check-other-buffers dabbrev-always-check-other-buffers)) ;;; Find all buffers that are considered "friends" according to the ;;; function pointed out by dabbrev-friend-buffer-function. (defun dabbrev--find-friend-buffers () (save-excursion (and (window-minibuffer-p (selected-window)) (set-buffer (dabbrev--minibuffer-origin))) (let ((orig-buffer (current-buffer)) (orig-mode major-mode)) (mapcan (function (lambda (buffer) (and (not (eq orig-buffer buffer)) (funcall dabbrev-friend-buffer-function buffer) (list buffer)))) (buffer-list))))) ;;; Try to find PATTERN in REVERSE direction N times. (defun dabbrev--try-find (pattern reverse n ignore-case) (save-excursion (let ((case-fold-search-is-local (memq 'case-fold-search (buffer-local-variables))) (expansion nil)) (and dabbrev--last-expansion-location (goto-char dabbrev--last-expansion-location)) (unwind-protect (progn (or case-fold-search-is-local (make-local-variable 'case-fold-search)) ;; Tricky! If 'case-fold-search' isn't buffer-local, then ;; this innocent let creates a buffer-local variable and ;; when the let returns, it is still there! The ;; unwind-protect stuff around this makes sure that there ;; exists one before the let, and removes it afterwards. (let ((case-fold-search (or ignore-case (not dabbrev-et ((case-fold-search (or ignore-case (not dabbrev-upcase-means-case-search)))) (loop repeat n while (setq expansion (dabbrev--search pattern reverse ignore-case))))) (or case-fold-search-is-local (kill-local-variable 'case-fold-search))) (and expansion (setq dabbrev--last-expansion-location (point))) expansion))) ;;; Find all expansions of ABBREV (defun dabbrev--find-all-expansions (abbrev ignore-case) (let ((all-expansions nil) expansion) (while (setq expansion (dabbrev--find-expansion abbrev 0 ignore-case)) (setq all-expansions (cons expansion all-expansions))) all-expansions)) (defun dabbrev--scanning-message () (message (concat "Scanning '" (or buffer-file-name (buffer-name (current-buffer))) "'"))) ;;; Find one occasion of ABBREV. ;;; DIRECTION > 0 means look that many times backwards. ;;; DIRECTION < 0 means look that many times forward. ;;; DIRECTION = 0 means try both backward and forward. ;;; IGNORE-CASE non-nil means ignore case when searching. (defun dabbrev--find-expansion (abbrev direction ignore-case) (let ((pattern (concat "\\b" (regexp-quote abbrev) "\\(\\(" (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_") "\\)+\\)")) expansion) (save-excursion (cond (dabbrev--last-buffer (set-buffer dabbrev--last-buffer) (dabbrev--scanning-message)) ((window-minibuffer-p (selected-window)) (set-buffer (dabbrev--minibuffer-origin)) ;; We don't want to be in the middle of a possible ;; expansion, because then we will not find it. (re-search-forward (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_")) (dabbrev--scanning-message))) (cond ;; ------------------------------------------ ;; Look backwards ;; ------------------------------------------ ((and (>= direction 0) (setq dabbrev--last-direction (min 1 direction)) (setq expansion (dabbrev--try-find pattern t (max 1 direction) ignore-case))) expansion) ;; ------------------------------------------ ;; Look forward ;; ------------------------------------------ ((and (<= direction 0) (setq dabbrev--last-direction -1) (setq expansion (dabbrev--try-find pattern nil (max 1 (- direction)) ignore-case))) expansion) ;; ------------------------------------------ ;; Look in other buffers. ;; Start at (point-min) and look forward. ;; ------------------------------------------ (t (setq dabbrev--last-direction -1) ;; Make sure that we should check other buffers (or dabbrev--friend-buffer-list dabbrev--last-buffer (not dabbrev--check-other-buffers) (not (or (eq dabbrev--check-other-buffers t) (progn (setq dabbrev--check-other-buffers (y-or-n-p "Check in other buffers this time? "))))) (setq dabbrev--friend-buffer-list (dabbrev--find-friend-buffers))) ;; Walk through the buffers (while (and (not expansion) (dabbrev--find-friend-buffers))) ;; Walk through the buffers (while (and (not expansion) dabbrev--friend-buffer-list) (setq dabbrev--last-buffer (car dabbrev--friend-buffer-list)) (setq dabbrev--friend-buffer-list (cdr dabbrev--friend-buffer-list)) (set-buffer dabbrev--last-buffer) (dabbrev--scanning-message) (goto-char (point-min)) (setq dabbrev--last-expansion-location nil) (setq expansion (dabbrev--try-find pattern nil 1 ignore-case))) expansion))))) (eval-when-compile (require 'picture)) (defun dabbrev--safe-replace-match (string &optional fixedcase literal) (if (eq major-mode 'picture-mode) (picture-replace-match string fixedcase literal) (replace-match string fixedcase literal))) ;;;---------------------------------------------------------------- ;;; Substitute the current string in buffer with the expansion ;;; OLD is nil or the last expansion substring. ;;; ABBREV is the abbreviation we are working with. ;;; EXPANSION is the expansion substring. (defun dabbrev--substitute-expansion (old abbrev expansion) ;. (defun dabbrev--substitute-expansion (old abbrev expansion) ;;(undo-boundary) (and (not dabbrev-upcase-means-case-search) (setq old (concat abbrev (or old ""))) (setq expansion (concat abbrev expansion))) (if old (save-excursion (search-backward old)) (store-match-data (list (point-marker) (point-marker)))) ;; Make case of replacement conform to case of abbreviation ;; provided (1) that kind of thing is enabled in this buffer ;; and (2) the replacement itself is all lower case. (dabbrev--safe-replace-match expansion dabbrev-upcase-means-case-search t)) ;;;---------------------------------------------------------------- ;;; Search function used by dabbrevs library. ;;; PATTERN is string to find as prefix of word. Second arg, REVERSE, ;;; is t for reverse search, nil for forward. Variable dabbrev-limit ;;; controls the maximum search region size. Third argment IGNORE-CASE ;;; non-nil means treat case as insignificant while looking for a match ;;; and when comparing with previous matches. Also if that's non-nil ;;; and the match is found at the beginning of a sentence and is in ;;; lower case except for the initial then it is converted to all lower ;;; case for return. ;;; Table of expansions already seen is examined in buffer ;;; 'dabbrev--last-table' so that only distinct possibilities are found ;;; by dabbrev-re-expand. ;;; Value is the expansion, or nil if not found. (defun dabbrev--search (pattern reverse ignore-case) (let ((found-string nil)) ;; Limited search. (save-restriction (and dabbrev-limit (narrow-to-region dabbrev--last-expansion-location (+ (point) (if reverse (- dabbrev-limit) dabbrev-limit)))) ;;-------------------------------- ;; Look for a distinct expansion, using dabbrev--last-table. ;;-------------------------------- (while (and (not found-string) (if reverse (re-search-backward pattern nil t) (re-search-forward pattern nil t))) (cond ((or (not dabbrev-abbrev-char-regexp) (not (save-excursion (goto-char (match-beginning 0)) (char-equal ?_ (char-syntax (preceding-char)))))) (setq found-string (buffer-substring (match-beginning 1) (match-end 1))) (and ignore-case (setq found-string (downcase found-string))) ;; Throw away if found in table (and (some (function (lambda (table-string) (string= found-string table-string))) dabbrev--last-table) (setq found-string nil))))) (cond (found-string ;;-------------------------------- ;; Put in 'dabbrev--last-table' and decide if we should return ;; result or (downcase result) ;;-------------------------------- (setq dabbrev--last-table (cons found-string dabbrev--last-table)) (let ((result (buffer-substring (match-beginning 1) (match-end 1)))) (if ignore-case (downcase result) result))))))) ;; nmatch-beginning 1) (match-end 1)))) (if ignore-case (downcase result) result))))))) From fredrik at pythonware.com Sun Jul 14 09:04:03 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Jul 2002 13:04:03 GMT Subject: Python and Parrot References: <3D316CCA.90605@myrealbox.com> Message-ID: <7FeY8.15997$p56.5173354@newsb.telia.net> Johann H?chtl wrote: > Recent progress has been very fast and according to > > http://use.perl.org/articles/02/07/03/2241212.shtml > > the progress of parrots implementation is even likely to speed up. didn't that article basically say "we're out of money, and will no longer work full time" rather than "the progress is likely to speed up"? (and why is it that the Parrot advocacy reminds me of stuff like Freedows and Allos, not to mention HarrixOS... ;-) From jylimd at yahoo.com Mon Jul 15 17:59:53 2002 From: jylimd at yahoo.com (J. Li) Date: Mon, 15 Jul 2002 17:59:53 -0400 Subject: Python and HDF Message-ID: Hi, I am looking for a way to read HDF files directly from Python. Could someone show me the way? thanks in advance Jason From jonathan at onegoodidea.com Tue Jul 30 04:22:39 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 09:22:39 +0100 Subject: pretty basic: get variable name from list of strings? References: <34kbku4j76104d193oevjfi83mk3olvsbt@4ax.com> Message-ID: On 30/7/2002 4:37, in article oktbkuokccfaimsqs1qd6dcgs84qfommm5 at 4ax.com, "chris" wrote: > thanks for the advice. i'm definitely new to programming in addition > to python, so I appreciate the big-picture advice. In general, whenever you think you need a lot of similar variable names containing similar things, you probably actually want a single variable containing a list of things, i.e.: >>> horse1 = 'tonto' >>> horse2 = 'silver' >>> horse3 = 'blackie' >>> >>> horse2 'silver' >>> makes more sense as: >>> horses = [ 'tonto', 'silver', 'blackie' ] >>> >>> horses[1] 'silver' >>> Elements of a list can be indexed by their position - note though that lists are numbered from 0 not 1. Using collections allows you to do generalised operations across all the elements of the collection. For instance: >>> for horse in horses: ... print 'A horse might be called', horse ... A horse might be called tonto A horse might be called silver A horse might be called blackie >>> If, on the other hand, you think you want a lot of differently named variables containing similar things, you probably actually want a dictionary, i.e.: >>> tonto = 'white' >>> silver = 'grey' >>> blackie = 'black' >>> >>> print 'silver is', silver silver is grey >>> makes more sense as: >>> colours = { 'tonto': 'white', 'silver': 'grey', 'blackie': 'black' } >>> >>> print 'silver is', colours['silver'] silver is grey >>> Again, using a collection allows you to do something to/with all of the elements in a general way: >>> for horse in colours: ... print horse, 'is', colours[horse] ... tonto is white blackie is black silver is grey >>> Note that, in contrast to a list, the order things come out of a dictionary is not necessarily the order you put them in. Hope this helps a little. Take comfort that you've picked a good language to start learning in :-) -oh-a-horse-is-a-horse-of-course-of-course...-ly y'rs, Jonathan From raims at dot.com Sat Jul 20 10:24:59 2002 From: raims at dot.com (Rhymes) Date: Sat, 20 Jul 2002 16:24:59 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <3D388C5A.4070309@mxm.dk> Message-ID: <2hkiju466nu6p4fri3i0pbsjt3l25haclu@4ax.com> On Sat, 20 Jul 2002 00:02:02 +0200, Max M wrote: >Hmm ... sounds like you look for a reason to postpone a project. Nooo :) It's only a simple question... -- Rhymes rhymes at myself.com " ride or die " From pixie888 at hotmail.com Mon Jul 15 05:52:05 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Mon, 15 Jul 2002 09:52:05 GMT Subject: SNMP module in python Message-ID: <3d329ac0.330042218@news.skynet.be> Hi, I am looking for a module written in Python to perform SNMP communication. Can anyone tell me where I can find one? Thx, Henk From xiaokai at antibiotics-cn.com Mon Jul 1 21:23:48 2002 From: xiaokai at antibiotics-cn.com (xiaokai) Date: Tue, 2 Jul 2002 09:23:48 +0800 Subject: (no subject) Message-ID: <000a01c22167$219ed280$1100a8c0@unix> -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdsteph at earthlink.net Wed Jul 3 16:34:36 2002 From: rdsteph at earthlink.net (Ron Stephens) Date: Wed, 03 Jul 2002 20:34:36 GMT Subject: A Sourceforge project for newbies Message-ID: <3D2326F8.3000605@earthlink.net> Hmmm, announcing a new Sourceforge project called Decision Analysis at http://sourceforge.net/projects/decision/ The code available for downloading is decide.py, a much updated (improved?) version of my very simple (yet functional, as in working, code) program which some folks on this list helped me with a year ago, when I was a total newbie to Python. The idea is this: newbies can use decide.py, and the Decision Analysis Sourceforge project, to learn new programming skills, and practice the Python techniques learned from books and tutorials. No one is too new, or too clueless, to contribute. The ideas behind decide.py are very simple, and the code is well documented, if (certainly) not elegant. But there is much that can be added, and I am betting that almost any newbie can find ideas in their own head to add to decide.py, without hurting their nogin too much . ;-)) The general version of decide.py is a generalized decision maker. The same code can be easily altered to create new modules, of a specific nature, in any areas in which the individual coder is an "expert" Hey, we're all expert in somethings! For instance, one of the areas in which I claim vast expertise, and therefore I created a module for, is deciding where to go and what to eat for lunch on any given day. Others may be experts in nuclear physcis or world peace, and decide.py can just as easily be extended to incorporate their expertise as well! Beyond adding new modules of exxpertise, which probably represent the easiest additions coders can make to decide.py, there are many other areas for coding, a short list of which follows: 1. Decision Analysis needs a GUI, any GUI. This will be relatively straight-forward, with one big caveat: one must be able to program GUI's in *some* (read *any*) Python GUI toolkit. How about a PythonCard version, a Tkinter version, a Java Swing vesion, a wxPython version...let a thousand flowers bloom... 2. The simple underlyng logic behind decide.py needs to be extended. Any one with a even a modicum of statistical knwoledge (as in more than me ;-))) should be able to come up with more interesting algorithms to use to supplement (or replace!) decide.py's current logic. 3. PDA's. ...I think that decide.py's kind of fun, easy, and lightweight programs are prefect for use on PDA's. I already have decide.py working perfectly well on my Sharp Zaurus, which is cool. But a version taylored just for a given PDA, with a lightweight GUI taylor-made for the PDA, with sliders say for data entry, would be really fun. 4. I have non-working code that uses simple semantic analysis of random questions to identify type of question and keywords involved, , and then uses the WWW and Google to do simple statistical anaysis to "answer" random questions. Could be a part of a new decide.py logic module someday, but the algorithm needs a lot of work. I will be uploading this code to the Sourceforge site, as soon as I get it into reasonable shape.(The existing code can be found on my web site, just look for askMerlin.py) Anyway, all are welcome. Hey, I won even turn away any non-newbies who might show up! ;-))) But for newbies, this is the one place on the net where you can code but not be ashamed of your newbieness. Just have fun. By the time I get back from my two week trip starting Monday July 8, I hope to see some contributions and some questions. Address email questions to rdsteph at earthlink.net or just post them on the Sourceforge site.(That's if I survive *coach* round the world lfight with stops in several countries ;-(((( Decision Analysis, think of it as a poor man's extensible, expert system, semi-intelligent AI ssytem. From cliechti at gmx.net Wed Jul 31 17:02:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 23:02:09 +0200 Subject: C++/Python version problems? References: <3D484ACD.7030503@nonesuch.com> Message-ID: David Smith wrote in news:3D484ACD.7030503 at nonesuch.com: > I'm running Python 2.2.1 under Linux, and successfully interfaced my > C++ procedures into Python. Then I got more aggressive with the > templates, and g++2.95 wouldn't compile it. So I got g++ 3.0, and it > compiles -- I used distutils/setup.py to make the shared object file. > But, now when I try to import my module, I get the error message: > > ImportError: ./cfuncs.so: undefined symbol: __gxx_personality_v0 > > Does this maybe have to do with Python being compiled under an older > g++, or being linked with an older library? Any suggestions as to > what I should do? i'm probably the wrong one to answert this, but... i think the naming conventions have chaged from g++2.9x to 3.x. the name manglig for C++ methods/functions is diffrent. there might be some option to enfore the old behaviour. python is written is C anyway, so you should not have any problems with it, but maybe you're using an interface library like Boost or CXX. that one should(must?) be compiled with the same compiler as your extension. so, yes i do think you thoughts were right, have a look at the libraries you link with. chris -- Chris From b.maryniuk at forbis.lt Thu Jul 4 05:11:56 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 11:11:56 +0200 Subject: creating XML elements Message-ID: <200207041111.56194.b.maryniuk@forbis.lt> On Thursday 04 July 2002 10:57, Thomas Guettler wrote: > If you want to create an xml file it might be easier > to use print(). > > string.encode() might help, too Well, I had same problem, when I needed to create nice XML. Yes, I tried SAX and DOM. Since method dom.toprettyxml() provides VERY UGLY text, I wrote very simple my one. Maybe my XML creator (attachment) helps for somebody of you (note, that code is very ugly yet). -- Sincerely yours, Bogdan M. Maryniuck But what can you do with it? -- ubiquitous cry from Linux-user partner. (Submitted by Andy Pearce, ajp at hpopd.pwd.hp.com) -------------- next part -------------- A non-text attachment was scrubbed... Name: xemlgenxml.py Type: text/x-python Size: 2892 bytes Desc: not available URL: From aleax at aleax.it Mon Jul 15 08:44:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 15 Jul 2002 12:44:51 GMT Subject: objects in a list ... References: Message-ID: <7tzY8.81546$vm5.2959968@news2.tin.it> Ingo St?cker wrote: > Hey. > > I am a newbee @ python. For a little application-project I have a > questions to you: > > I want to create many Objects of a class designed by my own and these > objects should be stored/append in/on a list. Is this possible and how can > I realize it? Thanx & Sorry for my bas englisch :-) Sure, it's perfectly possible. For example: class Object(object): " insert your class's body here " alist = [] # an initially-empty list # make a new one and contextually append it alist.append(Object()) # make one, then separately append it anobj = Object() alist.append(anobj) # make seven more then append them alist.extend([ Object() for j in range(7) ]) # make a new one and put it in first place for a change alist.insert(Object()) and so on, and so forth. In Python, just about everything is "first-class" -- you can always hold things in lists or tuples, or as values in dictionaries, pass them as function arguments, return them as function results -- no problem. Alex From gbien at intekom.co.za Tue Jul 9 18:32:56 2002 From: gbien at intekom.co.za (Geoff Bien) Date: Wed, 10 Jul 2002 00:32:56 +0200 Subject: 8 Queens Problem References: Message-ID: wrote in message news:mailman.1026221774.20130.python-list at python.org... > > > Just For Fun! > > I've been working on a solution to the eigth queens puzzle. > Here is my attempt. There's a solution in Scheme in SICP > which takes only 13 lines. Can anyone come up with a shorter > solution in Python, without any of the obvious silliness? > import string def queens(n,lr,vert,rl,cols): lr, rl = lr >> 1, rl << 1 if len(cols)==n: print 'Solution: ', string.join(cols,', ') for col, bitmask in [ (i+1, 0x01 << i) for i in range(n)]: if not (bitmask & (lr | vert | rl)): queens(n, lr | bitmask, vert | bitmask, rl | bitmask, cols+[`col`]) queens(8,0,0,0,[]) From anton.wilson at camotion.com Fri Jul 26 14:28:19 2002 From: anton.wilson at camotion.com (anton wilson) Date: Fri, 26 Jul 2002 14:28:19 -0400 Subject: thread wierdness In-Reply-To: <200207261812.OAA19811@test-area.com> References: <200207261812.OAA19811@test-area.com> Message-ID: <200207261828.OAA29906@test-area.com> > Instead of the two high-priority threads I thought I created, I see 3 > threads with the PIDs 1374, 1375, and 1376. > Ok, I see that python creates an init thread when the first thread is being created that sits there and does nothing but loop. That seems very pointless although I'm sure there is a reason for this. > Additionally there is a huge gap in time (multiple seconds) on the 6th line > when process 1374 was scheduled and the 7th line when it was removed from > the CPU. This breaks my assumption that python threads will switch every 10 > byte codes. Does anyone have any suggested explanations? > > [(1374) (1375) - 778582] > [(1375) (1374) - 778598] > [(1374) (1375) - 778618] > [(1375) (1376) -778678] > [(1376) (1375) - 778696] > [(1375) (1374) - 778713] > > [(1374) (1376) - 506072] > [(1376) (1375) - 506107] > [(1375) (1376) - 506150] > [(1376) (1375) - 506184] > [(1375) (1374) - 506213] > [(1374) 1068 - 506496] From loewis at informatik.hu-berlin.de Wed Jul 24 09:11:40 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 24 Jul 2002 15:11:40 +0200 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> <3D3EA54C.3EF009A@lfpt.rwth-aachen.de> Message-ID: Lars von Wedel writes: > Sure, there's many applications using distributed functionality. > However, you should consider that technologies like CORBA or > Web Services have similar goals, so check out these before > duplicating work! > > omniORB (http://omniorb.sourceforge.net) and fnorb (don't know where) > are CORBA implementations with Python support. For web services in > Python, have a look at http://pywebsvcs.sourceforge.net/ In addition, a number of Python-specific frameworks for that have been developed over time as well; one of the oldest of those is Dopy (http://www.users.cloud9.net/~proteus/dopy/welcome.html). Regards, Martin From ods at fep.ru Tue Jul 16 08:23:34 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Tue, 16 Jul 2002 16:23:34 +0400 (MSD) Subject: Newbie: Capture output of compile_dir In-Reply-To: <3D340A39.2514C3BE@engcorp.com> Message-ID: On Tue, 16 Jul 2002, Peter Hansen wrote: PH> By the way, "sys" has _stdout and _stderr already, which I PH> believe PH> point to the originals, so I believe you don't need to PH> preserve PH> these in your own locals unless you're expecting to have to PH> nest PH> these sorts of redirections. Certainly, sys module have __stdout__ and __stderr__. But we should restore values being before our definition. For instance if I have colored python shell with already redefined sys.std{out|err} to add ANSII escape sequences then falling back to __std{out|err}__ will break this. -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From jwbaxter at spamcop.net Wed Jul 3 18:27:44 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Wed, 03 Jul 2002 15:27:44 -0700 Subject: python decimal infection? References: Message-ID: In article , "Tim Peters" wrote: > [Thinkit] > > How much has the cancer known as decimal infected python? > > Decimal is evil. > > Indeed, Python uses base-3 arithmetic exclusively, in honor of the Holy > Trinity. I wonder where this puts the old Librascope RPC-9000 (ca 1960) which used BCD coded in binary excess 3 (that is, 0 == 0011, 1 == 0100,etc, with three non-digits at each end). The advantage is that a complement is simply a bit flip; there were signals named III and III-bar (sorry, this medium doesn't allow the overbar) running everywhere around the machine, since a+b is straight add plus III-bar, etc). Odd machine in other ways, too: magneto-strictive delay line memory. "Mass" storage an endless loop 35mm sprocket-feed magnetic tape, etc, etc. And no Python interpreter. --John From tdelaney at avaya.com Wed Jul 10 02:35:46 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 10 Jul 2002 16:35:46 +1000 Subject: A better self Message-ID: > From: Erik Max Francis [mailto:max at alcyone.com] > > Matt Gerrans wrote: > > > In keeping with that concept, '..' would be referring to the base > > class > > (equivalent to java's "super"). > > I think that's definitely mixing metaphors. For one thing, which base > class? Python supports multiple inheritance. Well, obviously it would only be available for new-style classes, and the following would be equivalent ... # current class A (object): def __init__(self) super(A, self).__init__() class B (object): def __init__(self) super(B, self).__init__() class C (A, B): def __init__(self) super(C, self).__init__() # new class A (object): def __init__(self) ..__init__() class B (object): def __init__(self) ..__init__() class C (A, B): def __init__(self) ..__init__() thus getting rid of the need to do a self.__super = super(cls, self) or use a metaclass for this ... ;) Tim Delaney From peter at engcorp.com Fri Jul 12 12:08:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Jul 2002 12:08:08 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <3D2EFEE8.F3F1B94B@engcorp.com> Fran?ois Pinard wrote: > > [Peter Hansen] > > > XML was adapted from SGML to meet several key goals. Among those was > > the desire to make a format which was easily human-readable and editable > > using simple tools like text editors. > > I do not think so. >From http://www.idealliance.org/standards_xml.asp, picked arbitrarily from a Google search for "xml design goals": The design goals for XML are: XML shall be straightforwardly usable over the Internet. XML shall support a wide variety of applications. XML shall be compatible with SGML. It shall be easy to write programs which process XML documents. The number of optional features in XML is to be kept to the absolute minimum, ideally zero. XML documents should be human-legible and reasonably clear. The XML design should be prepared quickly. The design of XML shall be formal and concise. XML documents shall be easy to create. Terseness in XML markup is of minimal importance. I believe "human-legible and reasonably clear", and "easy to create" pretty much cover what I said above. -Peter From sil at kryogenix.org Mon Jul 1 10:31:16 2002 From: sil at kryogenix.org (Stuart Langridge) Date: 1 Jul 2002 07:31:16 -0700 Subject: Castalian: the Active Server Pages object model for Python-embedded HTML pages Message-ID: I've written a thing that provides the Active Server Pages object model to Python embedded in HTML pages; that way, those of you who think of CGI stuff in terms of Request.Querystring and Response.Cookies can use Python in pages on Apache. The code might look something like: Hello, world! Hello, world! (from HTML)
") import os response.write("Your environment variables are:
") for i in os.environ.items(): response.write("%s=%s
\n" % i) if request.querystring.has_key("foo"): response.write("The 'foo' variable in the querystring was:") response.write(request.querystring["foo"]) ?> I'd be interested in comments; Castalian implements a reasonable proportion of the ASP object model, and it's been used in some reasonable-sized projects. Code available from http://www.kryogenix.org/code/castalian/. sil -- 2. Make it halfway normal. I don't have any use for laser-beam-shooting pocket combs, or non-existent existents existing within their own existences, or ballpoint pens made out of lettuce. -- CardinalT dictates rules for the raif Silly Game From aleax at aleax.it Fri Jul 19 07:18:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 19 Jul 2002 11:18:21 GMT Subject: Sorting list of objects on arbitrary attribute References: <3D36AD49.2020305@mxm.dk> <3D372045.9000303@mxm.dk> Message-ID: <1ASZ8.100968$vm5.3501975@news2.tin.it> Max M wrote: ... > made my own from scratch and will use that in my code ;-) ... > def __call__(self, obj1, obj2): > return cmp(self._attrList(obj1), self._attrList(obj2)) ... > aList.sort(sorter) I hope you only sort *SHORT* lists, because performance IS going to be lousy with this approach -- see the Searching and Sorting chapter in the Python Cookbook, or the several examples in the online Python cookbook of the DSU idiom, and do your own timing with pretty modest lists -- you'll see. Alex From maxm at mxm.dk Thu Jul 4 09:39:44 2002 From: maxm at mxm.dk (Max M) Date: Thu, 04 Jul 2002 15:39:44 +0200 Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: <3D245020.5030007@mxm.dk> Ben Fairbank wrote: > I have several long (thousands of entries) dictionaries of words used > in plays; associated with each word is the number of times it is used > in the play. I have had no problem printing the words alphabetically > (send keys to a list, sort the list, access dictionary by the sorted > key list), but I have not found an elegant way to sort by frequency > of use. The best I have been able to do is a workable but inelegant > kluge that looks more like Basic than Python. Is there a "Python Way" > of doing that? # the basic sort sortedList = [(key, theDict[key]) for key in theDict.keys()] sortedList.sort() # if you want most frequent first sortedList.reverse() # plain printout for frequency, word in sortedList: print 'word: %s, freq: %s' % (word, frequency) # or for a faster printout of large amounts of text print '\n'.join(['word: %s, freq: %s' % (item[1], item[0]) for item in sortedList]) regards Max M From fredrik at pythonware.com Thu Jul 18 12:07:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Jul 2002 16:07:13 GMT Subject: __del__ in classes derived from Tkinter classes References: Message-ID: Petr Klyushkin wrote > I'm a Python and Tkinter newbie. I've noticed that __del__ methods of > my classes derived from Tkinter classes are never called. Is this > normal behavior, or I am doing something wrong? > > Example code: > > import Tkinter > > class Test(Tkinter.Toplevel): > def __del__(self): > print 'hey!' > > tk = Tkinter.Tk() > test = Test(tk) tkinter maintains an internal widget tree. if you want to print "hey" when your toplevel widget is destroyed, over- ride the "destroy" method: class Test(Tkinter.Toplevel): def destroy(self): Tkinter.Toplevel.destroy(self) print 'hey!' if you want to capture attempts to close the window, you should install a WM_DELETE_WINDOW protocol handler; for details, see: http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm (and using __del__ is usually bad style even outside Tkinter, but that's another story). From bh at intevation.de Thu Jul 4 05:49:56 2002 From: bh at intevation.de (Bernhard Herzog) Date: 04 Jul 2002 11:49:56 +0200 Subject: replacing instance __setattr__ References: Message-ID: <6qsn2zyg8r.fsf@abnoba.intevation.de> Robin Becker writes: > In article , Robin Becker > writes > >Is there something intrinsically hard about overriding an instance's special > >methods? I'm using > >python 2.2 and expected that it would be easy to wrap an existing __setattr__, > >but > >it seems the class is searched first not the instance. Must I clone the class > >and > >set the method on that? > > > .... > well it seems Python not as dynamic as I believed. The object is > searched last which seems completely counter-intuitive to me, but there > you go. The truth is a bit more complex. If a class defines or inherits one of the special methods __setattr__, __getattr__ and __delattr__, the corresponding unbound methods are stored in the class structure directly so that they can be accessed quickly. There's no way to override them on an instance by instance basis (except perhaps by deriving an appropriate class from instance.__class__ and turning the instance into an instance of that class by assigning to __class__) Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From peter at engcorp.com Tue Jul 16 23:32:22 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Jul 2002 23:32:22 -0400 Subject: SVG viewer in python? References: Message-ID: <3D34E546.AC852777@engcorp.com> gb at cs.unc.edu wrote: > > Does anyone know of an open source SVG viewer written in Python? I'm > working with some students on a project to make SVG drawings (maps in > particular) accessible to visually impaired students. Well, a simple Google for "python svg viewer open source" returns a link to http://www.w3.org/Graphics/SVG/SVG-Implementations as it's first hit... does Sketch do it for you? -Peter From dale at riverhall.NOTHANKS.co.uk Fri Jul 26 10:16:16 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Fri, 26 Jul 2002 15:16:16 +0100 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> <7xeldq1zzp.fsf@ruckus.brouhaha.com> Message-ID: Thanks that's very helpful. This isn't really a browser issue. It's a rather unusual service we need to offer. We are providing a number of forms which sit, seamlessly, inside client web pages. We handle the form and the data, although the content of the form will depend on the client - not the user of the browser. The client needs to identifiy and authenticate themselves on the URL that puts the form in the frame. The communication between our servers and the browser isn't the issue here. Had a quick look at HMAC Thanks for the info. -- Dale Strickland-Clark Riverhall Systems Ltd From jepler at unpythonic.net Wed Jul 3 22:10:51 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 3 Jul 2002 21:10:51 -0500 Subject: Newbie lists question In-Reply-To: References: Message-ID: <20020703211046.A1326@unpythonic.net> Rows are retured as tuples. If you selected more than one column you might see something like [('Wall', 'Larry'), ('van Rossum', 'Guido'), ...] Because you SELECTed one field, you get a length-1 tuple. try this as your "for" loop: for last in result: selectlist.append(last[0]) instead of using "last". Jeff From david.levy at xrce.xerox.com Mon Jul 22 06:22:58 2002 From: david.levy at xrce.xerox.com (David Levy) Date: Mon, 22 Jul 2002 12:22:58 +0200 Subject: SOAP.py and complex types Message-ID: <3D3BDD02.3997B185@xrce.xerox.com> Hi I am using Python to call Web Services, with SOAP.py (0.9.7) library However I can't figure how to use it when input messages requires user defined types like the one for the new Amazon web service : http://soap.amazon.com/schemas/AmazonWebServices.wsdl does anyone know how to do it ? Thanks -- _____________________________________________________________ David Levy Xerox Research Centre Europe 6, ch. de Maupertuis F - 38240 Meylan Email david.levy at xrce.xerox.com http://www.xrce.xerox.com From als at usenet.thangorodrim.de Wed Jul 24 10:32:17 2002 From: als at usenet.thangorodrim.de (Alexander Schreiber) Date: 24 Jul 2002 14:32:17 GMT Subject: Detecting pipe on stdout? Message-ID: Hi! Is there any way for a Python program to detect wether its stdout has been redirected to a pipe/file (like "./programm | less")? I've didn't find anything about this in the FAQ and failed to come up with the right search terms for google. Reason: I've got a Python program[0] here which normally colorizes its output (to the terminal) using escape sequences. This is fine and nice while running on a terminal, but when running the program with less attached to it the escape sequences are annoying. Ideally, I want to detect a pipe attached to stdout and switch of the color (the flag is already there) in this case. Regards, Alex. [0] Not written by me. -- Those who desire to give up Freedom in order to gain Security, will not have, nor do they deserve, either one. -- Benjamin Franklin From emile at fenx.com Thu Jul 11 10:27:21 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 11 Jul 2002 14:27:21 GMT Subject: struct unpack help? References: Message-ID: Scherer, Bill > Here's a sample string of the struct: > > sampleStructString = "_782c1a08_p_void" > > I know that the struct defines only two unsigned shorts. That > would imply (to me, anyway) a format of 'HH'. But calcsize of > that is 4, while my string is 16 bytes. So > If you know the expected results of the sample, you can pass in the appropriate slice: >>> struct.unpack('HH', s[1:5]) (14391, 25394) >>> struct.unpack('II', s[1:9]) (1664235575L, 942694705L) -- Emile van Sebille emile at fenx.com --------- From peter at engcorp.com Sun Jul 7 08:52:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Jul 2002 08:52:43 -0400 Subject: Problem with mxDateTime function DateFromString Message-ID: <3D28399B.3C879371@engcorp.com> I would submit this somewhere as a defect report except I can't find an appropriate place on the http://www.lemburg.com site, and all contact information seems to be surrounded by licensing agreements and commercial per-incident support fees and such... it's pretty unfriendly towards someone who doesn't want support, doesn't use the package, but just wants to point out a little problem so others can benefit... (no doubt I missed the correct link, but that just supports my point). Anyway: >>> from mx.DateTime.Parser import DateFromString this is wrong: >>> DateFromString("October 29/2000") but this is right: >>> DateFromString("October 29, 2000") Note the year in the results. It would seem that lack of a space in the first two would not be an entirely unusual situation. I wouldn't mention it except for the comment in the notes for the Parser submodule: "The Parser submodule ... will try very hard to come up with a reasonable output given a valid input." The first date we gave it, however, had no space after the comma and it _quietly_ gets it wrong, making it questionable how reliable it will be for other perhaps unusual inputs. -Peter From siugarc at interserv.com.tw Thu Jul 25 03:29:26 2002 From: siugarc at interserv.com.tw (¥ð¸¯º¸) Date: 25 Jul 2002 15:29:26 +0800 Subject: memory leak Py_initialize+Py_Finalize??? Message-ID: I call only Py_Initialize() and Py_Finalize() in VC. Many memory leaks are showed in BoundsChecker. If I call Py_Inisialize() and Py_Finalize() repeatedly, more memory leaks are made. Who know if this is the bug of python? -- CNews 0.4 From justin at iago.org Sun Jul 14 13:13:52 2002 From: justin at iago.org (Justin Sheehy) Date: Sun, 14 Jul 2002 13:13:52 -0400 Subject: Is count supposed to still work? In-Reply-To: ("David LeBlanc"'s message of "Fri, 12 Jul 2002 13:49:49 -0700") References: Message-ID: "David LeBlanc" writes: > Aren't these all built in anyway? I don't recall having to do it for > len(mystring). No. len() is different, as it needs to operate on all sequences. -Justin From eric.brunel at pragmadev.com Tue Jul 30 12:48:55 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 30 Jul 2002 18:48:55 +0200 Subject: How to find out if february has 29 or 28 days ? References: Message-ID: Marcus Vinicius Laranjeira wrote: > Folks, > > I use the mx.DateTime package, and I need to know if in one particular > year has a february with 28 or 29 days ? I don't know how to do that ! A year is a leap year if it can be divided by 4, except if it can be divided by 100, where it's a leap year only if it can be divided by 400. It sounds awful to compute, but in Python, it's actually quite simple: >>> isLeap = lambda x: x % 4 == 0 and (x % 100 != 0 or x % 400 == 0) >>> isLeap(1980) 1 >>> isLeap(1991) 0 >>> isLeap(2000) 1 >>> isLeap(1900) 0 HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From neal at metaslash.com Thu Jul 18 11:53:38 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 18 Jul 2002 15:53:38 GMT Subject: Fail pyton build. What to do References: Message-ID: On Thu, 18 Jul 2002 06:58:57 -0400, edadk wrote: > I am build python 2.1.1 on Solaris/Intel 8 and get the error meassage > below. [I do not need the audio stuff at all. Can I shut it off for > instace.] > > What can I do? > > building 'sunaudiodev' extension > gcc -g -O2 -Wall -Wstrict-prototypes -fPIC -I. > -I/tmp/Python-2.1.1/./Include -I/usr/local/include -IInclude/ -c > /tmp/Python-2.1.1/Modules/sunaudiodev.c -o > build/temp.solaris-2.8-i86pc-2.1/sunaudiodev.o > /tmp/Python-2.1.1/Modules/sunaudiodev.c:24: sun/audioio.h: No such file > or directory > WARNING: building of extension "sunaudiodev" failed: command 'gcc' If this is your only problem, you can comment out the line in Modules/Setup for sunaudiodev and it should be fine. Neal From newfroups at jerf.org Fri Jul 12 11:00:21 2002 From: newfroups at jerf.org (Jeremy Bowers) Date: Fri, 12 Jul 2002 15:00:21 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <3D2EC004.7040700@jerf.org> Alex Martelli wrote: > It is -- easily. My pet peeve is the idea of using XML files for > tasks that obviously need a real database, preferably a relational one. > > I think some people never really GOT relational databases, no matter > that they've been around for decades and are so widespread, and they're > now turning to *overusing* XML to cover up for that:-). This was the idea in the core of my point. Databases are far more powerful then any XML library I've ever seen... not counting the XML databases, I suppose, which don't seem to be in the common use that relational databases are (and I don't know much about, except $$$). Don't decide on XML until you've eliminated relational databases, for instance. (In an experienced engineer's head, that elimination can be instantaneous, based on the knowlege and experience of the engineer. In a new programmer, it may take actual thinking.) Indeed, relational databases are almost as cross-platform and cross-language as XML is! But if you *need* transferability and extensibility, you'll probably end up with XML. Databases don't just sit on a file system or get forwarded in email very well. From martin at v.loewis.de Tue Jul 30 14:03:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 20:03:01 +0200 Subject: UnicodeError... References: <3D459AE0.5030509@pp.inet.fi> <3D46B617.10909@pp.inet.fi> Message-ID: Teemu Luojola writes: > Well, here is the result, when I entered precisely what was told in FAQ: > > >>>> encoding = "ascii" > >>>> import locale > >>>> loc = locale.getdefaultlocale() > >>>> if loc[1]: > > encoding = loc[1] The FAQ did not tell you enter these statements at the interactive prompt. It told you to modify the file site.py, which is located on your hard disk. > How it is possible, that sys.setdefaultencoding() does not exist? It's deleted from sys in site.py. Regards, Martin From neal at metaslash.com Fri Jul 26 16:58:16 2002 From: neal at metaslash.com (Neal Norwitz) Date: Fri, 26 Jul 2002 20:58:16 GMT Subject: type names versus types module References: <918bc22f.0207261239.37a56073@posting.google.com> Message-ID: On Fri, 26 Jul 2002 16:39:26 -0400, Donnal Walter wrote: > I read in Guido's keynote address (slide 15 of 23) that we are now > supposed to be using built-in type names instead of the types module. > What is the preferred alternative syntax in Python 2.2 for the following > snippet? > > ... > if type(content) is types.ListType: > print 'content is a list' > else: > print 'content is not a list' Check out PEP 8, Programming Recommendations (near the end). http://www.python.org/peps/pep-0008.html Guido prefers to use isinstance(content, list). Neal From boud at valdyas.org Sun Jul 7 02:22:10 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sun, 07 Jul 2002 08:22:10 +0200 Subject: Chinese language support of Python? References: <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <3d27de14$0$94898$e4fe514c@dreader3.news.xs4all.nl> Leon Wang wrote: > Hi, I got the Chinese displayed correctly in window title without > change the default encoding in site.py by: > > root.title(u'\u4e2d\u6587') > > But still can not put Chinese directly as string in source, I can not > live with so much \u... for a whole Chinese sensence/paragraph, it's > impossible to read and edit them :( > However, I can print Chinese string (normal string, without u prefix > and \u codes) in console with command line python.exe. How can I let > Tkinter accept that? I don't think that's going to work (caveat: I use PyQt which has different conventions). If you absolutely want to have Chinese characters in your source files*, you can do something like the following**: root.title(unicode('???', 'utf-8') Note that you _will_ have to construct a unicode object, not an ordinary string, since ordinary strings are just containers for bytes, one character per byte. If you want the system to understand what you mean. You can find out which encodings are available by inspecting the python/lib/encodings directory (or, python\lib\encodings): you can use any encoding instead of the 'utf-8'. Of course, the string must then be in the right encoding, too. There are some errors in my handling of this topic in my book, but it might still be useful to you: http://www.opendocspublishing.com/pyqt/index.lxp?lxpwrap=c2029%2ehtm errata: http://www.valdyas.org/python/book.html The paper version has nice pictures that are quite useful in this chapter. * Actually I still think it would be great to be able to have sourcefiles in utf-8, not limited to unicode strings. I want to type: def ??(): pass That this would make my source code unreadable for a lot other people, tant pis, I still would like the power. Just as I want the power to do a quick sys.setAppDefaultEncoding('utf-8') to make sure this application sees all its strings as encoded in utf-8. ** Note that this posting is encoded in utf-8. If you see gibberish instead of a friendly greeting, then either the message is mangled, or your newsreader can't handle the encoding, or you don't have the fonts to show Chinese. -- Boudewijn Rempt | http://www.valdyas.org From martin at v.loewis.de Wed Jul 10 00:48:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Jul 2002 06:48:43 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: sjmachin at lexicon.net (John Machin) writes: > (1) Shouldn't you deduct the 2048 surrogates from the count? Correct. Rounded to two decimal places, it would still be 4.09 bits. > (2) Why did you round up to two decimal places and not zero decimal > places? Can you buy 4.09 cans of beer? To counter the impression that surrogates give you 5 additional bits, which they don't. That they give 4 additional bits is much closer to truth. I would by 4 cans of beer, and accept that I owe someone a drop - especially since me and my guest won't drink more than 2 cans tonight. Regards, Martin From tjreedy at udel.edu Thu Jul 25 17:39:30 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Jul 2002 21:39:30 GMT Subject: Numeric data question References: <%Nz%8.15893$A72.86385@news1.mts.net> Message-ID: "James J. Besemer" wrote in message news:mailman.1027627251.9009.python-list at python.org... > > Terry Reedy wrote: > > If the amounts of money you are dealing with are well less than the > > max, and if you are only doing + and - (accounting in the strict > > sense) and maybe * by int amounts, > > Accounting per se cannot be limited to the above operations. Account: "to furnish a reckoning of money received and paid out" says my Websters New World Dict. If this is all one wants or needs a program to do, then it is sufficient. > Think of tax tables, withholding percentages, asset depreciation, interest > calculations, etc., etc. I did, which is why I wrote >> Financial calcs with interest and other rates requires more care. Calculations of amounts to seek or pay are not the same as actual flows themselves Terry J. Reedy From hsfrey at earthlink.net Mon Jul 1 17:18:34 2002 From: hsfrey at earthlink.net (Harvey Frey) Date: Mon, 1 Jul 2002 14:18:34 -0700 Subject: Where is Source for Node Class? Message-ID: <009001c22144$dbe4e8a0$289dfea9@t9k2t3> I'm trying to convert a C program which makes extensive use of pointers and lists. I assume that dictionaries would be the corresponding python method, but I'd like to see an example. I see that minidom uses a node class, apparently subclassed from a node class in xml.dom. I searched through the other .py files in xml/dom, but I can't find the original node class that minidom is importing. I am a rank beginner in python, so don't hesitate to mention obvious blunders and misunderstandings. Harvey From tdelaney at avaya.com Sun Jul 7 20:30:43 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 8 Jul 2002 10:30:43 +1000 Subject: Thanks ... and how to express them. Message-ID: > From: chris lyon [mailto:chris.lyon at spritenote.co.uk] > > Just a question of etiquete. > I have recieved beneficial help form individuals do I thank > on the list or not? It depends on the complexity and number of answers ;) If it's just one or two people, and the answer is simple, an off-list email is good. If there are lots of people, or the answers are complex, an on-list email, with a summary of the (correct) answers and a "thanks to all who helped" is much appreciated. However, if you *just* post a "thanks to all who helped" message, you are almost certain to get people asking "and what was the answer?" so you should supply it first :) Cheers. From Gabe.Newcomb at noetix.com Wed Jul 10 13:55:02 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Wed, 10 Jul 2002 10:55:02 -0700 Subject: A better self Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6033@NOXMAIL.noetixad.com> It seems to me that, given that most folks here agree the concept of 'self' is useful, we may as well stick with the word 'self' as is. It's the explicit version--it makes things clear, and if anyone's really dying to use the shortest identifiers possible, they might consider Perl. Yes that last statement was partially tongue-in-cheek, but seriously, readability is worth preserving IMO. Gabe -----Original Message----- From: Huaiyu Zhu [mailto:huaiyu at gauss.almadan.ibm.com] Sent: Wednesday, July 10, 2002 10:01 AM To: python-list at python.org Subject: Re: A better self Sean 'Shaleh' Perry wrote: >> >> Before you all react (programmers can be SO conservative), please think >> about it! >> > >I have played with ideas like this in python and other languages, and witnessed >others do the same. > >.foo is REALLY hard to see if the font is not just right. > >.size = .r + .l > >is even worse. > >I am not 100% against the idea as an idea, but the actual usage is not all that >fun. A better (and currently available) convention is _.size = _.r + _.l It has been mentioned several times in this thread. I've used it several times in the past and liked it, esp in iterative algorithms. Some usage patterns include def __init__(_, x, y, z): _.x, _.y, _.z = x, y, z def process(_, x, y, z): actions involving _.x, _.y, _.z, x, y, z _.x, _.y, _.z = x, y, z def update(_): x, y, z = _.x, _.y, _.z actions involving x, y, z _.x, _.y, _.z = x, y, z One could even think of _. as a magic persistence prefix that makes the variable keep its value between method calls. It is also easy to replace _.x with self.x or vice versa in a good editor. Huaiyu -- http://mail.python.org/mailman/listinfo/python-list From whisper at oz.net Wed Jul 10 13:36:01 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 10:36:01 -0700 Subject: Hierarchical Editor In-Reply-To: <3D2C500D.5000100@thomas-guettler.de> Message-ID: Try Leo? http://personalpages.tds.net/~edream/front.html David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Thomas Guettler > Sent: Wednesday, July 10, 2002 8:18 > To: python-list at python.org > Subject: Re: Hierarchical Editor > > > John Hunter wrote: > > >>>>>>"Thomas" == Thomas Guettler writes: > >>>>>> > > > > Thomas> Hi! Does someoone know an editor for editing hierarchical > > Thomas> text data? > > > > Thomas> I need it for something like a todo-list. One task can > > Thomas> have several subtasks. > > > > Emacs has a number of todo modes: > > > > http://www.emacswiki.org/cgi-bin/wiki.pl?ToDo > > > I love emacs for editing source code. But I need something that > can be used by everybody. The treeview should look like in the > windows explorer. > > thomas > > > -- > http://mail.python.org/mailman/listinfo/python-list From marklists at mceahern.com Mon Jul 1 09:57:48 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 1 Jul 2002 08:57:48 -0500 Subject: New style classes as exceptions (Was: exception handing) In-Reply-To: Message-ID: > New style classes don't work when used as exceptions. I guess it > should be considered as a bug. Just out of curiousity: How come you aren't subclassing from Exception? // m - From gerhard.haering at gmx.de Mon Jul 8 02:09:20 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 8 Jul 2002 08:09:20 +0200 Subject: structs in python In-Reply-To: References: <20020706231200.A25295@arizona.localdomain> Message-ID: <20020708060920.GA7546@lilith.my-fqdn.de> * Christopher A. Craig [2002-07-08 01:22 -0400]: > "Kevin O'Connor" writes: > > > What if a syntax like the following were permitted: > > >>> p = ( .x = 10, .y = 11, .color = 'blue') > > >>> print p.x > > 10 > > >>> > > Why don't you just use a dict? > > >>> p = {'x'=10, 'y'=11, 'color'=blue} > >>> print p['x'] > 10 > >>> I prefer tiny data-only classes. These can be used exactly like a a struct. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gv at cs.uu.nl Wed Jul 24 09:14:53 2002 From: gv at cs.uu.nl (Gerard A.W. Vreeswijk) Date: Wed, 24 Jul 2002 15:14:53 +0200 Subject: is so simple that is not in a module References: <3D3E9F34.90FB8B3F@cs.uu.nl> Message-ID: <3D3EA84D.FD25CC3C@cs.uu.nl> Chris Liechti wrote: > is so simple that is not in a module : Amazing that such a thing can be done in merely 12 (twelve) lines of code. I've tried it and it works (of course), thanks to Python (I guess) and Chris. Gerard From oliver.eichler at dspsolutions.de Fri Jul 5 04:36:30 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Fri, 05 Jul 2002 10:36:30 +0200 Subject: redirect stdout Message-ID: Hi I am using the bdb module wrapped by my own script to step thru a python script. Within the debugged script I have some textual printout to stdout. Is it possible to redirect the stdout stream e.g. to a socket? Oliver From suyong at fnal.gov Fri Jul 26 16:57:10 2002 From: suyong at fnal.gov (suyong) Date: Fri, 26 Jul 2002 15:57:10 -0500 Subject: window icons in Tkinter References: <3d2e442c$0$11264$afc38c87@news.optusnet.com.au> <5ZsX8.2270$931.1025656@newssrv26.news.prodigy.com> Message-ID: <3D41B7A6.5010603@fnal.gov> dsavitsk wrote: > look for tkicon at http://effbot.org/downloads/ > > > "Steven" wrote in message > news:3d2e442c$0$11264$afc38c87 at news.optusnet.com.au... > >>Can anyone shed some light on how to get the root window to use an icon >>other than the 'Tk' symbol? >> >>I can't seem to find an example of this anywhere >> >>thanks >> >>Steven >> >> >> > > Standard way, I think, is something like the following code. However, it only works for X bitmaps (you can create this using programs like gimp), which means they're black and white. Color bitmaps, according to some books, should work, that's the part I commented out, because it doesn't work. But then again, I'm not that experienced in python #!/usr/bin/env python from Tkinter import * class RecoJobs(Frame): title = "D0Reco" def __init__(self): self.master.iconname('Reco jobs') self.master.iconbitmap('@reco.xbm') #self.label=Label(self, image=PhotoImage(file='reco.gif')) #self.master.iconwindow(self.label) def test(): """Simple test program.""" RecoJobs().mainloop() test() the '@' in front of the file name reco.xbm, is important. Suyong From aleax at aleax.it Thu Jul 25 10:20:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 14:20:05 GMT Subject: how to get a return value from an exception ? References: Message-ID: Shagshag13 wrote: > hello, > > i need to raise an exception which "carry" some data... i think that it's > something like : > > class MyException(Exception): > > def __init__(self, *args): > Exception.__init__(self, args) This method __init__ is useless. Just write: class MyException(Exception): pass for clarity and brevity. >>>> raise MyException('one', 2, 'three') > Traceback (most recent call last): > File "", line 1, in ? > raise MyException('one', 2, 'three') > MyException: ('one', 2, 'three') > > but them how to access to 'one', 2, and 'three' ? try: raise MyException('one', 2, 'three') except MyException, e: print repr(e.args) e.args is the tuple ('one', 2, 'three') . > it's ok if i do it like in "dive in python" > >>>> class MyError(Exception): > def __init__(self, value): > self.value = value > def __str__(self): > return `self.value` > > but here what does the `` stand for ? A weird ancient way of spelling repr(self.value) that some Pythonistas like (me, I don't). Alex From cliechti at gmx.net Mon Jul 8 15:52:56 2002 From: cliechti at gmx.net (Chris Liechti) Date: 8 Jul 2002 21:52:56 +0200 Subject: Flush References: Message-ID: Charles wrote in news:mailman.1026155209.5313.python- list at python.org: > Anyone know if python has a flush() function like PHP, > to buffer dump in CGI ? like sys.stdout.flush() ? don't know PHP so i hope it's that what you mean :-) chris -- Chris From mwh at python.net Tue Jul 2 10:39:40 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Jul 2002 14:39:40 GMT Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3D12E228.6030501@wedgetail.com> Message-ID: Jim Richardson writes: > On Fri, 21 Jun 2002 08:22:02 GMT, > Derek Thomson wrote: > > Easy, just use the "join" function to concatenate a sequence of strings > > into a single string. For example: > > > > > > import string > > > > list = ['a', 'b', 'c', 'd'] > > > > s = string.join(list, '') > > > > print s [...] > huh! > > cool, thanks, that solved a problem I was having. > when did that show up? or was I not paying attention? What, string.join? It's been around forever, or as good as. Cheers, M. -- That one is easily explained away as massively intricate conspiracy, though. -- Chris Klein, alt.sysadmin.recovery From pixie888 at hotmail.com Mon Jul 22 09:24:11 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Mon, 22 Jul 2002 13:24:11 GMT Subject: Alex Martelli is off the net for a few days :-( References: Message-ID: <3d3c0738.271278796@news.skynet.be> Very of the shelf question: Martijn, have you been at the ETH in Zuerich somewhere around 1994/1995? Henk On 22 Jul 2002 13:13:57 GMT, m.faassen at vet.uu.nl (Martijn Faassen) wrote: >Laura Creighton wrote: >> Some construction workers have severed his phone and internet lines. >> Expect him back in a few days, not a few hours. :-( > >Of course this is a Python Secret Underground coverup -- the martellibot >is offline for maintenance. There were some surprising bugs which caused him >to From karaatanasov at hotmail.com Fri Jul 19 08:08:58 2002 From: karaatanasov at hotmail.com (Kiril Karaatanasov) Date: 19 Jul 2002 05:08:58 -0700 Subject: Recursion References: <20020719083105.5c01b6a4.christophe.delord@free.fr> Message-ID: <71a1c515.0207190408.ee0e943@posting.google.com> Christophe Delord wrote in message news:<20020719083105.5c01b6a4.christophe.delord at free.fr>... > Try this: > > def bits(x): > return (x!=1 and bits(x>>1) or "") + "01"[x&1] > > The idea is to return the string instead of printing it. > > or this if you prefer: > > def bits(x): > if x != 1: > s = bits(x>>1) > if x & 1: > s = s+"1" > else > s = s+"0" > return s Smart but as anything French WRONG !!!! try calling bits(0) Now may be we want to write it the good way vs. the "smart" way :o) def bits(x): return (x>1 and bits(x>>1) or "") + "01"[x&1] From phr-n2002b at NOSPAMnightsong.com Sat Jul 13 00:29:53 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 12 Jul 2002 21:29:53 -0700 Subject: hiding command line input References: <3D2FA84F.7080002@doit.com> Message-ID: <7x7kk045dq.fsf@ruckus.brouhaha.com> destr0 writes: > I'm in the habit of using raw_input() for user interaction on > the command line. I now have a situation where I need to > prompt the user for input on the command line, but I need > to get a password from them, so I'd like to hide the display > of the letters on the screen. Is there another python function > that will get input in the manner raw_input() does, but mask the > input from the user, or am I going to have to roll my own > function. Use the getpass module: import getpass password = getpass.getpass("Enter password: ") From brian at sweetapp.com Fri Jul 19 11:51:26 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 19 Jul 2002 08:51:26 -0700 Subject: xmlrpclib oddness In-Reply-To: <3D382772.128F0930@millfilm.co.uk> Message-ID: <007701c22f3c$245db760$bd5d4540@Dell2> Eric Texier: > DUMPS: > File "/usr/people/erict/bin//lib/python2.2/xmlrpclib.py", line 763, in > dumps > data = m.dumps(params) > File "/usr/people/erict/bin//lib/python2.2/xmlrpclib.py", line 454, in > dumps > self.__dump(v) > File "/usr/people/erict/bin//lib/python2.2/xmlrpclib.py", line 465, in > __dump > raise TypeError, "cannot marshal %s objects" % type(value) > TypeError: cannot marshal objects The server is returning None, which is not a valid XML-RPC type. Without seeing the server code, it is impossible to say why. Cheers, Brian From phsdv.remove at earthlink.net Sun Jul 21 02:45:14 2002 From: phsdv.remove at earthlink.net (Paul) Date: Sun, 21 Jul 2002 06:45:14 GMT Subject: maximum recursion depth References: Message-ID: <_Ls_8.8858$_C2.708155@newsread2.prod.itd.earthlink.net> unfortunately it is not just memory... it will (did) crash when the stack size is full, which is only a fraction of the total memory space... right? python used less than 6MByte (less than 1% of total) when it crashed with a much higher limit set for the recursion depth. It took an awful lot of processing time as well... Have to rethink my strategy here. P. "Tim Peters" wrote in message news:mailman.1027230329.19568.python-list at python.org... > [Paul] > > ... > > Can I optimize my code so that there will be less recursion? yes, but my > > recursion depth will still be over 1000 times... > > Can I rewrite my code without recursion? Maybe, but I do not want to. > > > > My question to you: Is there a way to change the limit of the recursion > > depth? > > You've been correctly pointed at sys.setrecursionlimit(), but you should be > aware that unless you bought one of those new-fangled machines with infinite > memory , your program will eventually crash. > > > > From zopestoller at thomas-guettler.de Fri Jul 12 04:41:44 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 12 Jul 2002 10:41:44 +0200 Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> <3D2C500D.5000100@thomas-guettler.de> Message-ID: <3D2E9648.6090007@thomas-guettler.de> Ian Parker wrote: > If you wanted something only for Windows, then MS word has an outline mode. That's what I use at the moment. I like it very much, but something free, written in python and available on linux would be better. Don't need image support or things like this pure ascii (or better unicode) is enough. thomas From piet at cs.uu.nl Wed Jul 10 06:07:27 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 10 Jul 2002 12:07:27 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: >>>>> loewis at informatik.hu-berlin.de (Martin v. L?wis) (MvL) writes: MvL> Piet van Oostrum writes: >> I looked it up in The Online Edition of The Unicode Standard, Version 3.0 >> In chapter 3, section 3.8 it said: >> >> Because every Unicode coded character sequence maps to a unique >> sequence of code values in a given UTF, a reverse mapping can be >> derived. Thus every UTF supports lossless roundtrip transcoding: >> mapping from any Unicode coded character sequence S to a sequence >> of code values and back will produce S again. To ensure that >> round-trip transcoding is possible, a UTF mapping _must also_ map >> invalid Unicode scalar values to unique code value sequences. These >> invalid scalar values include FFFE, FFFF and unpaired surrogates. MvL> [...] >> Technical Reports tr27 and tr28 do not withdraw this. MvL> Notice that this is a requirement onto UTFs, not onto implementations MvL> of Unicode. So the UTF must define a mapping. UTF-8 happens to map MvL> invalid code sequences to illegal byte sequences. Unicode 3.1 now MvL> mandates that such sequences are flagged as an error. So should the UTF-8 encoding raise an exception then on encountering an unpaired surrogate rather than generating an illegal UTF-8 sequence? Tr28 says: It is illegal to emit or interpret any ill-formed code unit sequence. But this is exactly what the Python UTF-8 encoding does. It gives '\xa0\x80' as the encoding of u'\ud800', which is an il-formed UTF-8 sequence in any sense of the term (i.e. even in the old specs). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From donn at drizzle.com Tue Jul 30 01:26:50 2002 From: donn at drizzle.com (Donn Cave) Date: Tue, 30 Jul 2002 05:26:50 -0000 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: <1028006808.127972@yasure> Quoth "Steve Holden" : | "Carl Banks" wrote in message | news:ahuqd8$1a7$1 at solaris.cc.vt.edu... | [ ... ] |> Personally, I don't care about saving lines, per se. For me, lambda |> helps me to avoid stopping mid-function call, scrolling many or few |> lines to implement the function as a def, and returning. I.e., |> lambdas save me cursor movement. | | Well your programming style and mine are very different. I thought the whole | point of using functions was to provide a usable abstraction of a portion of | a program's logic. I therefore *conceptualize* a function long before I | write it, and don't feel the need to make it's source code explicit just | because I've caslled it somewhere in my (developing) program. Perhaps that is indeed the point - abstraction, and control of abstraction. I think you will agree that your choice of abstraction is a key question in your whole program design, not something where you'd just take all you get, willy-nilly. Where you want abstraction, functions are indeed useful. Where you do not, but you still need a function, you have lambda. These would often be functions that are so trivial that they can more economically simply stand for themselves. But in any case, you can ask "what do I get out of abstracting this", and the answer may just be "nothing". Donn Cave, donn at drizzle.com From tim.one at comcast.net Mon Jul 1 15:42:15 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 01 Jul 2002 15:42:15 -0400 Subject: python threads and the linuxthread pthread library In-Reply-To: <200207011843.OAA30115@test-area.com> Message-ID: [anton wilson] > ... > However, I am a bit confused on how threads interact with the python > interpreter at a low level. In general, if you have N threads, at any given time one of those threads is holding the GIL (global interpreter lock), and the other N-1 threads are blocked trying to acquire the GIL. No more than one thread can be running in the PVM at a time. A C module that knows for certain it won't be running the PVM can release the GIL to do some work in C (or Fortran, whatever), allowing some other thread to run in the PVM while it's doing its C (whatever) work. The Python implementation routinely does this around potentially blocking C-level I/O operations. > Is the Python Virtual Machine it's own thread? No. All threads run in the PVM, but the GIL serializes their PVM time. > How do threads aquire the global interpreter lock once they are awoken? I'm not sure what you mean by "awoken". Python doesn't normally put threads to sleep . Threads that don't hold the GIL are normally blocked trying to acquire the GIL. If by "awoken" you mean "become unblocked", then awakening and acquiring the GIL are exactly the same thing -- one doesn't precede the other. The details of how the GIL gets acquired live inside your platform thread implementation. On Linux, Python may use either pthread condition variables, or POSIX semaphores, to implement the GIL. > How exactly do the byte-codes for a particular thread get run by the > Python interpreter? See ceval.c. This isn't a thread issue beyond that threads in the PVM are serialized by the GIL. > Does each thread run the interpreter? Yes, but they're serialized via the GIL. From wade at lightlink.com Mon Jul 22 17:46:53 2002 From: wade at lightlink.com (Wade Leftwich) Date: 22 Jul 2002 14:46:53 -0700 Subject: Anybody using 4suite for xslt processing? References: Message-ID: <5b4785ee.0207221346.4311877a@posting.google.com> "Marko Faldix" wrote in message news:... > Hi, > > sometimes I think I am first man on earth want to process xslt. > > I got python on windows 2000 Server with iis and 4suite, I could change to > linux if necessary. > > > The following script: > > ############################################### > > from Ft.Xml.Xslt import Processor > > xslfilename = "abc.xsl" > xmlfilename = "abc.xml" > > path = "C:\\serverdirectory\\me\\python\\" > > > xslfile = path+xslfilename > xmlfile = path+xmlfilename > > > processor = Processor.Processor() > > processor.appendStylesheetUri(xslfile) > > result = processor.runUri(xmlfile) > > > print 'Content-type: text/html\n' > print result > > ############################################### > > throws this in browser: > > > ::: Using minidom > Traceback (most recent call last): > File "C:\home\marko\python\bxslt.py", line 15, in ? > processor.appendStylesheetUri(xslfile) > AttributeError: Processor instance has no attribute 'appendStylesheetUri' > > > But documentation contains method 'appendStylesheetUri'. Somebody any idea? > I am at the point that installation is ready and try to process our first > xslt to see that it can be used for it. I'm using 4xslt on win2k and it works well. However, the documentation is lagging way behind the code, and it took me some groveling through the 4suite mailing list before I could do this: ----------- from Ft.Xml.Xslt import Processor from Ft.Xml import InputSource TRANSFORM = """ """ processor = Processor.Processor() transform = InputSource.DefaultFactory.fromString(TRANSFORM, "http://okaynetwork.com/identity.xslt") processor.appendStylesheet(transform) def xform(s): source = InputSource.DefaultFactory.fromString(s, "http://okaynetwork.com/doc.xml") return processor.run(source) ------------------------- I believe Uche Ogbuji (Mr. 4Suite) has been updating the docs recently, but I haven't had a chance to check out the changes. However, if you are going to stay with Microsoft, their parser is fast, fast, fast, and you can use it via Mark Hammond's extremely excellent win32com module. -- Wade Leftwich Ithaca, NY From whisper at oz.net Wed Jul 3 18:45:59 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 3 Jul 2002 15:45:59 -0700 Subject: PythonWin + other GUIs = CRASH! In-Reply-To: <3D234007.1090103@gmx.de> Message-ID: That's because you end up with multiple event-handling loops, one per GUI. Who get's what events is a crap shoot. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Ingo Linkweiler > Sent: Wednesday, July 03, 2002 11:19 > To: python-list at python.org > Subject: Re: PythonWin + other GUIs = CRASH! > > > > > > > >try SCITE or IDLE > > > > IDLE crashes with Qt and pygame, too. It seems to be a general problem: > It is not possible to start a GUI-Toolkit, when the application or the > IDE is using a GUI itself. The only GUI which seems to work with most > IDEs is tkInter. PyQt, wxPython and Pygame will crash. > > Ingo > > -- > http://mail.python.org/mailman/listinfo/python-list From altis at semi-retired.com Wed Jul 17 22:08:59 2002 From: altis at semi-retired.com (Kevin Altis) Date: Wed, 17 Jul 2002 19:08:59 -0700 Subject: pickle performance on larger objects References: Message-ID: I'm quite surprised by your numbers, but perhaps it is because you didn't use a binary pickle? The companies sample included with PythonCard uses the flatfileDatabase module in the PythonCard framework to load and save a binary pickle file that is around 1.2MB, a little over 6600 records stored as one big list of 6600+ dictionaries, so single load and dump calls are used to get and save the data. On my machine, loading takes a fraction of a second. The original data is in XML format and another version of the data was output via pprint and both of those take dramatically longer to convert back to a usuable list of dictionaries in memory. If you are interested in exploring this further, contact me directly, and I can tell you how to run some additonal experiments. Then maybe we can summarize for the list. If you want to install MachoPython, wxPython Mac, and PythonCard on your system, you can just run the companies sample directly with the -l command-line option to enable logging. Alternatively, we can get the relevant data-centric parts of the flatfileDatabase module and the companies data set onto your box and you can play with it in a non-gui script. ka --- Kevin Altis altis at semi-retired.com http://www.pythoncard.org/ "Sam Penrose" wrote in message news:mailman.1026940226.16076.python-list at python.org... > On a recent project we decided to use pickle for some quick-and-dirty > object persistence. The object in question is a list of 3,000 > dictionaries > whose keys and values are short (< 100 character) strings--about 1.5 > megs worth of character data in total. Loading this object from a pickle > using cPickle took so long we assumed something was broken. > > In fact, loading is just slow. A list of 10,000 identical dictionaries > whose keys and values are short strings takes many seconds to load on > modern hardware. Some details: > i. A python process which is loading a pickle will use a lot of RAM > relative to the pickle's size on disk, roughly an order of > magnitude more on Mac OS X. > ii. Performance appears to scale linearly with changes in the size of > the list or its dicts until you run out of RAM. > iii.Python pickle is only about 5x slower than cPickle as the list > gets long, except that it uses more RAM and therefore hits a big > RAM-to-diskswap performance falloff sooner. > iv. You *can* tell a Mac's performance by its MHz. An 800 MHz PIII > running Windows is almost exactly twice as fast as a 400 MHz G4 > running Mac OS X, both executing the following code from the > command line. With 25 items in the dictionaries and 10K dicts > used, the former took just under a minute using cPickle, the > latter two minutes. > v. Generating a list of 3K heterogeneous dicts of 25 items (our real > data) by reading in a 750k text file and splitting it up takes on > the order of a second. > > Sample run on 400 MHz G4, 448 megs of RAM: > > >>> time_cPickle_Load() > dumping list of 10 dicts: > dumped: 0.00518298149109 > loading list of 10 dicts: > loaded: 0.1170129776 > dumping list of 100 dicts: > dumped: 0.0329120159149 > loading list of 100 dicts: > loaded: 0.849031090736 > dumping list of 1000 dicts: > dumped: 0.397919893265 > loading list of 1000 dicts: > loaded: 8.18722295761 > dumping list of 10000 dicts: > dumped: 4.42434895039 > loading list of 10000 dicts: > loaded: 133.906162977 > > #---code follows----------------// > def makeDict(numItems=25): > d = {} > for i in range(numItems): > k = 'key%s' % i > v = 'value%s' % i > d[k] = v > return d > > def time_cPickle_Load(): > import time > now = time.time > from cPickle import dump, load > filename = 'deleteme.pkl' > > for i in (10, 100, 1000, 10000): > data = [makeDict() for j in range(i)] > output = open(filename, 'w') > startDump = now() > print "dumping list of %s dicts:" % i > dump(data, output) > print "dumped:", now() - startDump > output.close() > input = open(filename) > startLoad = now() > print "loading list of %s dicts:" % i > x = load(input) > print "loaded:", now() - startLoad > input.close() > > > > From Gabe.Newcomb at noetix.com Mon Jul 15 11:22:16 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Mon, 15 Jul 2002 08:22:16 -0700 Subject: Generating .py from a .pyc: is it possible? Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6074@NOXMAIL.noetixad.com> I screwed up and deleted a python script of mine. I still have the compiled version, the .pyc. Is there anyway for me to regenerate the .py from it, so I make changes? Thanks, Gabe From tjreedy at udel.edu Fri Jul 12 17:54:49 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Jul 2002 21:54:49 GMT Subject: What went wrong in Python1.6 ? References: <6fttiuc7ligvbobpgcs41k7ek25vju8n59@4ax.com> Message-ID: > >The license was wrong. > > There were problems with GPL compatibility? Yes. If you want details, go to google groups archive. From duncan at NOSPAMrcp.co.uk Mon Jul 22 05:12:53 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 22 Jul 2002 09:12:53 +0000 (UTC) Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <190720021018041866%pecora@anvil.nrl.navy.mil> <3D385A46.6DC47857@astro.cornell.edu> Message-ID: Grant Griffin wrote in news:ah9p0o01ds at drn.newsguy.com: > For example: > > with self: > result=sin(t)*x**y+sqrt(z) # A pretend formula > > I don't know if there's a technical reason (in terms of either Python > grammar or C implementation) why this wouldn't work, but perhaps it's > not in Python because: > > 1) explicit is better than implicit > 2) there should be one--and preferably only one--way to do things It isn't in Python for a variety or reasons (your two among them), but perhaps more because there is no way in your scheme to tell which of result, t, x, y, and z are members of the self instance, and which are global (or in result's case local) variables. Languages which require you to declare all the member variables in advance can get away with this sort of usage, but they then introduce new problems. Even in C++ it can be impossible to tell whether a variable in a function is implicitly referencing a member variable or a global of the same name. An alternative which is proposed from time to time would be implementable: with self: result=sin(.t)*.x**.y+sqrt(.z) # A pretend formula This has the advantage of tagging the member variables, but is thought by many to reduce readability and be error prone. Perhaps someone should put it into a patch though so people could try it out. If Python supported this format you might even allow functions to default to assuming a 'with' block on their first argument. Then again, see your #1 above. Of course, Python being what it is, there are ways to simulate some of what people want without changing the language at all. Try the code below: ----- begin magic.py ----- # How to make methods magically access member variables. # import new from math import sin, sqrt def withself(method): '''withself(method) Converts an unbound method into a method where all global variables are assumed to come from the instance. Global variables are accessible only if the instance sets self.__builtins__=globals() Builtins are not accessible unless you do: self.__builtins__=__builtins__ ''' def callwith(self, *args, **kw): f = new.function(method.func_code, self.__dict__, method.func_name, method.func_defaults or ()) return f(self, *args, **kw) return callwith class C: def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z # Makes global variables visible to formulae self.__builtins__ = globals() def formula(self): return x + y - z formula = withself(formula) def updater(self): global x x += 1 updater = withself(updater) def formula2(self): return sqrt(y*z) formula2 = withself(formula2) test = C(3, 7, 2) print test.formula() test.updater() print test.formula() print test.formula2() ----- end magic.py ----- -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From cliechti at gmx.net Sat Jul 20 17:53:53 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jul 2002 23:53:53 +0200 Subject: Renting CPU time for a Python script References: <25c15ddd.0207190852.2aecc26c@posting.google.com> <25c15ddd.0207201216.46eddd73@posting.google.com> Message-ID: zbortolo at vt.edu (Zachary Bortolot) wrote in news:25c15ddd.0207201216.46eddd73 at posting.google.com: > Unfortunately the bottleneck > in my program lies with the PIL extension since I have to perform a > lot of putpixel and getpixel operations, which are quite expensive in > PIL. numpy/Numeric is very efficient on vectors and matrices. maybe you could convert the image, or parts of it, to a matrix and use Numeric to process it. function calls are relatively expensive, when you can formulate your algorithm with numpy you'll get the loop over the elements/pixels in C for free, which should give you some speedup (>>2). chris -- Chris From emile at fenx.com Thu Jul 11 20:10:57 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Jul 2002 00:10:57 GMT Subject: Transferring an excel file through HTTP References: <79b54d28.0207111451.35b583b2@posting.google.com> Message-ID: Chris > I have a question about clients (on windows) uploading Excel > spreadsheets (.xls) to a unix server. These spreadsheets contain > information that wil be used to store and update a database. I need to > be able to safely pass the information in the spreadsheet so that I > can parse it and update accordingly. However, when I upload through my > web page, the text that once was a nicely formatted excel spreadsheet > becomes jarbled and illegible. Passing the information (presumably > through a large string) messes it up understandably as there are text > format issues and such. I've explored such things as the COM and > win32com modules but am a little hesitant as my CGI script is not > operating on a windows platform. I'm using Python 2.2. Can someone > point me in the right direction? Thanks! > The easy answer is to save in excel as tab delimited output and upload that. Maybe someone else knows an easy answer to the hard answer? ;-) -- Emile van Sebille emile at fenx.com --------- From peter at engcorp.com Sun Jul 14 00:02:19 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 14 Jul 2002 00:02:19 -0400 Subject: Passing SAFEARRAY data type from win32com.client References: Message-ID: <3D30F7CB.1EB1182F@engcorp.com> Steve Greiner wrote: > > I am trying to automate Internet Explorer, and I need to use the Post > function. I can get IE to send a Post-method request, but the data > that it sends appears to be intrepreted as an incorrect type; in fact, > if I try to send a single character, it actually thinks it should send > 16 bytes. It appears to me that the value I'm passing as the Data > parameter is being passed as the wrong type. IE expects a SAFEARRAY > data type, and I think I've tried every Python type, but none of them > seems to convert correctly. I am using win32com.client with makepy > (thought I've also tried it without makepy). Can anyone tell me if > I'm attempting the impossible, or should I dig in and figure out what > I'm doing wrong? I have no idea. Please consider posting example code showing what you tried, so no one has to guess what you're doing. (I've been automating IE lately as well, but I have to say the above description sounds strange to me. I don't know why you would have to involve SAFEARRAY... aren't you just entering data into fields in a form, then doing a .submit() on it?) -Peter From simon at uggs.demon.co.uk Tue Jul 9 15:41:32 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Tue, 09 Jul 2002 19:41:32 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> Message-ID: <3d2b3c2f.3993392@news.dsl.pipex.com> On Tue, 9 Jul 2002 15:23:49 +0200, "Bo M. Maryniuck" wrote: >On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote: >> eval! > >Overkill. Unsafe. Ugly. Lame. > What do you mean by unsafe? Are you a troll? -- Simon Foster Cheltenham England From renez at lightcon.xs4all.nl Mon Jul 29 16:18:49 2002 From: renez at lightcon.xs4all.nl (renez at lightcon.xs4all.nl) Date: 29 Jul 2002 20:18:49 GMT Subject: Slow program exit on Dec Alpha 4.1 OSF References: Message-ID: Chris Liechti wrote: > renez at lightcon.xs4all.nl wrote in news:ahsfsk$36a$1 at news1.xs4all.nl: >> I'm trying to collect information from a cvs repository. >> Basically I visit every RCS file in the repository >> get tags:version with line=file.readline >> and build up the following dictionaries >> >> File[FileId] = name >> FileIndex[name] = (FileId , (branchetag (Bole, Bole)) ) >> tag[name] = (tagid,counter) >> tagindex[tagid] = name >> filetag[FileId, tagid] = version >> tagfile[tagid, FileId] = version > do you store a reference to the file object in one of those variables? do > you close the files after visiting them? I close the file > ... >> I cannot make head or tails out of this and probably most >> of you also not out of this message ;-( too. > maybe you could post some of the code or put it on a webpage, so that > people can comment on it. I went back to the machine and did some rtfm and a configure --with-dec-threads Same thing/problem configure without-threads and the problem went away. So I'm happy (for the moment) > chris > -- > Chris thanks for the responses Rene -- From pinard at iro.umontreal.ca Fri Jul 12 10:49:11 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 12 Jul 2002 10:49:11 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: <3D2E4FD6.CDEB601A@engcorp.com> References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: [Peter Hansen] > XML was adapted from SGML to meet several key goals. Among those was > the desire to make a format which was easily human-readable and editable > using simple tools like text editors. I do not think so. SGML already has these virtues, and much more than XML. The main goal of XML was to please machines, because full SGML is so difficult to parse. The price to pay to please machines was a loss of readability for humans. XML is so verbose that real information gets overwhelmed under tags. The fish often gets drawn in practice. This being said, XML has been immensely successful, at least in the democratic fields, because it is so easier to implement. Moreover, many people consider it is an acceptable compromise between humans and machines. But at least compared to SGML, we have to remember that it is a compromise away from humans and towards machines, and never turn the argument around. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From aleax at aleax.it Wed Jul 24 07:29:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 11:29:21 GMT Subject: Sockets for a file References: Message-ID: Teja Sastry wrote: > Hi, > > I would like to know if we can create a unix socket for a file (like > we do in C or C++ with struct sockaddr_un) > I want to wait on a file in python and trigger some function if the > file gets some data written in it by another program. > Please clarify if anybody has worked on this previously. I've done it, but not with sockets: >>> import os >>> os.mkfifo('/tmp/pappje') >>> f=open('/tmp/pappje') a wait here -- just as long as you want. At some point in another terminal window: echo ciao > /tmp/pappje causes the Python interactive interpreter to wake up, and prompt again -- whereupon you can, e.g.: >>> print f.read() ciao >>> f.close() >>> Alex From john.abel at pa.press.net Fri Jul 5 04:08:31 2002 From: john.abel at pa.press.net (John Abel) Date: 05 Jul 2002 09:08:31 +0100 Subject: Securing SimpleXMLRPCServer? Message-ID: <1025856511.20586.13.camel@lestat.howden.press.net> I've set up an server, and client, which works OK, but now I want to secure the server. Is there a way I can query the IP of the connecting client? I've looked through the documentation, and can see that SimpleXMLRPCRequestHandler is based on BaseHTTPServer, which has client_address, but I can't seem to get access that variable. Any pointers would be much appreciated. John From oren-py-l at hishome.net Fri Jul 12 01:54:40 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 12 Jul 2002 01:54:40 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: <3D2E4FD6.CDEB601A@engcorp.com> References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <20020712055440.GA83544@hishome.net> On Thu, Jul 11, 2002 at 11:41:10PM -0400, Peter Hansen wrote: > Jeremy Bowers wrote: > > > > (Thought: XML should never be your *first* choice of file format. It is > > the choice of *last* resort, when you absolutely *need* easy parsing in > > multiple languages or environments and can't get it any other way. It is > > then a much better choice then other formats, but only under those > > limited, albiet extremely popular, conditions.) > > I have to disagree with those who say, in effect, that XML is such > an unsuitable technology that it is truly a last resort. > > XML was adapted from SGML to meet several key goals. Among those > was the desire to make a format which was easily human-readable > and editable using simple tools like text editors. XML combines all the inefficiency of text-based formats with most of the unreadability of binary formats :-) > In addition, it leaves open the possibility of very easily > processing the data using one of the steadily growing number > of XML utilities. A growing number of utilities is a sign that a format is popular, not that it is good. In fact, it may be argued that a simpler format would actually need less tools. adding-more-oil-to-the-religious-war-fire-ly yours, Oren From marklists at mceahern.com Fri Jul 12 18:11:59 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 17:11:59 -0500 Subject: switch recipe? In-Reply-To: <2cIX8.74333$vm5.2697823@news2.tin.it> Message-ID: > Wouldn't you get exactly the same observable effect from > the simpler function: > > def make_switch(*args): > """Return an iterator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") > return iter(args) > > ...? No, sadly. The key to make_repeat() (as I've renamed it) is that it repeatedly loops through args. The above solution would suffice if you only wanted to iterate over the set at most once. Of course, I'm straining to come up with real world examples where this is helpful, but I take that as a sign of my lack of imagination. In general, this recipe, if it's worthy to be called such, is useful when you want to weave together a finite set of values of a given length (n) with a different set of values of a different length (m) and for the i-th element of n, you want it to be weaved with the len(m) modulo i-th element of m. How's that for a fancy definition? Of course, Alex, if there's a more elegant and simple way to do this, I have no doubt you'll come up with it! Cheers, // mark p.s. for what it's worth, here's the latest code and demo: #! /usr/bin/env python from __future__ import generators def make_repeat(*args): """Return a generator that repeatedly loops through args.""" if not args: raise TypeError("make_repeat() takes at least one parameter.") def repeat(): while args: for a in args: yield a return repeat() def colorize(value, *colors): repeat = make_repeat(*colors) template = "<%(color)s>%(item)s" items = [] for item in value: color = repeat.next() formatted_item = template % locals() items.append(formatted_item) return ''.join(items) s = colorize("testing", "black", "red", "green", "blue") print s expected = "t"\ "e"\ "s"\ "t"\ "i"\ "n"\ "g" assert s == expected - From dbasch at yahoo.com Tue Jul 30 21:36:36 2002 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 30 Jul 2002 18:36:36 -0700 (PDT) Subject: Win32/Python serial port event character problem In-Reply-To: Message-ID: <20020731013636.9793.qmail@web20810.mail.yahoo.com> Thanks alot. That answers my questions. According to this: http://www.tetraedre.com/advanced/serial2/msdn_serial.htm many different types of flow control can be used at the same time. It does make sense to leave the lines high if they are not being used. Thanks for the help, Derek Basch --- Chris Liechti wrote: > Am 30.07.2002 22:19:35, schrieb Derek Basch > : > >I had a quick question about flow control in > >serialwin32.py. On line 120,: > >http://www.geocities.com/dbasch/flowcontrol.txt > >if RTSCTS is selected by the user then RTS and DTR > are > >enabled (with handshaking). Why are both RTS and > DTR > >enabled? > > the idea if rtscts is to enable HW-handshake. there > is 5 and 7 > wire handshaking (RTS/CTS and those plus DTR/DSR). > i have to admit that i never use HW- handshake, i > included > that option for completeness. if if's not doing > what's generaly > understood under HW handshake, then they can be > changed. > > >If RTSCTS is not selected by the user then > >the RTS and DTR lines are still enabled but nothing > is > >done with them. Can you explain why? > > if you don't use hardware handshake, then the lines > should > be high, signaling that there is a programm running. > the pins go high by default, i think, but i wanted > to be sure. > i have embedded projects that are powered by the > control > lines and thus setting them to high is very > desirable for me. > (one board can be reset through the RTS line etc.) > > chris __________________________________________________ Do You Yahoo!? Yahoo! Health - Feel better, live better http://health.yahoo.com From tjreedy at udel.edu Thu Jul 11 22:12:54 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Jul 2002 02:12:54 GMT Subject: A better self References: Message-ID: "Huaiyu Zhu" wrote in message news:slrnairg48.c4b.huaiyu at gauss.almadan.ibm.com... > What is required is a convention that allows shorter notions when necessary > in a disciplined way. I find that switching from self to _ is quite > satisfactory for this purpose under the right circumstances. And, as such, > there is no need to extend Python's syntax for this purpose, which was the > initial topic of this thread. Another alternative is to copy instance vars to local vars and then use the latter without the 'self.' or 'self.__' prefix. If there are multiple references to the instance vars within a method, this may be just as fast or faster. IE def quadsolve(self): a,b,c = self.a, self.b, self.c discrim = b*b - a*c ... Terry J. Reedy From spam at ob_scure.dk Mon Jul 8 17:57:58 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Mon, 08 Jul 2002 23:57:58 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: Message-ID: <3D2A0AE6.6060401@ob_scure.dk> Stephan R.A. Deibel wrote: > On Sat, 6 Jul 2002, Laura Creighton wrote: [snip - cool links] Beeing away from this group for 6 months, I had almost forgotten how kind and helpful people here is - that goes for all of you, thanks. Since I'm quite busy right now (and I'm on vacation, damn it :-) and is leaving for Praha, Czech Republic on Thursdag, I might not be able to reply to every post. However do know that I will utilize my own (and Google's) mirror of this thread in the comming weeks. Cheers! (already looking forward to cheap Budwiser and Urquell! :-) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From jdhunter at ace.bsd.uchicago.edu Mon Jul 29 12:38:13 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 29 Jul 2002 11:38:13 -0500 Subject: Newbie: How to touch "global" variables In-Reply-To: <3D4568D5.3254F968@lmco.com> (Jeff Layton's message of "Mon, 29 Jul 2002 12:09:57 -0400") References: <3D4568D5.3254F968@lmco.com> Message-ID: >>>>> "Jeff" == Jeff Layton writes: Jeff> Hello, I've got a defeinite newbie question (I searched Jeff> some, but to be honest I don't know what keywords to search Jeff> on - which has brought me here :). I want a module to be Jeff> able to "touch" a variable defined globally (from the main Jeff> script). I don't necessarily want to change the value ofthe Jeff> variable, but to query it. For example, get the length. How Jeff> do I do this? The received wisdom is that you rarely if every want/need to use a global variable. Singletons/Borgs can do anything you'll want your global variable to do, and will be cleaner, easier to maintain and will win you friends, women and respect. Search google for 'singleton design pattern' And take a look at Alex Martelli's "Singleton? We don't need no stinkin' singleton: the Borg design pattern" http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 John Hunter From loewis at informatik.hu-berlin.de Mon Jul 29 05:21:29 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 29 Jul 2002 11:21:29 +0200 Subject: default setting of unicode set References: <3D45000F.5040300@gmx.net> Message-ID: mathias palm writes: > It is possible to set a default unicode (set to ascii) in > site.py. This is clearly a setting by site. For programs which my use > different unicode charackter set it would be useful to have a per user > or better still a per program setting. I did not find any possiblity > to do this. The function, sys.setdefaultencoding() which sets the > default unicode is even deleted in site.py. That is on purpose: Explicit is better than implicit. If you have a Unicode string, and you want to convert it to a byte string, invoke its .encode method, instead of implicitly relying on automatic conversion. > I am sure there is a reason for this behaviour, I cant see it > however. Can anybody explain or tell me where to read about it? Why > not setting the default unicode in a file like .pythonrc? The user's preferred encoding is already available to a Python program; there is no need to require the user to put her preferred encoding in yet another place. Unfortunately, it is not straight-forward to obtain the preferred encoding in a portable way. Here are some strategies: - on Unix, use locale.nl_langinfo(locale.CODESET) to find the user's encoding. Notice that you may have to invoke setlocale for this to work correctly (e.g. on Solaris), and that not all Unix variants provide this function. - on Windows, use locale.getdefaultlocale, ignoring the language result of that. This actually may work on Unix, too - but then, it may also fail. > Is there a possibility to set a unicode default later on? No. Just don't use the default. Be explicit about your encodings in your program. Use the user's preference where appropriate - only the application programmer can know whether using the user's preference *is* appropriate (for example, some data formats may require a fixed encoding, such as UTF-8, independent of the user's preference). Regards, Martin From otis_usenet at yahoo.com Mon Jul 22 19:27:18 2002 From: otis_usenet at yahoo.com (OtisUsenet) Date: 22 Jul 2002 16:27:18 -0700 Subject: urllib2 won't raise exceptions Message-ID: <5606b639.0207221527.12f91366@posting.google.com> Hello, I am trying to use urllib2 to make HTTP POST requests and a) retrieve HTTP status, and b) check for any exceptions. 1) I don't see a way to get the status code back from urllib nor urllib2 (and I read that this will be impossible to get from them and that httplib should be used instead). 2) I read that if something fails, URLError or HTTPError will be raised. So I have the code to catch them and print someting. However, nothing ever gets printed, even if I request pages that give '500 Server Error', like in the case below. Am I doing something wrong? Thanks. (pardon my indentation, I pasted this a few times...) from urllib2 import * def sendRequest(self): try: # NB: this URL gives "500 Server Error" urlObject = \ urllib2.urlopen('http://www.clr.utoronto.ca/cgi-bin/doc/show/doc=Cross.Rodney') response = urlObject.read() urlObject.close() return response except URLError, msg: print "URLError: ", msg; except HTTPError, msg: print "HTTPError: ", msg; except Exception, msg: print "EXCEPTION" except Error, e: print "ERROR" From anton.wilson at camotion.com Wed Jul 31 10:00:41 2002 From: anton.wilson at camotion.com (anton wilson) Date: Wed, 31 Jul 2002 10:00:41 -0400 Subject: global interpreter lock not working as it should In-Reply-To: <20020730202014.A3224@unpythonic.net> References: <200207302247.SAA21093@test-area.com> <20020730202014.A3224@unpythonic.net> Message-ID: <200207311359.JAA15020@test-area.com> On Tuesday 30 July 2002 09:20 pm, jepler at unpythonic.net wrote: > > On Tuesday 30 July 2002 07:18 pm, brueckd at tbye.com wrote: > > > Quick tangential question: if there's no blocking of any kind, why are > > > you using threads, anyway? Off the cuff thinking says this seems like a > > > misuse of them. > > On Tue, Jul 30, 2002 at 06:48:40PM -0400, anton wilson wrote: > > For a real-time system. ;) It will work. It would just be nice if they > > switched exactly every 10 byte codes becuase that means they only use > > about 10 to 20 milliseconds each. > > Realtime? Really? So can you tell me what the upper-bound on the runtime > of > > >>> x = 3 > > on the hardware you're targeting? > > Jeff Good question. You have any reasons why we should not use python? From aleax at aleax.it Sun Jul 7 12:08:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 16:08:35 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D282413.1010801@ob_scure.dk> <3D285612.762E590C@engcorp.com> Message-ID: <7IZV8.42327$Jj7.1163548@news1.tin.it> Peter Hansen wrote: ... >> award, http://www.activestate.com/Corporate/Awards/ActiveAwards.html ... > Unfortunately it is not possible to vote only for the Python programmers, Didn't USE to be, but they fixed it -- you can now choose "abstain for each category" for each language you don't want to vote on, and indeed it's now the default for each category. > making it impossible for me to vote in an ethical manner. I know > nothing of most of the other areas (Perl, etc.) and I won't resort > to random voting just to get in my votes for Paul, you, or the others. This does you honor and indeed many others must have felt the same way -- some, enough to let ActiveState know, since ActiveState did immediately respond by fixing the page accordingly. > (I assume I didn't miss something there. I left the others > unselected and it refused my submission.) It was that way until a few days ago, but now it's fixed. Retry... Alex From krissepu at vip.fi Tue Jul 16 16:22:49 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Tue, 16 Jul 2002 23:22:49 +0300 Subject: SOLUTIONS: Parsing nested strings Message-ID: <3D348099.9B4B63BA@vip.fi> Thank you all for your help and inspiration! It is payback time ;) I have tried past two months to create parser that returns strings limited by two different letters. The strings can be nested. I considered recursive call of regular expression to be too slow and decided to use mxTextTools 2.1 beta2 and the latest alpha of Simpleparse 2.0. Below are three solutions I found. Note that Simpleparse creates different tagtable as the "manually" found. Further ideas to be implemented: 1) Input of limiting letters as parameters (easy) 2) Unicode support 3) Test for equal amount of limiting letters before calling of parser (will this speed up the solution ?) 4) Parsing one line at a time without looping thru lines of the text with "while" or "for" (maybe "None, AllNotIn, '()\n'" ) One development idea to mxTextTools: 1) Instead of using list of tables to recurse, would it be possible to use "global jump" to outside of current table ? --- solution 1 starts (with limiting letters)--- from mx.TextTools import * text = "aa(AA)a((BB))aa((CC)DD)aa(EE(FF))aa(GG(HH(II)JJ)KK)aa" tables = [] # used for recursion only tab = ('start', (None,Is+LookAhead,'(',+1,'nesting'), # If next character is "(" then recurse (None,Is,')',+1,MatchOk), # If current character is ")" then stop or return from recursion (None,AllNotIn,'()',0,'start'), # Search all characters except "(" and ")" 'nesting', ('group',SubTable+AppendMatch,((None,Is,'(',0,+1), # Since we have looked ahead, collect "(" -sign (None,SubTableInList, (tables,0)))), # Recurse (None,Jump,To,'start')) # After recursion jump back to 'start' tables.append(tab) # Add tab to tables if __name__ == '__main__': result, taglist, nextindex = tag(text,tab) print taglist --- solution 1 ends --- --- solution 2 starts (without limiting letters) --- from mx.TextTools import * text = "aa(AA)a((BB))aa((CC)DD)aa(EE(FF))aa(GG(HH(II)JJ)KK)aa" tab = ('start', (None, Is+LookAhead, ')', +1, MatchOk), # When character ")" is seen stop recursion (None, Is, '(', 'letters', +1), ('group', SubTable+AppendMatch, ThisTable), # Recurse (None, Skip, 1, 0, 'start'), # Last character in recursion was ")" so jump over it back to 'start' 'letters', (None, AllNotIn, '()', 0, 'start')) # Collect all characters except "(" and ")" result,taglist,next = tag(text, tab) print taglist --- solution 2 ends --- --- solution 3 starts (Simpleparse solution) --- from simpleparse.parser import Parser from mx.TextTools import * declaration = r''' >line< := (a/match)+ match := '(', line, ')' := -[()] ''' text = "aa(AA)a((BB))aa((CC)DD)aa(EE(FF))aa(GG(HH(II)JJ)KK)aa" parser = Parser(declaration) success, children, nextcharacter = parser.parse(text, production = "line") print_tags(text,children) --- solution 3 ends --- -pekka- From sholden at holdenweb.com Fri Jul 26 23:26:29 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 26 Jul 2002 23:26:29 -0400 Subject: calendar lameness! References: Message-ID: "James J. Besemer" wrote in message news:mailman.1027735971.17108.python-list at python.org... > > Tim Peters wrote: > > > [James J. Besemer] > > > ... > > > And don't get me started on when Easter is. > > > > That's easy! Sunday. > > Yeah, but which Sunday? > > Hint: the Catholic church went to great lengths attempting to define Easter in > such a manner that (among other things) it could never occur on the same day > as Passover. > The Catholic church also went to great lengths to get Galilleo Galilei to recant, which he eventually, albeit grudgingly, did. Since I don't know how the Jewish religion decides when Passover is, your statement doesn't convey that much. It's the astronomers and the astrologers I feel sorry for in all this, since all the calendar really represents is an agreement to label particular moments. Since one second follows another with remorseless inevitability (absent Guido's time machine), the real problem is correct labelling. Even an apparently simple problem such as keeping track daylight savings time eventually burgeoned (as it did in the case of SunOS) into a whole subsystem, so ${deity}help me if I have to keep track of ten-day gaps. Couldn't we just all agree to call the big bang zero, and count from there? [Answer: no -- even those who agree there *was* a big bang don't agree-on when]. 256-bit-integers-might-do-it-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From cpbotha at i_triple_e.org Tue Jul 30 10:26:33 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Tue, 30 Jul 2002 14:26:33 +0000 (UTC) Subject: Searching for email address References: Message-ID: In article , Graeme Longman wrote: > I'm writing some code which searches html for email addresses. Does > anyone out there have a good regular expression syntax for searching for > the email string, I'm sure this must've been done a few times before. Excuse my curiosity, but what are you going to do with this code? :) -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From rob Sat Jul 20 10:19:22 2002 From: rob (Rob Andrews) Date: Sat, 20 Jul 2002 14:19:22 GMT Subject: text adventure game module for Python References: Message-ID: > I post this to see if anyone finds this an interesting project, and > would be interested in seeing it fully developed. Perhaps something > like this would have uses beyond text adventures. Obviously they are > mostly a thing of the past. > I have friends who play with MUDs every day, and half of them are into scripting and such for the MUDs and clients they play. I'll refer them to this thread so they can find out about your idea. Besides, there's much to be learned from programming for text adventures. It's a good project for programming students to put some time into. Rob Andrews http://uselesspython.com From gerhard.haering at gmx.de Tue Jul 9 23:14:35 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 10 Jul 2002 05:14:35 +0200 Subject: How to grab a part of web page? In-Reply-To: References: Message-ID: <20020710031435.GC1965@lilith.my-fqdn.de> * William Park [2002-07-09 22:31 +0000]: > A wrote: > > Hi, > > Is it possible to download only a part of web page? > > Say I need to find out an information about a customer that starts > > at 1500 byte position and ends at 2000 byte position. If the whole > > page has about 100 kb it seems to me waste of time to load all the > > page. > > What is the best, yet easy, solution? > > Is it possible to use httplib or necessary socket module? > > Thank you for help. > > Ladislav > > I think it's possible. When I use 'wget -c' to download HTML, sometimes I > see it start from an offset, rather than from the beginning. Doing this while having a packet sniffer running showed me what the corresponding HTTP header is. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.6 ?C Wind: 1.7 m/s From mhuening at zedat.fu-berlin.de Mon Jul 1 02:07:55 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 1 Jul 2002 06:07:55 GMT Subject: Getting the XP clipboard in tkinter References: <3D1F1A81.95602DE0@tds.net> Message-ID: "Edward K. Ream" wrote in news:3D1F1A81.95602DE0 at tds.net: > The > following two statements also take exceptions: > > s = app().root.selection_get("clipboard") > s = app().root.selection_get(".") > Did you try this: root.selection_get(selection="CLIPBOARD") Worked for me... Matthias From cappy2112 at yahoo.com Sun Jul 21 12:36:24 2002 From: cappy2112 at yahoo.com (Tony C) Date: 21 Jul 2002 09:36:24 -0700 Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? Message-ID: <8d3e714e.0207210836.7f8a51c8@posting.google.com> I've searched through this newsgroup and saw several references for the Oreilly book "Learning Python". I've noticed it was originally published in 1999, and I am wondering if it is still a good place to start, for a programmer who wants to learn Python, since Python has undergone several new releases, 2.2.1 being just a few months old. thanks tony From neal at metaslash.com Thu Jul 11 22:16:12 2002 From: neal at metaslash.com (Neal Norwitz) Date: Fri, 12 Jul 2002 02:16:12 GMT Subject: uncaught TypeError exception in re module or redemo.py References: Message-ID: On Tue, 09 Jul 2002 02:26:08 -0400, Kevin Altis wrote: >>>> re.compile('([a-') > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\Lib\sre.py", line 178, in compile > return _compile(pattern, flags) > File "C:\Python22\Lib\sre.py", line 226, in _compile > p = sre_compile.compile(pattern, flags) > File "C:\Python22\Lib\sre_compile.py", line 430, in compile > p = sre_parse.parse(p, flags) > File "C:\Python22\Lib\sre_parse.py", line 623, in parse > p = _parse_sub(source, pattern, 0) > File "C:\Python22\Lib\sre_parse.py", line 318, in _parse_sub > items.append(_parse(source, state)) > File "C:\Python22\Lib\sre_parse.py", line 583, in _parse > p = _parse_sub(source, state) > File "C:\Python22\Lib\sre_parse.py", line 318, in _parse_sub > items.append(_parse(source, state)) > File "C:\Python22\Lib\sre_parse.py", line 424, in _parse > if this[0] == "\\": > TypeError: unsubscriptable object I posted a patch which seems to work: http://python.org/sf/580386 Neal From martin at v.loewis.de Mon Jul 22 16:32:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 22 Jul 2002 22:32:05 +0200 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > martin at v.loewis.de (Martin v. Loewis) writes: > > You can put a callable object in sys.modules. Module objects > > themselves are not callable. > > Is this documented somewhere? I don't see it in the obvious places. sys.modules is documented in the import statement, which also documents that further imports will first look in sys.modules. A few places mention that sys.modules is a dictionary; from that, it follows that you can modify it. Then, it also follows that if you put a callable object into sys.modules, that you can call the result of an import. Regards, Martin From bokr at oz.net Sat Jul 20 01:45:24 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Jul 2002 05:45:24 GMT Subject: A better self References: Message-ID: On Tue, 9 Jul 2002 15:10:59 -0700, "David LeBlanc" wrote: >I notice that in every discussion of self, there's always a '.' in there. >So, why not make a leading '.' mean self? AFAIK, it's otherwise currently >illegal. The only drawback that I can think of is that it's less visible as >a first argument for class defs. > >class foo(): > def __init__(., me, me2, me3) > .a = me > .b = me2 > .c = me3 > def fee(.) > print .a, .b, .c > def bar(.) > .fee() > >What I like about it is that it's resonant with the use of '.' to denote >members/components of modules (i.e: sys.path) and suggests that the >identifier is a member of the local "capsule" (or class scope if you >prefer). I see it as answering the needs of both camps: it's easy to typy, >unobtrusive and yet supports the "belt and suspenders" crowd who are not >comfortable with an implied self. > >Before you all react (programmers can be SO conservative), please think >about it! > Ok, I thought about it some ;-) I think I may even have proposed or seconded virtually the same self-less-dot in the past, so I'm not going to criticize that too much, but I think there is more to think about ;-) ISTM that self in self.x is really a named name-space selector identifying a list of "directories" to search in orderly fashion for the appended 'x', or a default place to bind 'x' if not already bound. A bare 'x' implies a search through another namespace, also a list of "directories", depending on context. (By quoting I mean that some may not literally be directories). If these lists of directories could be exposed simply for purposes of declaration and access, we might be able to do some interesting things. Suppose 'namepath' were magically defined in all execution contexts to be the list of directories to search for a bare name in that context (i.e., pretty much what dir() sees now). Hence namepath[0] would always be the local namespace first accessed for a bare name, unless other factors apply. In a method, 'self' would normally be found in namepath[0], and self.x would be found in self.namepath[0] if it was an instance attribute, and self.namepath[1] if it was in self.__class__.__dict__, etc. Now if namepath were dynamically modifiable, you could get bare name access to instance attributes as in this example: class FOO: def __init__(self, v): self.v = v # old style init def myMethod(self): x = 123 # default local namepath.insert(0, self.namepath[0]) y = 456 # bare means self.y here!! print v, x, y # found in namepath[0], namepath[1], and namepath[0] resp. namepath.pop(0) # back to default print self.v, x, self.y # duplicate previous output An alternative (additional) way to spell the above namepath operations might be: def myMethod(self): x = 123 # default local with self.namepath[0]: # [1] y = 456 print v, x, y print self.v, x, self.y # [2] duplicate previous output [1] meaning namepath.insert(0, self.namepath[0]) until dedent. A list of directories might also be allowed for "with ... :" [2] dedent accomplishes namepath.pop(0) if it's a with-block # back to default Note that namepath always appears locally as if namepath == namepath[0]['namepath'] This still leaves "global x" to be handled generally in terms of namepath. IOW, a kind of private namepath.insert(0, namepath[-1]) for 'x' but not all names, and no need to search beyond the one directory. The general problem is to control where a bare 'x' will be re/bound for assignment. Perhaps a placement function, e.g., place('x', namepath[-1]) # effect of "global x" Thus the equivalent of the default for any bare name would be place('name', namepath[0]) Given the above, we are perhaps in a position to write place(('x','y'), namepath[1]) and expect to use it with nested scopes, e.g., def foo(): def init_xy(): place(('x','y'), namepath[1]) # force binding in immediately enclosing scope f = file('blah') # local f goes to namepath[0] # just a weird example x, y = map(int, f.readline().split()) # x and y bindings are created in enclosing scope def bar(dx,dy): with namepath[1]: # could/should use place x += dx y += dy If you wanted to specify name-specific lookup search paths it could be like place: lookup(('x','y'), namepath[1:], {'x': 'no NameError for x'}) # y will raise NameError if not found. I am implying that default assignment goes to namepath[0] unless place() has defined other places for the name in question, and that lookup by default does not just go from local to global, but through lexically enclosing scopes in between (as found in the default namepath list). Additionally, namepath can be modified dynamically, which will control search for names, unless overridden for specific names by lookup(). Also, for a given statment, rebinding should occur in the same namepath directory where a lookup succeeds for the same name, so that x += 1 will not create a local based on an 'x' in an enclosing scope. However x = 1 would bind in namepath[0] unless overridden by a place('x', somewhere). This would allow bar() above to leave out the "with namepath[1]:" statement. However, place() might be better optimizable, since it would not change default lookup for dx and dy. For convenience, namepath(n) could present the relevant dictionary as a virtual "self" of a virtual object whose attributes are stored in that directory. I.e., namepath(1).x = 123 would be equivalent to namepath[1]['x'] = 123 which would bind x in the immediately enclosing scope. This is hot OTTOMH, offered in the hope of stimulating useful and/or enjoyable discussion. ISTM these issues are bound (non-Python sense ;-) to play an evolving role in Python given nested scopes etc. Obviously a naive implementation of the above would have a lot of overhead. OTOH, place() and lookup() might provide optimization opportunities. Hm, a further thought: If place() had an optional keyword argument named 'prop', we could write place('p', myModule.namepath[0], prop=0) # ensure that p is not already a property at myModule.p p = property(get_p, set_p) # myModule.p is property object itself here place('p', myModule.namepath[0], prop=1) # myModule.p triggers property methods after this or if we know p is ordinary or nonexistent, just myModule.p = property(get_p, set_p) # myModule.p is property object itself here place('p', myModule.namepath[0], prop=1) # myModule.p triggers property methods after this and expect writing myModule.p to trigger the get_p or set_p functions. If you wanted to rebind p in that directory, you would have to do another place('p', ... prop=0). One way to do this, and keep ordinary lookups fast, might be to associate a flag byte with names in dictionaries, so that it's a one-instruction matter to decide whether special processing such as for properties is required. A C switch on this byte could also handle special-casing for slots, I would imagine. The place() function would change bits in the flag byte. With this methodology for properties, the magic actions could be triggered on any access to a name via any specified directory, not just class attribute directories accessed via instances. Sharp tools are dangerous, of course ;-) I'm not sure whether tying property magic to name lookup is a better idea than tying the magic to the looked-up object and its state independent of access path, but that is another discussion. Regards, Bengt Richter From piet at cs.uu.nl Fri Jul 12 08:03:25 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 12 Jul 2002 14:03:25 +0200 Subject: What went wrong in Python1.6 ? References: Message-ID: >>>>> Roy Smith (RS) writes: RS> Rhymes wrote: >> Now I ask my self: what went wrong in that release? Where i could find >> some further infos about this "miscarriage" ? RS> As far as I know, nothing was really "wrong" with 1.6, other than RS> timing. IIRC, the final release announcement for 1.6 came out the very RS> same day that the alpha 2.0 release announcement was made. Most people RS> were running 1.5.2 and didn't see the point in upgrading to 1.6 now and RS> then 2.0 a short time later, so they just waited for 2.0 to go final. The license was wrong. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From tim.one at comcast.net Tue Jul 16 17:12:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 16 Jul 2002 17:12:56 -0400 Subject: map del efficiency python2.2 and 2.1 In-Reply-To: Message-ID: [John Hunter] > I have a file formatted like > > word1 int1 > word2 int2 > > with 800,000+ lines like that. I want to load that file into a map > > m[word] = int > > and my original implementation was quite slow. ... > In the process of profiling, however, I found something surprising. > Most of the total execution time of the code is spent clearing the map > from memory, after all the lines in my script have executed (ie, the > equivalent of calling __del__ on a dictionary type. ... Before trying anything else, rebuild with pymalloc enabled. We've seen many cases where the platform free() ends up in seemingly quadratic-time behavior when deleting gazillions of objects, presumably while trying to coalesce them into larger free blocks. pymalloc usually fixes that. Would also be interesting to try this under current CVS Python (where pymalloc is enabled by default, and handles strings too). From tim at bladerman.com Sun Jul 28 15:23:51 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sun, 28 Jul 2002 19:23:51 GMT Subject: Guide to the python interp. source? References: Message-ID: "Andreas Kostyrka" > the sidefects of it. An other possibility would be to generate a good >> looking errormessage. Because it is likely a mistake. >Or you forbid also constructs like: >sys.stdout.write("Hello World\n") No I don't I wouldnt prevent it in every case, just when the parameter is actually assigned a value by the function. But this is not an issue since I wont do it that way... Tim From see_reply_address at something.invalid Thu Jul 4 21:47:49 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 13:47:49 +1200 Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <3D2487CB.9000102@gmx.de> Message-ID: <3D24FAC5.3050406@something.invalid> Ingo Linkweiler wrote: > > I know that I can use a while loop with break instead of repeat-until. I > am using it, but I just think a repeat-until looks better. The trouble with repeat-until is that the entire loop always executes at least once, even if the stopping condition is true at the outset. The more experience you get at programming, the more you come to realise that situations where this is the right behaviour are extremely rare, and in the vast majority of cases, writing a loop that way is asking for a bug. On the other hand, a situation that *is* very common is a loop-and-a-half, with the exit condition in the middle. So far, I've never seen *any* really good loop-and-a-half structure in any language, and I think Python has a chance to be truly innovative here. The syntax I favour at the moment for Python looks like while: line = f.readline() gives line <> "": do_something() Some day I'll get around to PEPping this... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From roy at panix.com Tue Jul 2 22:26:00 2002 From: roy at panix.com (Roy Smith) Date: Tue, 02 Jul 2002 22:26:00 -0400 Subject: Comments in pickles? Message-ID: I've got a file parser that returns a data structure. As part of a regression test suite, I'm going to parse several sample files and save the resulting data structures as pickle files to compare against future versions. I want to check those pickles into CVS. Our usual practice is to imbed the CVS id string ($Id: ) in every checked-in file as a comment. Is there any way to do that with a pickle? Does a comment convention exist which cPickle.load() understands? From maxm at mxm.dk Tue Jul 2 02:28:59 2002 From: maxm at mxm.dk (Max M) Date: Tue, 02 Jul 2002 08:28:59 +0200 Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: <3D21482B.7060004@mxm.dk> Fredrik Lundh wrote: > well, someone recently added > > "TenaciousD rocks your socks off" > > to the front page, so it's not entirely dead. Yuo just made me spill my morning cofee over my keyboard. Thank you very much ! regards Max M From ods at fep.ru Mon Jul 22 10:08:26 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Mon, 22 Jul 2002 18:08:26 +0400 (MSD) Subject: Webmin-alike cgi script and security In-Reply-To: <20020722133609.GB2610@software.plasmon> Message-ID: On Mon, 22 Jul 2002, Dave Swegen wrote: DS> The scripts themselves are run as the default webserver DS> user, and take DS> care of stuff like authentication and basic sanity checking. DS> DS> If all input checks out an external script is called using DS> sudo to gain DS> root privs. Any data that should be provided is pickled and Adding webserver default user to sudoers is a bad thing anyway. It's better to use suexec with unique user, that will be used for this script only. DS> stored in a DS> file with a unique name, which is then the only argument to DS> the sudo'ed DS> script. Depending on the return value any return data is DS> picked up again DS> by the cgi script from a pickled data structure with the DS> same name. -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From gerhard.haering at gmx.de Tue Jul 16 05:12:36 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 16 Jul 2002 11:12:36 +0200 Subject: uniform interface for MySQL & MSSQL In-Reply-To: References: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> Message-ID: <20020716091236.GA3845@lilith.my-fqdn.de> * Alex Martelli [2002-07-16 09:02 +0000]: > Johann wrote: > > I found this module have no cursor.seek(nr) method. :( > > Method seek is not part of the DBAPI standard, It's one of the very useful optional features described in PEP 0249 :-) > so it's hardly surprising that DBAPI compliant modules may lack it > :-). The next versions of at least MySQLdb, pyPgSQL, PySQLite and mxODBC will have it. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From pinard at iro.umontreal.ca Mon Jul 8 09:09:12 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 09:09:12 -0400 Subject: stackless python In-Reply-To: References: Message-ID: [Tim Peters] > [...] Python's generators are between Icon's generators and Icon's > co-expressions: [...] BTW, Neil Schemenauer had no trouble rewriting all > "the usual" coroutine examples to use Simple Generators instead. [...] Are these examples available for us to browse? Just a bit curious... -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 31 17:15:51 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 31 Jul 2002 21:15:51 +0000 Subject: source installation issue Message-ID: <200207312016.g6VKGC011684@helios.gatwick.geco-prakla.slb.com> On Wednesday 31 Jul 2002 6:39 pm, mimurra3 wrote: > All, > > I am attempting to install Python from source on my Mac OS-X system. I > downloaded the tar file to my desktop and expanded it there. I ran > './configure,' 'make,' and 'make install' without any issues. However, the > only way I can get the interpreter to start is by going to /usr/local/bin > and typing './python' On my Linux systems at work Python can be started I know nothing of Macs but this sound's like the PATH enviroment variable on this machine does not include /usr/local/bin, and your user ID at work has this set. HTH Martin From marklists at mceahern.com Sat Jul 13 01:37:07 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 13 Jul 2002 00:37:07 -0500 Subject: Making code 2.1 compatible In-Reply-To: <1026536116.794774@yasure> Message-ID: > | did you know that 2.2 has been deemed the release targeted for > | stability by the pbf? > > Where can I read about that? I'm curious to know what they mean. I read about that here: http://starship.python.net/crew/mwh/europython.html There doesn't appear to be a formal announcement here, yet: http://www.python-in-business.org/ // m - From cce at clarkevans.com Tue Jul 30 23:25:47 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 30 Jul 2002 23:25:47 -0400 Subject: Pyrex / py2exe import interaction In-Reply-To: <20020730225220.A86211@doublegemini.com>; from cce@clarkevans.com on Tue, Jul 30, 2002 at 10:52:20PM -0400 References: <20020730165458.A81189@doublegemini.com> <200207310045.g6V0jWZc019035@kuku.cosc.canterbury.ac.nz> <20020730225220.A86211@doublegemini.com> Message-ID: <20020730232547.A86330@doublegemini.com> Ok. I've gone a bit further. It appears that the problem occurs during a call to imp.load_module on line 163 of support.py of py2exe The tail of my trace now looks like... imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') AT support.py#160 CALLING imp.load_module(fqname='testmod', fp=, pathname='c:\\cygwin\\home\\cce\\prob\\dist\\test\\testmod.pyd', desc=('.pyd', 'rb', 3)) imputil.py#085 IN _import_hook(fqname='string',globals=,locals=None,fromlist=[]) imputil.py#088 _determine_import_context(globals=) imputil.py#151 .get('__importer__') Traceback (most recent call last): File "", line 1, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 267, in _import_one File "", line 164, in get_code File "imputil.pyc", line 89, in _import_hook File "imputil.pyc", line 152, in _determine_import_context AttributeError: 'module' object has no attribute 'get' ... Now, I just tried imp.load_module directly, and it worked. So, somehow one of those other "hooks" is firing and doing something strange... I don't know where to put trace code to peek ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import imp >>> name = "c:\\cygwin\\home\\cce\\prob\\dist\\test\\testmod.pyd" >>> file = open(fn,'rb') >>> imp.load_module('testmod',file,name,('.pyd','rb',3)) >>> ^Z So. I just don't know where else to look at this point. Here's hoping! Clark On Tue, Jul 30, 2002 at 10:52:20PM -0400, Clark C . Evans wrote: | On Wed, Jul 31, 2002 at 12:45:32PM +1200, Greg Ewing wrote: | | > Hello. I'm having difficulty with using a combination | | > of pyrex and py2exe; the problem occurs when the module | | > compiled with pyrex has an "import". | | | | I'll look into this if I can, but I don't know if | | there's much I can do, as I don't have easy access | | to a Windows machine to debug this sort of thing on. | | I've tracked it down a bit further. The _import_one is being | called on 'testmod', which is the binary module compiled by | pyrex. Then, in some override code for "get_code" which appears | to be provided as a dynamically generated string, it calls | _import_hook on the following items: imp, marshal, sys, and | then finally string. In the cases of imp, marshal, and sys | the 'globals' parameter of _import_hook is a mapping. But | then somehow, when it goes to import string, globals is | actually a module object instead of a mapping. | | So, somehow the get_code operator provided somehow is | passing a module to _import_hook instead of a mapping... | | Traceback (most recent call last): | File "", line 1, in ? | File "imputil.pyc", line 103, in _import_hook | File "", line 52, in _import_top_module | File "imputil.pyc", line 216, in import_top | File "imputil.pyc", line 267, in _import_one | File "", line 163, in get_code | File "imputil.pyc", line 89, in _import_hook | File "imputil.pyc", line 152, in _determine_import_context | AttributeError: 'module' object has no attribute 'get' | | Here is my trace that I generated... | | imputil.py#085 IN _import_hook(fqname='testmod',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},fromlist=('go',)) | | imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) | | imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') | | imputil.py#102 _import_top_module('testmod') | | imputil.py#215 _import_one(None,'testmod','testmod') | | imputil.py$266 get_code(None,'testmod','testmod') | | imputil.py#215 _import_one(None,'testmod','testmod') | | imputil.py$266 get_code(None,'testmod','testmod') | | imputil.py#085 IN _import_hook(fqname='imp',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals=None,fromlist=None) | | imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) | | imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') | | imputil.py#085 IN _import_hook(fqname='marshal',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals=None,fromlist=None) | | imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) | | imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') | | imputil.py#085 IN _import_hook(fqname='sys',globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None},locals=None,fromlist=None) | | imputil.py#088 _determine_import_context(globals={'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}) | | imputil.py#151 {'__builtins__': , '_extensions_mapping': {'testmod': ('testmod.pyd', ('.pyd', 'rb', 3))}, '__name__': '__main__', '_ModuleType': , '__doc__': None}.get('__importer__') | | imputil.py#085 IN _import_hook(fqname='string',globals=,locals=None,fromlist=[]) | | imputil.py#088 _determine_import_context(globals=) | | imputil.py#151 .get('__importer__') | Traceback (most recent call last): | File "", line 1, in ? | File "imputil.pyc", line 103, in _import_hook | File "", line 52, in _import_top_module | File "imputil.pyc", line 216, in import_top | File "imputil.pyc", line 267, in _import_one | File "", line 163, in get_code | File "imputil.pyc", line 89, in _import_hook | File "imputil.pyc", line 152, in _determine_import_context | AttributeError: 'module' object has no attribute 'get' | | | | | -- | http://mail.python.org/mailman/listinfo/python-list -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From claird at starbase.neosoft.com Mon Jul 8 22:19:43 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 8 Jul 2002 21:19:43 -0500 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2A078A.7040502@ob_scure.dk> <06F2E275AA053281.30FCDA468DD949D2.9ED8D7E798995448@lp.airnews.net> <3D2A2586.5070302@ob_scure.dk> Message-ID: In article <3D2A2586.5070302 at ob_scure.dk>, Thomas Jensen wrote: . . . >The last 6 months I've been working almost exclusivly on a (commercial) >project heavily based on SOAP (not for performance objectives though :-). >That part really doesn't scare me :-) . . . Let me know if you want to publicize your work. I frequently write articles and profiles of SOAP projects for State-side magazines (and worldwide, when there's an opportunity). -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From boud at valdyas.org Mon Jul 29 10:04:49 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Mon, 29 Jul 2002 16:04:49 +0200 Subject: default setting of unicode set References: <3D45000F.5040300@gmx.net> Message-ID: <3d454bc8$0$94895$e4fe514c@dreader3.news.xs4all.nl> Martin v. L?wis wrote: > mathias palm writes: > >> Is there a possibility to set a unicode default later on? > > No. Just don't use the default. Be explicit about your encodings in > your program. Use the user's preference where appropriate - only the > application programmer can know whether using the user's preference > *is* appropriate (for example, some data formats may require a fixed > encoding, such as UTF-8, independent of the user's preference). > This question comes up so often that I'm more and more convinced that the argument for deleting sys.setdefaultencoding() is flawed. Calling sys.setdefaultencoding("utf-8"), _is_ rather explicit, and beats having to add .encode()'s to all string handling. There exists a class of application that want to use unicode irrespective of any settings the user might have decided upon(1). My default way of coding around this inconvenience is to add a site-customize.py file that saves the setdefaultencoding under another name, like setappdefaultencoding(). (1)It's still very inconvenient to live with a default LC_CTYPE=en_US.UTF-8. For one thing, it messes up motif so the motif open file dialog can't select strings. For another thing, javac can't handle it... -- Boudewijn Rempt | http://www.valdyas.org From gollem at chatway.nl Tue Jul 2 18:03:12 2002 From: gollem at chatway.nl (gollem) Date: Tue, 02 Jul 2002 22:03:12 GMT Subject: Maximum size of list? Message-ID: What is the maximum listsize in python? In characters or items. Thnx. From johann.hoechtl at myrealbox.com Thu Jul 25 14:51:34 2002 From: johann.hoechtl at myrealbox.com (=?ISO-8859-1?Q?Johann_H=F6chtl?=) Date: Thu, 25 Jul 2002 20:51:34 +0200 Subject: PyXPCOM and SVG References: <3D3EEFE1.5090109@myrealbox.com> Message-ID: <3D4048B6.2060309@myrealbox.com> Gerhard H?ring wrote: > Trent Mick wrote in comp.lang.python: > >>[Johann H?chtl wrote] >> >>>Hello ! >>> >>>I was thinking of using Mozillas new SVG and/or the gecko rendering >>>engine and XUL capabilities in a wxpython-application using PyXPCOM >>>bindings. >> >>Phew. I don't know how you would mix XUL and wxPython. > > > Stupid question maybe. What does XUL have to do with Gecko? I had the > impression that you could embed Gecko in win32 or gtk apps just fine > without having to touch XUL at all :) Well XUL is of course not my primer as i can always use the wxwindows widgets. But I thought about the ability to "remote control" mozilla (maybe gecko and the upcoming SVG features) and therefore I need xpcom, or? > > Especially on Windows, I believe there are only one or two lines to be > changed to replace wxPython's upcoming IE component (in 2.3.3) with > the Mozilla COM component. The IE and Gecko controls are interface > compatible and only differ in class name and clsid. > > I've just read about it this evening. > > URLs of interest for the win32 side: > http://www.iol.ie/~locka/mozilla/mozilla.htm > http://www.codeguru.com/controls/iemozilla.html > > Being able to use Gecko in the gtk flavour of wxPython would be extra > cool, but I have no idea how to do _that_. > > Gerhard From shagshag13 at yahoo.fr Mon Jul 22 05:12:39 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 22 Jul 2002 11:12:39 +0200 Subject: file ops on the fly ? References: <21TZ8.101254$vm5.3505549@news2.tin.it> Message-ID: "Alex Martelli" it's ok you convince me to use a temp file or a fileinput, thanks, s13. From jonathan at onegoodidea.com Tue Jul 9 05:57:23 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 09 Jul 2002 10:57:23 +0100 Subject: Why self? References: <080720021650379803%pecora@anvil.nrl.navy.mil> <3D2A06F9.7050805@onsitetech.com> Message-ID: On 8/7/2002 22:42, in article 3D2A06F9.7050805 at onsitetech.com, "Robb Shecter" wrote: > Good ideas. Or just do nothing: make self optional as in Java, and the > innermost scope is searched first if no self is given. I've done > years of Java programming, and have never had issues with instance vs. > local variables. It just really doesn't happen in practice because of > the differences in naming and usage of variables. Actually, one of my number one errors in Java was always stupid copy and paste errors along the line of (not compiled, don't bother pointing out any syntax errors): public void setX( int x ) { this.x = x; } public void setY( int x ) { this.y = y; } which elicits no error but is completely wrong. Hint if you can't see it: forgetting to change the name of the argument to the setY function - a 'y' is in scope because 'this' is implicitly searched so there is no compile error. Because of this it's a standard practice in Java to write: public void setY( int inY ) { this.y = inY; } or something similar to avoid the confusion. I hate this with a passion. The comparable function in Python would be: def setY( self, x ): self.y = y which would fail immediately (as long as 'y' isn't a global variable - but don't get me started on global variables...). Explicitly writing 'self.' means that the difference between referencing a local variable (or argument) and an instance variable is always obvious. I have never had a bug in a Python program from confusing the two. [Actually when writing Java programs I always explicitly reference 'this' anyway because I want to be able to look at a line of code and know what's what without having to look at the instance and local variable declarations.] -down-with-using-naming-conventions-to-differentiate-scopes-ly y'rs, Jonathan From imbosol at vt.edu Sat Jul 27 17:45:02 2002 From: imbosol at vt.edu (Carl Banks) Date: Sat, 27 Jul 2002 17:45:02 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: Alex Martelli wrote: > Carl Banks wrote: > ... >>>> def sort_the_right_way (f, a): > ... >> Come on! Wrapping up a sort in a function is an "ambitious >> framework"? I'm talking about writing a single function because a >> certain sort appears a dozen or so times in the code. I'm sure you're >> aware of the advantages of putting oft-repeated code into one place. > > If the SAME sort appears repeatedly, it surely needs to be a > function. But you do have to get your parameters right when > "same" is not exactly "same". And if it gets to...: > ... >>>> sort_the_right_way (lambda x:x[1], a) > > ...the lambda suggests imperfect factorization. If this "same" sort > does occur often, IS it the case that this is the ONLY place where it > needs to be by the 1-th item? Or, by AN item? > > Statistically, it IS possible that the sort is both frequent enough > to deserve factoring out AND yet so varied and diverse in the criteria > to use that a general function is the only effective way to express > them AND that this one in particular is a freak case never to reoccur, > so that naming the sortfield-selector function (while not a problem) > MIGHT be fractionally suboptimal. > > The combination of each of these unlikely factors, all together, > multiplies down to a VERY small chance. Not for me. I have found this "very small chance" you speak of to be common in my programming, although not for sorting. I pass functions around a lot, both by preference, and because it is useful for the programs I write (a lot of deeply nested and arbitrary structure). So yes, when I've done this, it has been proper factorization. It's certainly been more ideal than repeating lots of similar "global" operations that vary only in the "local" operation. [snip] >>> Somebody ambitious enough to encapsulate DSU should surely proceed > ... >> So now you're advocating building a framework of closures to replace > > No, I'm saying that IF somebody was ambitious enough to encapsulate > DSU, then the same somebody should be consistent and proceed along > the same route. "If the fool would persist in his folly he would > become wise" (Blake). Can't you read? Evidently not. Sorry about that. You're wrong, though. As I've said, I have good reason to wrap up my sort functions, but no such good reason to wrap up functions I pass to it that way. As I've said, I pass around all kinds of functions, and that is where I face danger of trying to overgeneralize. [snip] >> What I'm saying is, your objection that this use of lambda only is >> necessary because of over- and under-generalization isn't true for my >> circumstances. > > I don't know you well enough to use my judgment about your specific, > individual circumstances, but I *DO* know that I *NEVER* said, implied, > inferred or let it be suspected that "this use of lambda is > *NECESSARY*" (my emphasis). Again, I'm sorry. I misspoke. If I replace necessary with tempting, is that what you were objecting? (Or were you objecting that the tempation to use lambda was because of the over- and under-generalization?) Well, whatever. All I'm saying is, for me, with the way I organize and factor code, the situation where it is tempting to use lambda comes up a lot, and not because of any over- or under-generalization on my part. [snip] >> Personally, I don't care about saving lines, per se. For me, lambda >> helps me to avoid stopping mid-function call, scrolling many or few >> lines to implement the function as a def, and returning. I.e., >> lambdas save me cursor movement. > > In VIM, I hit ESC, uppercase-O, and I'm in insert mode on a newly > inserted immediately-previous line with correct indent, ready to > flow on with def and so on. I assume more powerful editors and > IDEs, such as EMACS and the like, must have facilities at least as > powerful. Thus, the "saving" seems utterly trivial. It's not about keystrokes. Stopping mid-function-invocation to define a function stops my train of thought, one way or another. Regaining my train of thought, and my cursor position, is what I find tiring. -- CARL BANKS http://www.aerojockey.com From emile at fenx.com Sun Jul 14 12:23:30 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 14 Jul 2002 16:23:30 GMT Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: <6AhY8.529383$cQ3.46651@sccrnsc01> ppcdev > i was working on an old pentium II and wanted to send a very long > string in the USER parameter but it made my computer bug.. is it > normal??? > > str='a'; r=range(1024); > for x in r[:]: > str=str+str > I can't imagine a computer it wouldn't be normal on. ;-) This will create a string of length 2**1024, a result that starts 1797... and continues for another ~296 numbers. I imagine what you probably want is a string of 1024 characters? str = 'a'*1024 HTH, -- Emile van Sebille emile at fenx.com --------- From phr-n2002b at NOSPAMnightsong.com Wed Jul 24 20:01:52 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 24 Jul 2002 17:01:52 -0700 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: <7xn0sgpte7.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > >> If the main purpose of the module is to provide one function, I think > >> it's cleaner to be able to import the module and call the function > >> without special tricks. > Or just use your own trick, e.g., given > > ----< PR.py >------ > #PR.py for Paul Rubin > def PR(): return 'Hi Paul' > ------------------- > > Define one-line trick: > >>> def PRimport(name, locs=locals()): locs[name] = getattr(__import__(name),name) > ... > > And use it thus > >>> PRimport('PR') > >>> PR > > >>> PR() > 'Hi Paul' But that's another special trick, more hair to remember. Why not just do the obvious thing and make modules work the same way as other objects? From aleax at aleax.it Sat Jul 20 08:00:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 12:00:10 GMT Subject: file ops on the fly ? References: <409a56e2.0207200145.77c2004@posting.google.com> Message-ID: Shagshag wrote: ... > i was also thinking of this mecanism, but my biggest trouble is how to > write the new file end ? and/or delete the last lines : f.seek to the place you want to be the last one in the file, then call f.trucate(). That's the least of your worries... Alex From "gkrohnXvolucris.8m.com".replace Wed Jul 24 19:42:22 2002 From: "gkrohnXvolucris.8m.com".replace (Greg Krohn ("X", "@")) Date: Wed, 24 Jul 2002 18:42:22 -0500 Subject: Tk Dynamic Menus problem References: Message-ID: "Jeremy Bowers" wrote in message news:SBF%8.104617$_51.86102 at rwcrnsc52.ops.asp.att.net... > For the following Tk test program, I am having a problem. A dynamic menu > is being generated every time I click the "Test" menu, and three menu > options are generated, each with a different command. However, if you > click on any of the three options, the *third* command is executed, so all > menu options print 3. I expect the menu options to do what they say. > > I'd rather do it this way then fiddle with the menu options on each drop > down, as that's complicated when I can't guarentee the same number of > options on each drop down. (There are good reasons for that that make UI > sense in the context of the program this is getting used in.) > > I've tried a number of workarounds, but none seem to work. Is this a bug > in Tk or Tkinter? (It doesn't seem like this should be impossible...) > > --------- > > from Tkinter import * > > def printFunc(s): > print s > > class App: > def __init__(self, master): > self.frame = Frame(master, width = 200, height = 40) > self.frame.pack() > > self.menu = Menu(master) > master.config(menu = self.menu) > > self.dynmenu = Menu(self.menu, postcommand = self.updateMenu) > self.menu.add_cascade(label="Test", menu = self.dynmenu) > > def updateMenu(self): > self.dynmenu.delete(0, 99) # big num to get everything > > for i in [1, 2, 3]: > self.dynmenu.add_command(label = "Print %i" % i, > command = lambda: printFunc(i)) > > root = Tk() > app = App(root) > root.mainloop() > I'm not exactly sure why it's printing '3', but you do have a scoping problem there. Replace 'lambda: printFunc(i)' with 'lambda i=i: printFunc(i)'. Supplying i as a keyword arg for the lambda brings i into the labmda's scope. greg From pyth at devel.trillke.net Mon Jul 1 04:45:13 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 1 Jul 2002 10:45:13 +0200 Subject: Partial Parsing of Python In-Reply-To: <20020701060124.GA9937@luminance.reworld.org>; from pde@cs.mu.oz.au on Mon, Jul 01, 2002 at 04:01:24PM +1000 References: <20020629141507.GA6507@luminance.reworld.org> <20020630094833.B20310@prim.han.de> <20020701060124.GA9937@luminance.reworld.org> Message-ID: <20020701104513.E10625@prim.han.de> Peter Eckersley wrote: > [me] > > Actually the REAL problem to solve first is to have Multi-Line editing. > > Then all sorts of partial parsers *and* partial evaluation. Python is > > just too damn dynamic to have that one easily. > > > > Oh, which reminds me of something else. I also have problems with > side-effects ("heisenberg" effects)-- it will be necessary to get rid of > these. But you certainly know that this isn't generally possible? Take somestrangefile.read(). for example. The next best bet (read: hack) is to fork off a process which does the evaluation of an Subexpression. This way you'd catch 90% of in-place modifications. Doesn't work for files. But then how often are you doing dynamic network/file communication on the commandline? This might change once we have multiline editing. But one after three others :-) > My feeling was that this could be done using purity analysis and > return-type annotation. Many of the important cases can be handled by > just adding information about the builtin modules, but it might also > be possible to do generalised python purity analysis. Has anyone tried > this? Not me. I don't even now exactly what you are talking about :-) > > So what to do? Our idea at EuroPython was to use PyGame (the wrapper > > around SDL) to get rid of the uglyness and restrictiveness of > > readline and curses alltogether. We want to have a REAL playground > > and concentrate on our ideas. > > Hmmm, I agree that one needs to escape readline/curses - but SDL sounds > like overkill, since I imagine you'll have to re-implement lots of basic > widgets on top of it. I picked GTK, and have found it generally > suitable, despite a few quirks. Reflecting our EuroPython discussion, GTK or QT seems to be heavyweight. We don't need widgets but the ability to put scalable fonts on a screen. Having sprites and game-level performance can't hurt either :-) It's very worth a try. > A copy of my (pre-pre-alpha) code is available at > http://www.cs.mu.oz.au/~pde/src/gush-0.003.tgz (it's currently called > gush - the Grand Unified SHell - although I think somebody might have > already used that name), so you can see how GTK works for this. All > completions except obj.attr are currently turned off. > > In order to run it, you'll need the latest version of pygtk (1.99.10 or > later), from ftp://ftp.gtk.org/pub/gtk/python/v2.0/ . I see. I'll check that out after i caught up with my post-europython task list. holger From akuchlin at mems-exchange.org Sun Jul 14 17:04:50 2002 From: akuchlin at mems-exchange.org (A.M. Kuchling) Date: 14 Jul 2002 21:04:50 GMT Subject: Python and Parrot References: <3D316CCA.90605@myrealbox.com> Message-ID: In article <3D316CCA.90605 at myrealbox.com>, Johann H?chtl wrote: > Has the situation for Python changed since > > http://groups.google.com/groups?q=parrot+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&scoring=d&selm=slrna8us88.ol4.akuchlin%40ute.mems-exchange.org&rnum=9 > > got posted? No, nothing much has changed. There's still no support for scoping, still no compilers into Parrot bytecode except for toy demonstrations, and the rate of development has either remained constant or slowed. Premature optimization has continued, though, with patches to do things like make stack operations faster; I don't know how someone decided stack operations were a significant bottleneck without actually being able to run real code on the VM. I'll continue to keep an eye on Parrot development, and if someday implementing Python semantics seems possible, I'll try to update the Python-to-Parrot compiler. My dream would be just a compiler that handled simple functions and variables correctly; that would be enough to run a subset of existing Python programs and compare the performance of the Parrot and Python VMs. --amk (www.amk.ca) Choose your next words carefully, Doctor; they could be your last. -- The Borad, in "Timelash" From cliechti at gmx.net Tue Jul 2 15:49:24 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Jul 2002 21:49:24 +0200 Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> <35nU8.46034$n4.10990740@newsc.telia.net> Message-ID: "Fredrik Lundh" wrote in news:35nU8.46034$n4.10990740 at newsc.telia.net: > Chris Liechti wrote: > >> > maybe we should start here: >> > >> > http://www.python.org/cgi-bin/moinmoin/Python >> > >> > and see what happens... >> >> ... >> File "/usr/local/apache/MoinMoin/parser/wiki.py", line 335, in replace >> return apply(getattr(self, '_' + type + '_repl'), (hit,)) >> AttributeError: Parser instance has no attribute '_hmarker_repl' > > I have no idea -- it did work just fine about 30 minutes > before I saw your post... > > Is J?rgen reading this? Or the python.org webmasters? well they do now... i sent a message to both. chris -- Chris From pecora at anvil.nrl.navy.mil Wed Jul 3 15:23:40 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 03 Jul 2002 15:23:40 -0400 Subject: Memory leak in Mac Python IDE ? References: <020720021354486814%pecora@anvil.nrl.navy.mil> Message-ID: <030720021523400734%pecora@anvil.nrl.navy.mil> In article , Daniel T. wrote: > I take it you are running this in the "Python Interactive" window? Yes, > the various objects you are creating stay around until you explicitly > get rid of them. ie: del( tab1 ) will get rid of tab1 and free some > memory. Yes, I have since found out (from none other than Just Rossum), that this is a ... ta! ta! Feature! :-) -- Lou Pecora - My views are my own. From bruce_edge at yahoo.com Thu Jul 18 13:04:16 2002 From: bruce_edge at yahoo.com (bruce edge) Date: Thu, 18 Jul 2002 10:04:16 -0700 Subject: signals, threads, omniorbpy, SIGINT and segfaults Message-ID: When I init the ORB, there are 4 additional threads started. One of these segfaults on a SIGINT: Python 2.1 (#1, Jul 2 2002, 21:34:59) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import sys >>> import omniORB.CORBA OK here, Ctrl-C generated kbd int exception: KeyboardInterrupt >>> KeyboardInterrupt >>> orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID) Here Ctrl-C segfaults one of the threads: KeyboardInterrupt >>> KeyboardInterrupt >>> KeyboardInterrupt >>> zsh: 25516 segmentation fault python How can I fix this? I've tried trapping SIGINT in my main thread using signal(), which "helps" only in that now it takes more than one Ctrl-C to segfault it. Or, how can I proceed to debug this? Thanks, Bruce. From sholden at holdenweb.com Fri Jul 5 15:49:31 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 5 Jul 2002 15:49:31 -0400 Subject: help using (x)inetd References: Message-ID: "Cliff Wells" wrote in message news:mailman.1025654105.12451.python-list at python.org... > On Tue, 2 Jul 2002 19:39:22 -0400 > rahvee at yaahhoo.com wrote: > > > I have xinetd accepting a tcp connection on some port, and spawning a > > process that I wrote. > > > > The process wants to have a conversation. It can take input, it can > > make output, but when it prints some output, that output gets buffered > > by xinetd, and it is never received by the client until the process > > closes. My process is written in python. > > > > How can I signal inetd to flush the buffer? > > > sys.stdout.flush() > Ravee: Please also note that xinetd is completely out of the picture once your daemon program is fully started, which is why Cliff's suggestion works: your daemon program is in control of the socket directo to the client. Xinetd spawns the right daemon and just carries on waiting for connections. regards Steve From sandskyfly at hotmail.com Sat Jul 13 16:29:19 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 13 Jul 2002 13:29:19 -0700 Subject: PYREX References: <3d1749d3.19107439@news1.news.adelphia.net> Message-ID: edlsoft at mindspring.com (Burt Leavenworth) wrote in message news:<3d1749d3.19107439 at news1.news.adelphia.net>... > Has anyone installed Pyrex on Windows? If so, can you share the > details? Here's a dirty little script that allows me to type: C:\> python pyx.py extension.pyx and have pyrex produce an extension.c and an extension.pyd file (assuming Pyrex is in sys.path of course). It's only been tested in present form with single *.pyx files but I'm sure you can modify to do what you want. Incidentally, I use Microsoft Visual C++ and winXP. PS: Pyrex rocks. ciao, Sandy # pyx.py import sys, os, glob, time, shutil import Pyrex.Compiler.Main #GLOBAL # variables cwd = os.getcwd() os.chdir(cwd) timestamp = time.asctime(time.localtime()) filename = os.path.splitext(sys.argv[1])[0] filenameExt = os.path.join(cwd, sys.argv[1]) # functions join = os.path.join # run pyrex compiler Pyrex.Compiler.Main.main(c_only = 1, use_listing_file = 0) def isMember(file): x = len(filename) if os.path.basename(file)[:x] == filename: return 1 else: return 0 # create setup.py for c files setupfile = join(cwd, "setup.py") files = glob.glob(join(cwd,"*.c")) setup = open(setupfile, 'w') setup.write("""# automatically generated - %s from distutils.core import setup, Extension setup(name = "%s", version = "1.0", ext_modules = [Extension("%s", sources=%s)] ) """ % (timestamp, filename, filename, [os.path.basename(file) for file in files if isMember(file)])) setup.close() # compile corresponding python extension os.system("python %s build" % setupfile) # copy extension to python extension directory path = join("build\\lib.win32-2.2", "*.pyd") files = glob.glob(path) for file in files: shutil.copyfile(file, join(cwd, os.path.basename(file))) # cleanup shutil.rmtree(join(cwd, "build")) os.remove('setup.py') From jdhunter at nitace.bsd.uchicago.edu Sun Jul 21 14:34:32 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Sun, 21 Jul 2002 13:34:32 -0500 Subject: ssh and Python References: Message-ID: >>>>> "edadk" == edadk writes: edadk> I would like to write script that using ssh automatically edadk> execute commands commands on a remote machine. How can I do edadk> that? For simple stuff, you have at your disposal, for example: import os h = os.popen('ssh -2 somehost.com ls') print h.read() John Hunter From tundra at tundraware.com Thu Jul 11 03:30:02 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Thu, 11 Jul 2002 07:30:02 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: James J. Besemer wrote: > Tim Daneliuk wrote: > > >>I want to write a program which goes to specific registry locations and >>scrubs out the MRU cruft left behind by so many programs. So, for example, >>say I've edited a bunch of Word docs, I want to run a script from the scheduler >>which periodically goes in and removes the MRU entries. > > > Yeah, sure. I bet what you REALLY want is to scrub your MRU list of all those Porn > pix you downloaded. ;o) Naw, I'm not into spectator sports ;) But it does give me an idea - how about a program which allows you to *write* bogus MRU entires on your coworkers' machines so it *looks* like they've been places they have not... ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From huaiyu at gauss.almadan.ibm.com Tue Jul 30 18:19:58 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 30 Jul 2002 22:19:58 +0000 (UTC) Subject: signature for a file ? References: Message-ID: Shagshag13 wrote: > >i had at home many hdds, that could contain many time same files, in many >places/directories (-> i'm really disorganized). i would like to do some >sort on theses files. to do this i'm planning to write a python script that >would compute a kind of CRC32, MD5 or SHA (i'm really not competent in that >- so here i need advices and pointer to some implementations - and to know >which is the best to had a unique unambiguous signature for a file) and >then use it to find "doubles" : same size + same signature = probably same >file. That would be very useful indeed. (Concurs another disorganized person :-) Here's a further question. Once you get to know the identities of files, how do you know about the directories? I have many directories that have identical subdirectories. I'd like to build an inventory of maximal identical directories. A and B are defined as maximal identical if they are identical but their parents are not. The few ideas I have all produces combinatorial explosion. Huaiyu From aleax at aleax.it Sat Jul 27 16:50:50 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 20:50:50 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: Fredrik Lundh wrote: > Carl Banks wrote: > >> I'm sorry if it seemed like I was trolling. > > Oh, sorry, I didn't mean you. I meant the "lambda lovers have > childhood traumas" guy. If he cannot defend his position with- > out stuff like that, it must be a pretty worthless position. I can defend my position, or attack yours, in many different ways, but I've noticed that ways that tend to elicit smiles (albeit delivered in my usual deadpan style) also tend to stick better and more effectively in many humans' minds. Haven't you noticed the same effect in your occasional, wry attempts at humor? > If you like lambdas, use them. All the best pythoneers do, so why > shouldn't you? On the other hand, implied put-downs such as this one (which logically implies "if you don't use lambdas, you're not among the best pythoneers") are only effective if they're allowed to operate subliminally; once brought to light as bullying attempts, they lose most of their effectiveness. Alex From chris.myers at ingenta.com Thu Jul 25 14:17:03 2002 From: chris.myers at ingenta.com (Christopher Myers) Date: Thu, 25 Jul 2002 14:17:03 -0400 Subject: Jython newbie question References: <3D401577.65D61189@ingenta.com> Message-ID: <3D40409F.8BA9DDC8@ingenta.com> Aha -- I wasn't thinking about using Java string methods (Duh!) Also, I didn't install Jython on my machine -- the interpreter comes embedded in Maxq, so I don't really have the Jython interpreter to test with. So, how about using Python's 're' module if string ops aren't appropriate? Some of the string ops I need to do may require using re's. Any comments on that? Thanks for the help. -Chris Martin Franklin wrote: > > On Thursday 25 Jul 2002 3:12 pm, Christopher Myers wrote: > > I just downloaded Maxq (http://www.bitmechanic.com/projects/maxq/) > > > > (etc . . .) > > I forgot to add that as of python 2.0 (and Jython 2.0) you don't need the > string module for anything apart from obscure (IMHO) methods as string > objects have methods: > > >>> "aaaaa".upper() > 'AAAAA' > >>> _.lower() > 'aaaaa' > >>> ",".join('abcdefg') > 'a,b,c,d,e,f,g' > > etc..... > > Martin -- Christopher Myers, Graduate Software Developer Ingenta, Inc. 12 Bassett St. Providence, RI 02903 ph: 401.331.2014 x 102 em: chris.myers at ingenta.com aim: chrismyers001 From aahz at pythoncraft.com Tue Jul 23 16:52:48 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2002 16:52:48 -0400 Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3AEDD6.78B39D70@engcorp.com> <3D3B4F80.B0D6BE07@engcorp.com> Message-ID: In article <3D3B4F80.B0D6BE07 at engcorp.com>, Peter Hansen wrote: >Alex Martelli wrote: >> Peter: >>> >>> the name you use is local to the function, then when >>> the function exits the binding is removed and the object, >>> if no other names are by now bound to it, is destroyed. >> >> Yes, except that 'names' must be used in a very wide >> sense here -- e.g., async.dispatcher instances are kept >> alive by references to them in the socket_map dict, >> which are "names" only in a very wide sense. > >I'm trying to follow Aahz' advice and avoid "reference" in favour of >"binding" etc, but I guess I carried it too far! :) Your problem wasn't in your use of "binding", but in your use of "name; I use "target" to refer to the general case of thingy that can contain a binding, of which names are a subset. "Names" are words attached to a namespace (i.e. function local, module global, builtin, or object attribute). Another target is an index/key for container objects. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From gtalvola at nameconnector.com Wed Jul 17 09:41:27 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Wed, 17 Jul 2002 09:41:27 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty Message-ID: <61957B071FF421419E567A28A45C7FE514A5C9@MAILBOX.nameconnector.com> aahz at pythoncraft.com wrote: > In article , > Geoffrey Talvola wrote: > > > > In case you're wondering, this is in Webware's WebKit > > application server > > where there is a pool of N threads, and a queue of > > (non-thread-safe) servlet > > instances acting as a cache. We only want to create servlet > > instances when > > all existing instances are in-use. When a given thread > > needs a servlet, it > > basically does: > > > > try: > > instance = cache.get_nowait() > > except Queue.Empty: > > instance = new_instance() > > # use the instance... > > cache.put(instance) > > > >The problem is that every once in a while get_nowait() > > returns Empty when > > the queue isn't actually empty, so the size of the cache > > grows slowly and > > unboundedly over time. But I'd prefer for the cache to > > contain at most N > > instances where N is the number of threads. > > You've got several options. Simplest is to change the > exception so that > it only creates new instances when there are fewer than N instances. > > What I'd consider doing, though, is make a data queue instead of a > servlet cache queue, such that all the servlet threads grab their data > from that data queue. Then you have a separate monitor thread that > periodically checks the data queue and creates new servlet > threads when > it hits "too many" items. Conversely, if the data queue stays empty, > you delete servlet instances (by passing quit tokens in the data queue > would be simplest). There is something like that already in WebKit that handles the overall request processing. What I'm talking about here is essentially caches of individual servlets, where loosely speaking a servlet corresponds to a unique URI. You may have 10 threads, but 2000 different servlet classes in your application. Each of those servlet classes has a cache with anywhere from 0 through 10 instances, depending on the maximum number of simultaneous accesses of that servlet. We only want to allocate a new instance when all existing instances of that servlet class are busy. That's what the catching of Queue.Empty was intended to detect, but it in fact doesn't work. As mentioned in a response to Tim, I switched to using a list with .append() and .pop() and it is working fine. It actually functions as a stack instead of a queue but that's fine with me. - Geoff From dkirby at orchestream.com Mon Jul 1 09:01:51 2002 From: dkirby at orchestream.com (Dave Kirby) Date: Mon, 1 Jul 2002 14:01:51 +0100 Subject: Python COM problem - accessing properties with optional parameters References: <1025282888.585264@lave> <3D1CFBB8.90709@skippinet.com.au> Message-ID: <1025528675.988592@lave> Perfect - that works just as you said. Thank you Mark for your fast and helpful reply. Dave "Mark Hammond" wrote in message news:3D1CFBB8.90709 at skippinet.com.au... > > If you run makepy over the type library, you *should* find that the > property has *also* been exposed as a "SetAccName()" method. Check the > generated code for details. > > Mark. > From rjones at ekit-inc.com Wed Jul 3 21:16:46 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 4 Jul 2002 11:16:46 +1000 Subject: File Locking (or any similar file mutex) in Windows OS??? In-Reply-To: <1025744866.5412.10.camel@localhost.localdomain> References: <3d238ca3$0$333$e2e8da3@nntp.cts.com> <1025744866.5412.10.camel@localhost.localdomain> Message-ID: <200207041116.46899.rjones@ekit-inc.com> On Wed, 2002-07-03 at 16:45, Ron Horn wrote: > I would like some simple and robust way to know if one of the clients is > currently using the file, but my question could apply to any shared > resource the various client instances could want to share. It seems that > the various file locking features of os.open(), and anydbm.open(), etc. > are not working right on Windows? > > Any suggestions on how to make this work in python running on windows > clients/server would be appreciated. Missed the original post. Try the portalocker.py code for hints: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 Richard From martin at v.loewis.de Wed Jul 24 18:34:11 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Jul 2002 00:34:11 +0200 Subject: UDP Multicast HELP! References: Message-ID: "Larry" writes: > s1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, '234.5.6.7') The problem here is that IP_ADD_MEMBERSHIP requires a struct ip_mreq, which is typically defined as struct ip_mreq { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_interface; /* local IP address of interface */ }; So this is an 8-byte value. For imr_interface, you usually specify INADDR_ANY, which is '\0\0\0\0', so you really need to use group = socket.inet_aton('234.5.6.7') + '\0\0\0\0' s1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group) [Strictly speaking, you should use struct.pack to build the struct, but the code above is just as portable, I assume] HTH, Martin From tim at vegeta.ath.cx Tue Jul 9 03:53:30 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: 9 Jul 2002 00:53:30 -0700 Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: Alex Martelli graced us by uttering: > Robb Shecter wrote: [ snip ] >> Sounds like a difference in design philosophies. In my code, private >> everything is the norm, with a very thin/small public API. > > Wise artisans learn a tool's strengths and use those strengths rather > than fighting against the tool. Your "design philosophy", *actively* > _hiding_ information, may be OK with other languages (one could > do a lot of debate about that -- see later for a start), but it's > definitely not the most productive way to use Python (or several other > tools with similar underlying philosophies). Agreed. How many more times must we see, "Why can't Python be more like X?" If the desired feature of language X is valuable enough, it may be worth simply using language X instead. OTOH, one can always take a cue from Guido himself: create your own language. > What I see as the fallacy of "information hiding" as an active purview > (having pursued it diligently for lo those many years) is that it > reflects and responds to an assumed underlying "pecking order" which, > upon reflection, is not a best fit for most projects. Though admittedly a weak analogy, this rings of a certain software company's claim of security through obscurity. Anyone attempting to use a security hole in an application to criminal ends is probably not above decompiling a Redmond binary (which is also illegal) to discover/exploit the security hole. Trusting a language structure to protect against malicious or simply incompetent users is bad design, and is likely to inhibit flexibility. To the truly intent or truly clueless, strict typechecking (a la C/Java) protects against misuse about as much as Python's __instancevar munge technique. > Alex My $0.02, Tim Hammerquist -- guru, n: a computer owner who can read the manual. From janeaustine50 at hotmail.com Fri Jul 26 10:42:47 2002 From: janeaustine50 at hotmail.com (Jane Austine) Date: 26 Jul 2002 07:42:47 -0700 Subject: [Re] euid/egid eaten up by os.popen References: Message-ID: "Donn Cave" wrote in message news:... > Quoth janeaustine50 at hotmail.com (Jane Austine): > | >I bet you're running Linux. My suggestion is to try popen2, and > | > | Yes, Red Hat 7.3 > | > |> specify the command as a list of arguments. For example, if you > |> have been writing > |> fp = os.popen('id') > |> then try > |> fp, ignore = popen2.popen2(['id']) > | > | Have done that and it didn't work still. > ... > | It seems like when popen forks for a new shell, euid is all cleared. > > Yes, I think it's the shell, all right. All I can say is, popen2() > works for me - *IF* I use the list of parameters as above. It doesn't > help to just use popen2 instead of popen, and give it the same command > string. > > Donn Cave, donn at u.washington.edu Well, it didn't work with list of parameters as above. But thank you anyway! Changjune Kim's suggestion worked just right. After a couple of research I found out this: Bash-2.x requires the `-p` option to run setuid. If that is not supplied, bash disables its setuid status. From wweexxsseessssaa at telusplanet.net Mon Jul 1 00:35:41 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Mon, 01 Jul 2002 04:35:41 GMT Subject: Q: Status of MySQL & Python? References: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> Message-ID: On Mon, 1 Jul 2002 05:33:16 +0200, Gerhard H?ring wrote: >* John Hall [2002-07-01 03:12 +0000]: >> When trying to run the dbBrowser from Samples, MySQLdb/__init__.py >> does a traceback in line #27 because _mysql is not found. Sure 'nuff, >> I don't have that. I do have souce C source: _mysql.c > >Obviously you downloaded the source distribution. It's dead simple to >build this, if you have Visual C++ installed: >- Edit setup.py to point to your MySQL installation >- Enter python setup.py install Hi Gerhard, thanks for the quick reply, but I did NOT D'L the source distribution, but the binary for Windows. Then I ran Setup, did the c:\mysql\bin mysql-nt --install then started the service, then got MySQL Studio and created a database & a table. I definitely have not compiled anything. Should I have a _mysql library or _mysql.py file somewhere? -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From jb at cascade-sys.com Sat Jul 27 00:36:09 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 26 Jul 2002 21:36:09 -0700 Subject: calendar lameness! References: Message-ID: <3D422339.4D6F95AB@cascade-sys.com> Steve Holden wrote: > Since I don't know how > the Jewish religion decides when Passover is, your statement doesn't convey > that much. It was intended as a subtle hint, not a big part of the answer. --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From jdhunter at nitace.bsd.uchicago.edu Fri Jul 12 12:25:44 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 12 Jul 2002 11:25:44 -0500 Subject: Converting 2 bytes string into INT References: Message-ID: >>>>> "DeDa" == DeDa writes: DeDa> Hi to all, I'm a newbie of Python and I already have a big DeDa> problem. I read 2 bytes from files and I like to convert DeDa> them into an integer. How can I do it? Thanks a lot. Bye, DeDa> DeDa. See the struct module and it's unpack function: http://python.org/doc/current/lib/module-struct.html For more info, take a look at: http://groups.google.com/groups?as_q=read%20binary&safe=images&ie=ISO-8859-1&as_ugroup=comp.lang.python&lr=&hl=en Cheers, John Hunter From phr-n2002b at NOSPAMnightsong.com Sat Jul 13 12:42:57 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 13 Jul 2002 09:42:57 -0700 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: Message-ID: <7x65zj60ku.fsf@ruckus.brouhaha.com> Christopher Browne writes: > I think the widespread lemming-rush to try to get _everything_ mapped > onto XML-based formats is a demonstration that a whole lot of people > have never even _looked at_ Lex and Yacc. > ... > (reverse (concatenate 'string "moc.enworbbc@" "enworbbc")) Or Lisp... ;-) From max at alcyone.com Mon Jul 29 04:32:09 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 29 Jul 2002 01:32:09 -0700 Subject: order of test References: <20020729095951.4cfad491.wilk-spamout@flibuste.net> Message-ID: <3D44FD89.84DF685E@alcyone.com> William Dode wrote: > can we be sure of the order of a test expression ? > i mean that > t=["one","two"] > x=10 > if x<2 and t[x]=="oups": > > will never throw an exception if t[2] will be tested before x<2 Yes. In Python, the and, or operators are short-circuiting. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From aleax at aleax.it Sun Jul 21 13:56:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Jul 2002 17:56:12 GMT Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? References: <8d3e714e.0207210836.7f8a51c8@posting.google.com> Message-ID: <0BC_8.112265$vm5.3832285@news2.tin.it> Tony C wrote: > I've searched through this newsgroup and saw several references for > the Oreilly book "Learning Python". > > I've noticed it was originally published in 1999, and I am wondering > if it is still a good place to start, for a programmer who wants to > learn Python, since Python has undergone several new releases, 2.2.1 > being just a few months old. My personal opinion: it's still good, because it's very clear and well written. It will teach you Python 1.5.2, but that's 80% of the task of learning Python 2.2.1, anyway. The understanding given by "Learning Python" is a great basis on which to continue with "intermediate" level books, such as (ahem) the Python Cookbook (due out in a couple of days, at OSCON) and the forthcoming Python in a Nutshell, due out in October (if I stop spending time on c.l.py and go back to the task of writing it, at least!-), which cover Python 2.2. I do hope Ascher and Lundh find the time to update "Learning" to 2.2 very soon, of course. But if they don't, it's still a good book indeed. There are other good books, but "Learning" is still my first recommendation to a programmer experienced in other languages who wants to get started with Python on the right foot. (Bias warning: working with David on the Python Cookbook has made us friends -- but I liked Learning Python even before then!-). Alex From mhammond at skippinet.com.au Thu Jul 25 23:59:07 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 26 Jul 2002 03:59:07 GMT Subject: embedding pythonwin into an MFC application References: Message-ID: <3D40C92A.5000909@skippinet.com.au> BethO at surfware.com wrote: > I'm having some problems getting started in this regard...............I > looked at the embedding pythonwin documentation that was included, but I > don't have the file win32uihostglue.h on any of my > machines................................I'm not sure what downloads contain > this file............. This is in the Pythonwin sources. My starship page has information on how to get the source code via CVS. > When I look at the C++ documentation, it talks about embedded applications > in relation to how they modify the document...........I really don't want to > modify the document in this way, I just want to embed the Python application > within a C++ view, so I'm really not sure about implementing the container > on the C++ end, etc.......... I'm not sure what you mean here, especially about "embed the Python application in a view". You can implement as much or as little of a document, view or doctemplate in Python as you like. If all you want is the Pythonwin editor, then this is doable too - Pythonwin registers a document template, so as long as you ensure this registration code is called, the normal MFC docview architecture should allow everything to work. Mark. From pecora at anvil.nrl.navy.mil Tue Jul 9 08:26:30 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 08:26:30 -0400 Subject: Why self? References: <000d01c226b5$8c68f520$bd5d4540@Dell2> Message-ID: <090720020826309018%pecora@anvil.nrl.navy.mil> In article , Bo M. Maryniuck wrote: this one > self.__baz = 'baz' Referred to later as > print stf._stuff__baz is new to me. Guess I'm out of it. -- Lou Pecora From abc at abc.com.sg Fri Jul 5 00:21:53 2002 From: abc at abc.com.sg (abc) Date: Fri, 5 Jul 2002 12:21:53 +0800 Subject: Newbie - Stand alone python Message-ID: Hi all, I am a newbie to Python and I want to ask you guys a question. Python program is very much like Java where both need a Virture machine to run the program, I wonder whether Python program is able to compile into a .exe file instead of a .py file so that PC without the VM is also able to run the program. Thankz From mwh at python.net Mon Jul 15 10:47:55 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Jul 2002 14:47:55 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> <1026545186.810050@yasure> Message-ID: "James J. Besemer" writes: > Browsing through the 2.2 Library, about half the modules I checked > exhibited deviations from the standard re horizontal whitespace. So > not too many key contributors appear to share your zealous view on > this particular point. The coding standard was written down relatively recently. Many of the standard libraries were not. Often when someone is working on a module they'll fix up the whitespace while they're there, but few people go on whitespace-fixing crusades. Cheers, M. -- FORD: Just pust the fish in your ear, come on, it's only a little one. ARTHUR: Uuuuuuuuggh! -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From bokr at oz.net Wed Jul 24 20:37:05 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 00:37:05 GMT Subject: A better self References: Message-ID: On Wed, 24 Jul 2002 08:34:33 GMT, Alex Martelli wrote: >Only when you're SURE you have the best possible algorithms (and the >most perfect, developed economy) and you're STILL too slow (or, still >too poor) should coding in lower levels be considered (on the other >hand, protectionist legislation shouldn't be considered even then, >but that's another issue:-). > What are you protecting with that "shouldn't"? ;-) ISTM everyone believes in protectionism, only differing in their ideas of what to protect and how to do it ;-) Regards, Bengt Richter From mlh at vier.idi.ntnu.no Mon Jul 15 17:12:53 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 15 Jul 2002 21:12:53 +0000 (UTC) Subject: Fakes... References: Message-ID: In article , Matt Gerrans wrote: >[snipped harangue] >> ... With 6 billion people... >[snipped diatribe] >> ... 99.9999999% of the >> population. I know this because I've searched, and in >> my search have so far only found one true ally... > >Well, I didn't have time to peruse this rant, but since you posted this to >comp.lang.python, I skipped to the relevant (loosly speaking!) part: > >>>> round((1.0-99.9999999/100)*6*math.pow(10,9)) >6.0 > >Looks like good news: you only have 4 more like yourself to find -- You >probably have better odds in high-population areas like China, India and >Africa than you do in comp.lang.pytyon... On a related note: http://www.humorisdead.com/news/makeadifference.html -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From see_reply_address at something.invalid Tue Jul 23 00:01:53 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 23 Jul 2002 16:01:53 +1200 Subject: ANN: Pyrex 0.4 -- Substantial new features Message-ID: Pyrex 0.4 is now available: --------------------------- http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. New Features in 0.4 ------------------- - "cdef extern from" statement allows inclusion of C header files to be specified, solving a number of problems including: - Clashes between Pyrex and C declarations, due to "const" and other reasons - Windows-specific features required in function declarations - Helping deal with types such as "size_t" - Helping deal with functions defined as macros - Access to internals of pre-existing extension types is now possible by placing an extension type declaration inside a "cdef extern from" block. Bug Fixes --------- - Error not reported properly when passing wrong number of args to certain special methods of extension types. [Mitch Chapman ] - Compile-time crash when defining an extension type with a __hash__ method. Minor Enhancements ------------------ - Hashing of the scanner source file made more platform-independent, making spurious regeneration of the pickle less likely. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From res0s92a at verizon.net Thu Jul 11 22:34:53 2002 From: res0s92a at verizon.net (Ray Tux) Date: Fri, 12 Jul 2002 02:34:53 GMT Subject: Recomendations on Books Message-ID: Hello I am a beginer to programming and I have chose Python. I was just wandering if you guys could recomend some good Python Beginers books. Thanks From whisper at oz.net Mon Jul 8 20:16:39 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 8 Jul 2002 17:16:39 -0700 Subject: Idle setup install falis on Win2k Message-ID: Idle.py assumes that it's scripts are in the same directory as itself and they're not after install. Idle.pyw just silently fails if they're not in the same dir as itself. This is PythonLabs Python 2.2.1 binary on Win2k with the included distribution of Idle. David LeBlanc Seattle, WA USA From tjreedy at udel.edu Wed Jul 24 19:11:05 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Jul 2002 23:11:05 GMT Subject: Numeric data question References: <%Nz%8.15893$A72.86385@news1.mts.net> Message-ID: "terry" wrote in message news:mailman.1027526808.16869.python-list at python.org... > > >> Well, PostgreSQL does have a money type, but IIRC it's just a > >> float with a fixed number of decimal places. You could just > >> use pennies as the unit and integer math though. > Thanks Tim, it is a more complex representation than just float > as it also contains the decimal places. I haven't seen the exact > internal format in Postgres, but it's a very common datatype in > many databases. In general it's not appropriate/legal to use > integer or floating point math when dealing with money. It > creates too many coding dependent variations in results - not to > mention maintenance nightmares. If the amounts of money you are dealing with are well less than the max, and if you are only doing + and - (accounting in the strict sense) and maybe * by int amounts, ints using the lowest denomination (cents in the US) work just fine. +/- 2 billion cents is +/- 20 million dollars. Python's integration of longs with ints should remove the upper limit constraint. Financial calcs with interest and other rates requires more care. TJR From bkelley at wi.mit.edu Mon Jul 1 09:03:27 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 01 Jul 2002 09:03:27 -0400 Subject: Getting the XP clipboard in tkinter References: <3D1F1A81.95602DE0@tds.net> Message-ID: <3D20531F.1050003@wi.mit.edu> Just in case you are using windows: # if we are running on windows, attach to the # windows clipboard import win32clipboard as clip def getFromClipboard(): 'Returns a list of the lines of text in the clipboard.' clip.OpenClipboard(0) if clip.IsClipboardFormatAvailable(clip.CF_TEXT): newText = clip.GetClipboardData(clip.CF_TEXT) lines = newText.split('\r\n') clip.CloseClipboard() return lines Brian Kelley Whitehead Institute for Biomedical Research From johnmc at velseis.com.au Thu Jul 11 19:39:47 2002 From: johnmc at velseis.com.au (John McMonagle) Date: 11 Jul 2002 16:39:47 -0700 Subject: Pmw.Counter and Pmw.ScrolledCanvas questions References: <18692175.0207102141.1d5279c1@posting.google.com> <200207110825.g6B8P4728314@helios.gatwick.geco-prakla.slb.com> Message-ID: <18692175.0207111539.47132bd6@posting.google.com> > On Thursday 11 Jul 2002 9:21 am, Martin Franklin wrote: > I just had some more thoughts on the Counter problem. Pmw uses the grid > geometry manager and presumably for the Counter has a sticky='news' option > which would account for what you are seeing, It should be possible to change > this. > > Ok from the source:- > > self._counterEntry.grid(column = 1, row = 0, sticky = 'news') > > This depends which orientation you are asking for but it's that sticky='news' > that is causing your problem, what to do??? I would start by changing it to > just sticky='ew' and see what happens. > > > Martin. Martin, thanks for the tip. Indeed I did change the PmwCounter.py code to what you suggested and it worked a treat. Thanks From vvainio at tp.spt.fi Mon Jul 8 04:24:09 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 8 Jul 2002 01:24:09 -0700 Subject: the meaning of life References: <3eeda89d.0207071133.4c07a86e@posting.google.com> Message-ID: aoeu at go.com (Thinkit) wrote in message news:<3eeda89d.0207071133.4c07a86e at posting.google.com>... > Take a break from python and realize the meaning of ALL conscious beings. I'm not sure what you are going after. Perhaps you could write a PEP? -- Ville From trentm at ActiveState.com Fri Jul 5 04:49:54 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 5 Jul 2002 01:49:54 -0700 Subject: ANN: 'which' v0.6.1 - A Python GNU-which replacement Message-ID: <20020705014954.C5086@ActiveState.com> Where? http://starship.python.net/~tmick/ What is 'which'? GNU which is a common command line app on Unix. There are Windows ports (for example, the one in the Cygwin distribution), though I find the ones I have seen to be a little stupid. They don't understand the use of the PATHEXT environment variable. They don't support the useful '-a' option to listing all matches on the current PATH. This which has the following features: - it is portable (Windows, Linux); - it understands PATHEXT on Windows; - it can print all matches on the PATH; - it can note "near misses" on the PATH (e.g. files that match but may not, say, have execute permissions); and - it can be used as a Python module. What platforms? Windows and Linux. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From johnroth at ameritech.net Fri Jul 26 15:59:01 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 26 Jul 2002 15:59:01 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: "Britt A. Green" wrote in message news:mailman.1027705851.8443.python-list at python.org... > So I know what lambda functions are, their syntax and how they're used. > However I'm not sure *why* one would use a lambda function. What's the > advantage that they offer over a regular function? They let you put short, one-time functions inline. In some environments (Tkinter comes immediately to mind) there are lots of places where short, one-line functions are useful. Putting a short, one-time function inline aids readability, (at least for people who regard lambdas as readable.) IMO, if the function is of any significant length, or if it duplicates functionality from elsewhere, it should be named and written separately. John Roth From talsit at talsit.org Wed Jul 31 12:44:14 2002 From: talsit at talsit.org (tALSit de CoD) Date: 1 Aug 2002 02:44:14 +1000 Subject: Debug version crashing... References: Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote in news:m3heig4cbi.fsf at mira.informatik.hu-berlin.de: > tALSit de CoD writes: > > Could it be that you are loading python22.dll instead of > python22_d.dll? > > Regards, > Martin Actually, this wierd error was actually due to the fact that during testing, i was invoquing the interpreter (python, not python_d) and the dll was loading python_d. Thanks! From mcfletch at rogers.com Mon Jul 1 23:43:58 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 01 Jul 2002 23:43:58 -0400 Subject: Unicode utf-8 doesn't do back-and-forth? Message-ID: <3D21217E.9050009@rogers.com> I'm trying to create exhaustive lists of unicode character categories for use by parsers. In doing so, I'm parsing the unicode database and generating the category uni-strings from the category sets. What I'd like to do is save the unicode strings in a python file for easy access. No problem thinks I (stupid I), I'll just write out a repr() of the unicode object --> no go, when I change locale to "fr", I get errors trying to import. The repr()'d string has lots of \x escapes, so I imagine it's getting cute and attempting to reduce the number of unicode-escaped chars by using > 127 chars in local-specific manner. Well thinks I (stupid I), I'll just use the natural 8-bit transfer format for Unicode, utf-8. When I do that, I get weird "Unicode errors". For instance (simplified example): >>> unicode( u'\ud800\udb7f\udb80\U0010fc00\udfff'.encode('utf8'),'utf8') Traceback (most recent call last): File "", line 1, in ? UnicodeError: UTF-8 decoding error: unexpected code byte >>> u'\ud800\udb7f\udb80\U0010fc00\udfff'.encode('utf8') '\xa0\x80\xad\xbf\xae\x80\xf4\x8f\xb0\x80\xed\xbf\xbf' >>> I was under the impression that utf-8 was supposed to be able to support any Unicode character with full back/forth translation. It doesn't seem to here... Anyone clueful out there like to slap me upside the head with my obvious mistake? Enjoy, Mike _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From marklists at mceahern.com Sat Jul 6 08:05:25 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 6 Jul 2002 07:05:25 -0500 Subject: Why self? In-Reply-To: Message-ID: [Matt Gerrans] > In Python, I think the required "self" reference in methods is a > case where the solution is worse than the problem it solves. What problem do you think it solves? > Since > indentation is the method of scoping in Python, this addition of > five characters to each instance variable is particularly annoying > -- a one-line statement that contains several instance variables > can easily become unmanageable. I personally like the explicit self reference. I think it's a good idea. I'm not sure I can explain why, but I'll try... Python is a dynamic language. So you can do stuff like this: class C:pass c = C() def x(self): if hasattr(self, "name"): print self.name else: print "I don't have a name yet." C.hello = x # These two are now equivalent: c.hello() C.hello(c) How is indentation supposed to distinguish def x above as a function from an unbound method from a bound method? I think if you consider the full implications of the above example, you'll understand and perhaps be able to better express than I can why explicit reference to self in bound methods (is that the right term?) is a good thing. // mark - From rotundo52 at hotmail.com Wed Jul 31 12:48:18 2002 From: rotundo52 at hotmail.com (Jon J. Morin) Date: Wed, 31 Jul 2002 16:48:18 GMT Subject: code examples for rfc822 module? References: Message-ID: Tim Roberts wrote: > rotundo52 at hotmail.com (Jon J. Morin) wrote: > >>Does anyone know of any sites or other resources with code examples >>using the rfc822 modulde? I am writing an app that sends and receives >>email and I really don't understand the documentation on the >>python.org site (I'm kind of a Python newbie). Any help is >>appreciated. > > The test routine at the end of the module gives you the basic operation. > There isn't too much to rfc822; you feed it a message, it returns the > headers and addresses in usable fashion. You might want to look at the > email module instead, if you need more (like MIME handling). > > What were you hoping to have it do? > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. Thanks. I checked out the documentation for the email modulue and this is more of what I need. I am still learning about the standard library, and I guess that I was trying to reinvent the wheel ;) Jon From matt_gerrans at hp.com Wed Jul 10 15:19:31 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Wed, 10 Jul 2002 12:19:31 -0700 Subject: Converting a hex string to a number References: Message-ID: > How the hell is the above better in any way shape or form than... Who said it was the hell better? :-) From mis6 at pitt.edu Sat Jul 6 06:53:48 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 6 Jul 2002 03:53:48 -0700 Subject: first experiences with Python Message-ID: <2259b0e2.0207060253.1723a696@posting.google.com> I became aware of the existence of Python a couple of months ago. The reason was an exceptional wave of heat in Pittsburgh, my problem the conversion from Fahrenheits to Celsius (I recently moved from Europe to the States and I hate Fahrenheits !). In the old days, I would have written a two line program in Basic to make the conversion. Unfortunately (or fortunately ;-) I was using Linux and there is no Basic on it. How to do the conversion ? Well, I thought, there should be some simple pre-installed language to do this kind of trivial jobs. Of course, the natural language under Unix-like systems would be C, but I immediately discarded this possibility due to my past experience (definitely, I don't like C; moreover I don't think it is a good idea to use a difficult tool to do a simple task). Therefore I looked at the list of languages installed on my machine and I discovered Python: "Python is an interpreted, interactive, object-oriented programming language" (quoted from the RPM package description in Red-Hat Linux) Well, I thought, maybe this is what I want. The fact that it was an interpreted language suggested simplicity of use (possibly).Moreover, it was documented and available on any Red Hat Linux system for free, already installed. Then I printed the tutorial and at a first look the language seemed quite simple. But actually it was more than that: it did what I expected ! I pretty soon discovered it from my first program, the conversion from Fahrenheits to Celsius. Since the tutorial (Guido forgive me !) is not well written and lacks such an essential thing as documenting the interactive input methods, I was forced to guess the sintax. I thought: which is the simplest way I would implement an input command, what's the obvious way things should work ? Of course F=input("Input the temperature in Fahrenheits: ") Then I tried, but from my past experience with others languages, I was sure of having troubles ("in computer science, things never work the obvious way"): but incredibly it worked since the very first attempt. This never happened to me before ! Encouraged by this little success, I solved my next problem guessing too: how to print the result in Celsius rounded to an integer ? What would be the obvious way, I asked myself ? Of course print "Temperature in Celsius: ",int(round((F-32)*5/9.0)) if the function round() exists. And actually it is a built-in function and does what expected. Having a language that did what I expected was unusual and excited me very much (I still remember the experience with my first program in C, when I wasted a lot of time since I couldn't imagine that to compute 1+1 I explicitly needed to link the math libraries !). Some time later the wave of heat passed and I decided to give a try to Python with a less trivial project. An old favorite of mine is a program to manage my archive of books, making various kind of histograms (for instance the number of books read versus the months of the year, the number of books versus the genre, etc.). The first version was implemented in AmigaBasic in 1987 (when I bought my first computer!), followed by a version in Pascal in 1988. Then for many years I did not program very much, I was too busy with other stuff. In 1999 I wrote a version for Mathematica, which however left me unsatisfied for many reasons. I wanted something better. And I found it ! Using Python, I implemented the most effective and sophisticated version I ever wrote in less than a week (I mean working only in my free time) ! I was really impressed by the power of the language and ever more by its simplicity of use, particularly comparing my experience with Python with the experience I had with C. The enormous advantage of Python, is that you can reuse what you already know: for instance, to plot the histograms I didn't need to learn a new set a commands, I simply used Python to write and execute a gnuplot program. Then I used Python to write a latex program which included the gnuplot pictures, I added some tables and comments and I invoked latex2html to create a Web page with very professional-looking results: and all that in an impressively short time ! The single feature that impressed me the most, is Python's ability to write programs that write programs, even in other languages ! But there are many other things that I liked, for instance the functions exec() and eval() which were new to me (I like this idea of automatic code generation). Moreover, I like the import statement that makes it possible for the user to create his own library of functions with no effort. Of course, this is an essential feature for a language which has to be scalable to larger applications. Python is as simple and readable as Basic but as full featured as the most powerful languages of the XXI st century. I don't care about the intrinsic slowness of an interpreted language with respect to a compiled one, it is of no point for my applications; moreover, Python is not really slow since most of the work is done by the powerful routines of the standard library: for instance my Python program was dozens of times faster than my Mathematica program implementing the same algorithm. No doubt that programming languages have undergone an enormous progress in the last years, but unfortunately this progress has been hidden in many languages by rather obscure syntaxes and technical complications which are absent in Python. Finally, one can spend his time in learning concepts, not a compiler's syntactical idiosyncrasies! Anyway, let me stop this praise to Python (people reading comp.language.python are already convinced) and let me come to the reason why I am posting this message. I want to raise a point about Python's accessibility to new users. Given for granted that the language per se is good and easy to learn, my questions are: how good is Python's documentation ? How could the Python community better help newcomers ? What are the most difficult things to learn and those that should be better explained ? What are the best references that should be recommended according to the newcomer's background ? Some of these questions should be asked to newbies, people who learned Python in the last six months, certainly not to experienced pythonists which cannot have a fresh look on these matters. For instance, in my personal opinion, the Python official tutorial becomes good only when you have already learned the language, but this is not what should happen to a tutorial written for newcomers. It is true that the Python home-page contains a list of links to "Python for beginners", but I feel that the official Python tutorial should be modified and simplified. Or, even better, I'd like to see in the official distribution a mini-tutorial for absolute beginners, to be read before the other tutorial. The reason is that many people (including myself) prefer to read the official documentation before searching in other places, especially because the official documentation is supposed to be updated whereas the unofficial one, who knows ? Therefore I overlooked the "Python for beginners" links and discovered the hard way that wasn't a good idea. A very simple and readable source for beginners I would recommend is the book "How to think as a computer scientist" (the other references in "Python for beginners" are good too). It has two features: 1) it is free; 2) it is written to be understood by high school students with no programming experience, thus everybody can read it; somebody with experience can absorb it in a couple of days. It is a little long, but I have found myself spending less time in reading a 200 page simple book with lots of examples that an hypercondensed 90 page reference manual with no examples. A little disadvantage is that it is not updated to Python2.2, unfortunately. I don't know if it will be updated. After the book I immediately passed to the Python Library Reference, which is over 600 hundred pages, but very well written and useful (you don't need to read the full reference, only the parts you need for your application, and reading the contents will give you a clear understanding of the potentialities of the language). Really, I had less trouble in learning from the Library Reference than from the tutorial ! It seems that the tutorial is written with the aim to wet the appetite, not with the aim to teach the language, but in my opinion this should NOT be the case for a tutorial. After having some experience with Python, I looked for the newsgroup. comp.lang.python is very interesting and helpful, but certainly it is not for the absolute beginner; however, after few weeks of experience with Python I have become able to follow the discussion: then I asked a question on Tkinter such that I could have hardly found the solution by myself and I had a precise, terse and effective answer in less than four hours. Moreover, by reading the postings I learned a lot about more recent features of Python not documented in the book and which I skipped in the Reference Library. Definitely, I will suggest to post in comp.language.python as the most effective way to get help (however, be aware that some questions can start a flame war ;-). Summarizing, this is the advice I would give to a newbie (other people can give their advice or tell their experiences too): 1) skip the tutorial 2) read one of the references in http://www.python.org/doc/Newbies.html 3) read the sections of the Reference Library you are interested in 4) for tricky points, ask comp.lang.python 5) finally, remember that the code is there, look in the standard distribution programs and learn how professionals write! I started to appreciate the standard tutorial in between steps 4) and 5): at this point it is definitely useful. Hoping this will be helpful to somebody, --- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From andreas at kostyrka.priv.at Sat Jul 27 16:11:22 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 27 Jul 2002 22:11:22 +0200 Subject: global variables In-Reply-To: <3D3C6F61.5070400@destiny.com> References: <3D3C6F61.5070400@destiny.com> Message-ID: <1027783500.19810.47.camel@vaio2> Am Mon, 2002-07-22 um 22.47 schrieb Michael Chermside: > Python has global variables... any variable declared at the "top level" > (ie, not inside a function or class) is a global variable. The only > trick that you need to know is this: global variables are tracked on a > per-module basis. This means that if your code is all in one module, > then you can go ahead and just use globals. Well, it's not that trivial. If you want to assign to global (module level) variables inside some function/method, you need to declare this by using global: mylist=[] def clearList(): global mylist mylist=[] def addToList(item): mylist.append(item) # this modifies the list # but does not assign anything # new to mylist. Andreas From spam at oblomov.org Wed Jul 10 16:54:36 2002 From: spam at oblomov.org (oblomov) Date: Wed, 10 Jul 2002 22:54:36 +0200 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: <20020710225436.10494132.spam@oblomov.org> On Wed, 10 Jul 2002 15:32:07 -0400 "Steve Menard" wrote: > > "Jacek Generowicz" wrote in message > news:tyf7kk4jauz.fsf at pcitapi22.cern.ch... > > "Bo M. Maryniuck" writes: > > > > > On Tuesday 09 July 2002 16:59, curt finch wrote: > > > > ftp://ftp.jump.net/pub/journyx/other/PythonWhtPaper0_1.doc > > > > > > Right people will not download this. M$ Word DOC is *evil* format. > Please do > > > PDF, DVI or HTML instead. > > > > I'll second that. I was about to have a look, and then saw the doc > > extension. I take doc extensions to mean "This document is intended > > for Microsoft customers only". I am not a Microsoft customer. > > See, this is something I really don't understand. I will agree that PDF or > html would have been a better choice, but not everyone can generate PDF ya > know. With this kind of attitude, we'll forever be regarded as the > extremists who won't listen to anything .... Antiword: a free MS Word document reader Summary: Antiword is a free MS Word reader for Linux and RISC OS. ... This Microsoft Word reader is called Antiword for reasons explained in the documentation. ... Description: A freeware MS Word reader available for Acorn RISC OS, Linux and BeOS. Category: Computers > Systems > RISC OS > Software > DTP www.winfield.demon.nl/ - 9k - Cached - Similar pages karl From pecora at anvil.nrl.navy.mil Mon Jul 8 14:59:49 2002 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 08 Jul 2002 14:59:49 -0400 Subject: Why self? References: <3D29DD1A.6040209@onsitetech.com> Message-ID: <080720021459493536%pecora@anvil.nrl.navy.mil> In article <3D29DD1A.6040209 at onsitetech.com>, Robb Shecter wrote: > >> self.__velocity = self.__factor1 * self.__factor2 You don't need the double underscores. From goldbb2 at earthlink.net Sun Jul 28 01:07:00 2002 From: goldbb2 at earthlink.net (Benjamin Goldberg) Date: Sun, 28 Jul 2002 01:07:00 -0400 Subject: Two dimensional regexp matching? References: <3D4285A3.80407@tiscali.co.uk> Message-ID: <3D437BF4.7733272E@earthlink.net> Paddy wrote: > > We already have the re module for regular expression matching on a string. > > I am looking for pointers to references/algorithms for regular > expression matching for files of tabular data, i.e. > > Table definition > ================ > 1) Samples from one point in the system > appears in a column of the table. > 2) Samples encoded as characters > 3) All points in the system are sampled at the > same time to produce successive rows of the table > > So a system sampled at two points in successively may produce the > following file: > > GH > DF > AS > QW > FF > SD > > I want to be able to do regular expression type searches within the > file. Things like > Where can I find > point1 == (D or G) then point2 == W within three samples > and > where the next sample of point2 != the earlier sample of point1? Hmm... To match just the first part /[DG].\n(?:..\n){0,2}.W\n/ might do it. And with that other requirement: /([DG]).\n(?:..\n){0,2}.W\n.(?!=\1)./ > That was a small example, in reality there is usually hundreds of > points and tens of thousands of samples in multi-megabyte files but The problem isn't in the size of the data (or at least, not *just* in the size of the data), but in the complexity of the regular expressions. > I'd first like to see if anyone else has considered this kind of 'two > dimensional regexp matching' > > Note: I DO NOT have queries in the date on sample points. The queries > will always be "Find the range of sample times in which 'this' > occurs". > > I have tried Google but without success - I don't know enough to think > of a suitable search phrase, or, (much less likely), Google doesn't > have it ;-) > > Thanks in advance, Paddy. -- tr/`4/ /d, print "@{[map --$| ? ucfirst lc : lc, split]},\n" for pack 'u', pack 'H*', 'ab5cf4021bafd28972030972b00a218eb9720000'; From pecora at anvil.nrl.navy.mil Mon Jul 8 16:50:37 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Mon, 08 Jul 2002 16:50:37 -0400 Subject: Why self? References: Message-ID: <080720021650379803%pecora@anvil.nrl.navy.mil> In article , Brian Quinlan wrote: > If the explicit self argument were removed, what would you add to the > language to differentiate between local and instance variables? > Here's a stab. (1) All self variables have to be initialized in __init__. That's just good practice anyway. They are labeled with self in __init__ otherwise they are local. (2) There can be no name conflicts between local and self variables. Also good practice within an object. -- Lou Pecora - My views are my own. From bokr at oz.net Wed Jul 24 19:44:20 2002 From: bokr at oz.net (Bengt Richter) Date: 24 Jul 2002 23:44:20 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 23 Jul 2002 10:47:10 +0200, holger krekel wrote: >Paul Rubin wrote: >> martin at v.loewis.de (Martin v. Loewis) writes: >> > You can put a callable object in sys.modules. Module objects >> > themselves are not callable. >> >> Is this documented somewhere? I don't see it in the obvious places. >> >> > > If there's not a way to do this already, maybe it's a reasonable >> > > addition. >> > >> > Maybe not. Why do you need this? >> >> Just to not have to say "foo.foo()" or "from foo import foo". >> >> If the main purpose of the module is to provide one function, I think >> it's cleaner to be able to import the module and call the function >> without special tricks. Or just use your own trick, e.g., given ----< PR.py >------ #PR.py for Paul Rubin def PR(): return 'Hi Paul' ------------------- Define one-line trick: >>> def PRimport(name, locs=locals()): locs[name] = getattr(__import__(name),name) ... And use it thus >>> PRimport('PR') >>> PR >>> PR() 'Hi Paul' > >Moreover, I often thought about integrating class and module types. >I am not primarly concerned about making modules callable, although >i might appreciate it. > >My use case is > > from somemodule.someclass import filter1 > >where 'filter1' would reference an unbound class-method. >I need this for implementing a class which offers filter >functions which can be applied either as > > obj.filter1(args) >or > filter1(obj, args) > >Of course, you can express the latter via > > someclass.filter1(obj, args) > >but i want to have filter1 (and 41 other filter methods) >potentially directly in the namespace. I *know* that i can write > > filter1=someclass.filter1 > filter2=someclass.filter2 > ... > >but it's redundant and you have to repeat this scheme whereever >you use 'somemodule'. That's ugly where in fact i just want to say > > from somemodule.filters import filter1,filter2, filter37 > >and someclass could inherit from 'filters', thus providing both >invocation methods. I know that i can *hack* this to work by > > - doing new.module('somemodule.filters') in somemodule > and adding the modules functions at runtime to someclass. > > - making up a package (with filters beeing in a different file) > and adding the modules functions at runtime to someclass > > - some variant of this schema > >but actually, doing the above 'from ....someclass import filter1,...' >seems much more expressive and doesn't involve any run-time hacks. > >I hope i made my point clear enough. Basically i'd like to >generalize the namespace-injection methods 'import' and 'from'. >This might involves extending the Module-type to work >more like a "usual" class with __getattr__ and such. Probabally >it only involves extending the import machinery. > >Unfortunately, i haven't found time to investigate the matter >but maybe someone can point out that it's the path to >all evil (read: wrong concept), anyway :-) > Is this what you want to do (just for grins I allowed a simple pattern to specify filter names). I (Warning: Not tested beyond what you see below ;-) you can do this, given the files noted below (ForHolger is a class in forHolger.py): >>> from importForHolger import importForHolger as impH >>> dir() ['__builtins__', '__doc__', '__name__', 'impH'] >>> impH('forHolger.ForHolger',globals(), locals(),['*Holg*']) >>> dir() ['ForHolger', '__builtins__', '__doc__', '__name__', 'filterHolger1', 'filterHolger2', 'im pH', 'methodForHolger'] >>> fh=ForHolger() >>> fh.filterHolger1() 'filtered by Holger1: KREKEL' >>> fh.filterHolger2() 'filtered by Holger2: krekel' >>> filterHolger1(fh) 'filtered by Holger1: KREKEL' >>> filterHolger2(fh) 'filtered by Holger2: krekel' >>> methodForHolger(fh,'an arg','another') methodForHolger called with: self= args=('an arg', 'another') >>> fh.methodForHolger('an arg','another') methodForHolger called with: self= args=('an arg', 'another') >>> fh.filter1() 'KREKEL' >>> fh.filter2() 'krekel' >>> fh.someOtherMethod() 'OM: Krekel' >>> impH('math',globals(), locals(),['pi','c*','*n']) >>> for k,v in locals().items(): print '%15s = %s' % (k,`v`) ... asin = cos = filterHolger1 = filterHolger2 = __builtins__ = ForHolger = ceil = atan = cosh = methodForHolger = tan = fh = __name__ = '__main__' impH = pi = 3.1415926535897931 sin = __doc__ = None math = --< forHolger.py >------------- #forHolger.py class ForHolger: def __init__(self, v='Krekel'): self.v = v def methodForHolger(self, *args): print 'methodForHolger called with:\nself=%s\nargs=%s'%(`self`,`args`) def filter1(self): return self.v.upper() def filter2(self): return self.v.lower() def filterHolger1(self): return 'filtered by Holger1: %s' % self.filter1() def filterHolger2(self): return 'filtered by Holger2: %s' % self.filter2() def someOtherMethod(self): return 'OM: %s' % self.v ------------------------------- --< importForHolger.py >------- # importForHolger.py def importForHolger(name, globs, locs, thinglist=None): """Walks dotted name and "imports" attributes matching thinglist patterns""" names = name.split('.') entity = __import__(names[0], globs, locs) for ename in names[1:]: entity = getattr(entity, ename) # walk to last entity locs[names[-1]] = entity # assume we want the entity as well as selected things for thingpatt in thinglist: # grab things in entity matching thingslist # allow for thingpatt or *thingpatt or thing*patt or thingpatt* or *thingpatt* tp = thingpatt.split('*') if len(tp)==1: matchtest = lambda x: x==tp[0] elif len(tp)==3: # *thingpatt* matchtest = lambda x: x.find(tp[1])!=-1 elif tp[0]: if tp[1]: matchtest = lambda x: x.startswith(tp[0]) and x.endswith(tp[1]) else: matchtest = lambda x: x.startswith(tp[0]) else: matchtest = lambda x: x.endswith(tp[1]) for k,v in entity.__dict__.items(): if matchtest(k): locs[k]=v ------------------------------- It seems to work inside a function too ( 2.2 on windows): >>> def foo(): ... from importForHolger import importForHolger as impH ... impH('math',globals(), locals(),['pi','c*','*n']) ... return locals() ... >>> d=foo() >>> for k,v in d.items(): print '%15s = %s' % (k,`v`) ... asin = cos = atan = sin = impH = pi = 3.1415926535897931 cosh = tan = math = ceil = That doesn't do what I wanted to do, though. I wanted to make a module with an attribute the works like a real property. So while we're on the subject (? ;-) of "integrating class and module types" ... given ----< testmod.py >----------- #testmod.py import time def get_p(self): return self._p def set_p(self, v): self._p=v p = property(get_p,set_p) _p = 'class variable default for p property' asctime = time.asctime def get_now(self): return self.asctime() now = property(get_now) ----------------------------- and ----< myImport.py >---------- # myImport.py def myImport(name, globs=globals(), locs=locals(), *args, **kw): import sys class MyModule(object): execfile(name+'.py') tmp = MyModule() tmp.__dict__.update(kw) if args: tmp.import_args = args tmp.__name__ = name sys.modules[name] = tmp locs[name] = tmp return tmp ----------------------------- this seems possible: >>> execfile('myImport.py') # so locs get bound to interactive locs >>> myImport('testmod') <__main__.MyModule object at 0x007D00D0> >>> testmod.now 'Wed Jul 24 16:50:12 2002' >>> testmod.p 'class variable default for p property' >>> testmod.p='instance value' >>> testmod.p 'instance value' >>> del testmod._p >>> testmod.p 'class variable default for p property' Only tested as far as you see above ;-) Regards, Bengt Richter From b.maryniuk at forbis.lt Mon Jul 8 09:20:35 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 8 Jul 2002 15:20:35 +0200 Subject: PKSC1 In-Reply-To: References: Message-ID: <200207081520.35063.b.maryniuk@forbis.lt> On Monday 08 July 2002 14:27, Alex Martelli wrote: > Assuming you mean PKCS1 (as per RFC 2437) Yes, exactly that. Sorry. ;-) -- Sincerely yours, Bogdan M. Maryniuck "All language designers are arrogant. Goes with the territory..." (By Larry Wall) From shalehperry at attbi.com Mon Jul 29 16:03:42 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 29 Jul 2002 13:03:42 -0700 (PDT) Subject: Python design failures (was Re: Let's Talk About Lambda Func In-Reply-To: Message-ID: > > Yes, the Python std lib has backticks in it. Cleaning that up would > likely be the first step toward deprecating backticks. In any event, > backticks will certainly be available at least until Python 3.0. well seeing as the python group went through and replaced all of the string exceptions with class based ones why not have another pass at modernizing python's lib? I am not suggesting we kill lambda/map with list comps but little things like backticks can be killed fairly quickly. I could submit a patch for the repr cleanup in pretty short order. From mwh at python.net Fri Jul 26 06:11:01 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 10:11:01 GMT Subject: [Python-Dev] Powerpoint slide for keynotes available References: <200207250004.g6P04pP20522@pcp02138704pcs.reston01.va.comcast.net> Message-ID: "Guido van Rossum" writes: > I wrote: > > If someone can donate PDF that would be great (the HTML > > generated by Powerpoint sucks too much to be worth it IMO). > > > > http://www.python.org/doc/essays/ppt/ > > > > (scroll to end) > > I've received about 5 offers of PDF. The first one is now on the web. > Mark Hadfield won the race. :-) Did anyone take notes during the open mike session this time? Cheers, M. -- I never realized it before, but having looked that over I'm certain I'd rather have my eyes burned out by zombies with flaming dung sticks than work on a conscientious Unicode regex engine. -- Tim Peters, 3 Dec 1998 From piet at cs.uu.nl Tue Jul 9 09:31:29 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 09 Jul 2002 15:31:29 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: >>>>> loewis at informatik.hu-berlin.de (Martin v. L?wis) (MvL) writes: MvL> Piet van Oostrum writes: >> Well, I looked into the Unicode specs and it says that even if single >> surrogates appear in a string, the UTF-8 encoding should generate a valid >> UTF-8 byte sequence, which on encoding should give the same surrogate. So >> I would say this is a bug in the UTF-8 encoding. MvL> Which Unicode specs did you look at? Unicode TR #28 (aka Unicode 3.2), I looked it up in The Online Edition of The Unicode Standard, Version 3.0 In chapter 3, section 3.8 it said: Because every Unicode coded character sequence maps to a unique sequence of code values in a given UTF, a reverse mapping can be derived. Thus every UTF supports lossless roundtrip transcoding: mapping from any Unicode coded character sequence S to a sequence of code values and back will produce S again. To ensure that round-trip transcoding is possible, a UTF mapping _must also_ map invalid Unicode scalar values to unique code value sequences. These invalid scalar values include FFFE, FFFF and unpaired surrogates. This sentence is also in the FAQ: http://www.unicode.org/unicode/faq/utf_bom.html Technical Reports tr27 and tr28 do not withdraw this. MvL> http://www.unicode.org/unicode/reports/tr28/ MvL> says MvL> MvL> The definition of transformation formats such as UTF-8 allowed MvL> conformant processes to interpret certain sequences called irregular MvL> sequences. These irregular sequences are those that would be produced MvL> by transforming supplementary code points as if they were a sequence MvL> of two surrogate code points. MvL> To tighten the definitions, in Unicode 3.2 such irregular sequences MvL> are now illegal. MvL> I think the above applies to something different, namely, if you have a surrogate pair that encodes a legal Unicode character, and the surrogates are independently transformed to UTF-8, rather than being transformed as a single character. MvL> Table 3.1B of the same document explicitly lists the byte sequences MvL> that would denote code points D800-D8FF as illegal. You are right. I found a long discussion in the i18n-sig archives in which you also participated. One conclusion was that the Unicode standard contradicts itself in this area. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From aleax at aleax.it Wed Jul 24 04:25:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:25:43 GMT Subject: No subject References: <3d3d53f4.356458609@news.skynet.be> <3d3d5dc4$0$94901$e4fe514c@dreader3.news.xs4all.nl> Message-ID: Yigal Duppen wrote: >>> What datatypes can one use as key in a dictionary? >> anything immutable. thats numbers, strings, tumples > > And of course any object that implements the __hash__(self) method. > > (Note: it is usually a good idea only to implement __hash__ for > immutable objects; hashing mutable objects can give very... interesting > results) Right, BUT -- this isn't the whole picture. Consider: >>> class X: pass ... >>> a=X() >>> b=X() >>> adic={} >>> adic[a]=23 >>> adic[b]=45 >>> adic[a] 23 >>> adic[b] 45 >>> See? Instances of this do-nothing, know-nothing class X, while of course being mutable, are also quite usable as keys in a dictionary. So, what gives? Answer: X doesn't implement __eq__ (nor __cmp__). Thus, equality checks on X instances implicitly use 'is' (or, if you prefer, implicitly use id(theinstance)). So, the hash value is also done that way: >>> id(a) 135653148 >>> hash(a) 135653148 >>> Keys don't have to be immutable, though most often they will be: what matters is that a key never compares unequal to some "previous version" of itself, and keys comparing equal also have the same hash value. In practice this means, EITHER immutable OR not defining equality-comparison and thus implicitly falling back to identity-comparison for the latter. Alex From jb at hotmail.com Wed Jul 24 05:26:52 2002 From: jb at hotmail.com (JB) Date: Wed, 24 Jul 2002 11:26:52 +0200 Subject: Regular expressions? Message-ID: <3d3e7106_9@news.newsgroups.com> I am working on an offline newsreader (with very limited capabilities). I think the only way I can reckognize a multi part message is that in the header something like '(1/12)' , which I call multi part indicator, is included in the subject field. Now I have seen that sometimes they use '[1/12]' and sometimes this indicator is not at the end of the subject line but somewhere in the middle of the line. (The number of bytes in the message could follow the multi part indicator). So I have to find the indicator in a line. Should I apply regular expressions to solve this problem? -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From tim.one at comcast.net Mon Jul 8 14:34:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 08 Jul 2002 14:34:18 -0400 Subject: `~/.pythonrc' `from __future__ import' In-Reply-To: Message-ID: [Fran?ois Pinard] >>> How should I proceed to activate this [future division] ]option once >>> and for all for interactive applications? [Tim] >> You can write an alias to start interactive sessions by passing -Qnew to >> Python. [Fran?ois] > I've heard about this undocumented feature indeed, and hoped to go without > resorting to it. All the -Q options are documented in the division PEP: http://www.python.org/peps/pep-0238.html > Moreover, this option only works for division, it does not apparently > activate generators, for instance. Yes, -Q is specific to division, as will become clear if you read the PEP 238 "Command Line Option" section. > I would rather have all future features available all the time when I > write interactively, yet I guess why some people would prefer not. There's no way to do that, short of fiddling Python's source code. > ... > However, it wonder if this is all fully right. The actual documentation > and the PEP say that one could `import __future__' explicitly, so to > check at run time what features are currently available in the running > Python. You could, although I advise against it (see below). For example, """ import sys try: import __future__ div = __future__.division except ImportError: print "This version of Python predates __future__ statements." except AttributeError: print "This version of Python never heard of future-division." else: opt = div.getOptionalRelease() mand = div.getMandatoryRelease() if mand is None: print "It was decided to drop future division." elif sys.version_info >= mand: print "future-division is enabled by default." elif sys.version_info >= opt: print "future-division is available if you explicitly ask for it." else: print "future-division isn't yet available." """ prints the truth about future-division under any version of Python that ever was or ever will be released. > Besides its compile-time effect, `from __future__ import division' (say) > dynamically defines `division' at run-time in the global space, at least > when done from the startup file, Yes, its runtime effect is the same as from math import cos or from difflib import SequenceMatcher or any other "from ... import ..." statement. > but this is no strong clue about if the feature has been activated or > not (at least when the Python version lies between the introduction > version and, excluded, the mandatory version). That "from __future__ import division" doesn't raise an exception means you're in one of the four states covered by the "else:" clause above. The code there shows how to distinguish among those, but again I don't recommend trying to do so. The possibility for this kind of introspection is for heavy-duty site-management tools (should anyone wish to implement such things). > Would it mean that one has no other choice than "benchmark" the feature at > run-time, the ugly way, to know whether it is active or not? The current > intent is to let an `from __future__ import FEATURE' generate an error if > the FEATURE is wanted in a module, but not available in the current > Python. > > Suppose, for example, that I write a module in which some function makes > good use of some future feature (it could be the `yield, statement), > but I want to provide an alternate implementation of that function which > is less interesting (because it gets much complex and slower) in case the > feature is not available. Since I cannot except out of the `from > __future__ > import' statement, for reasons I understand, I do not see how I take good > advantage of available future features, in a program meant to be portable > between versions. Maybe the future statement is rougher than I expected? It's less ambitious than you may want it to be. It was emphatically not the intent of future-statements to create multiple "pick and choose" dialects of Python. Its only design goal was to provide a transition period between flat-out incompatible semantics, where during the transition period you: 1. Continue to get the old semantics, but also get warnings about code that's going to break when the semantics change. and 2. You can explicitly request the new semantics on a module-by-module basis, to aid in reworking legacy code incrementally. #2 is intended for people who want an easy way to turn new semantics on and off while redoing their code, a bit at a time, to work either way -- provided they care about that. For everyone else, a future-feature is a planned experimental feature that may even get dropped (hence the possibility for .getMandatoryRelease() to return None). Portable distributed code should never contain a future statement! It wasn't designed for that, and, as you've discovered, trying to use it for that sucks. It's not for portability: it's a temporary aid to ease the transition between incompatible semantics. Note that, e.g., the only reason generators got put under the __future__ machinery is that they make "yield" a new keyword. That's "flat-out incompatible semantics", and the only purpose of the future machinery here is to give people a release cycle in which to rename their existing "yield" identifiers (provided they have any -- I haven't yet found any code that does, although I'm sure some exists somewhere). the-point-of-__future__-is-mostly-to-ease-living-in-the-past-ly y'rs - tim From joconnor at cybermesa.com Thu Jul 25 11:53:05 2002 From: joconnor at cybermesa.com (Fearless Freep) Date: 25 Jul 2002 08:53:05 -0700 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> <3D3EA54C.3EF009A@lfpt.rwth-aachen.de> <3D3DF209.17923D28@cybermesa.com> Message-ID: <7d3dc526.0207250753.59e8db61@posting.google.com> vvainio at tp.spt.fi (Ville Vainio) wrote in message news:... > Jay O'Connor wrote in message news:<3D3DF209.17923D28 at cybermesa.com>... > > > That was my other thought., wondering if someone else had already done > > what I was toying with. It appears so :) > > Yes, almost everybody starts to think about implementing a distributed > objects scheme when playing with python. It's so easy and fun, and > things like introspection practically force one to reinvent the wheel > ;-). > > It would appear that the sensible thing to do is to go the CORBA way, > which is tried, true, *easy* (controversy on this issue mainly > concerns non-python bindings) and interoperable (and fast, at least > with omniORBpy that I've tried). Well, my main motivation was that I'm going to be leaving my job and I was casting about for things to do. I remembered this code and was wondering if it would be worth finishing it up, either for sale or as a demo/example for prospective hirers. Take care, Jay http://www.r4h.org/r4hsoftware From pecora at anvil.nrl.navy.mil Fri Jul 12 09:53:48 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Fri, 12 Jul 2002 09:53:48 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> Message-ID: <120720020953486319%pecora@anvil.nrl.navy.mil> In article <3D2E508C.DBDF9E52 at engcorp.com>, Peter Hansen wrote: > > Just go and design + develope your own keyboard. > > Since you post without smileys, I can only assume you are serious? > > To which my response is: you can't be serious. :-) > > (Hint, the original was a joke... note the partial wink. I do > hate underscores, but concluding from that that my best option > is to design and develop my own keyboard is just bizarre.) Yes, I should have added a smilely. :-) Sorry. But my proposal is no more bizzare than yours suggesting we design our own language or such. Both proposals are in smilely land. I hope you agree. ;-) -- Lou Pecora - My views are my own. From observer at NOSPAM.space.pl Mon Jul 22 08:51:07 2002 From: observer at NOSPAM.space.pl (Johann) Date: Mon, 22 Jul 2002 14:51:07 +0200 Subject: XSLT processor References: Message-ID: <3rvnju0c276pen4cemsmb2qi4v0dpjusrk@4ax.com> On 20 Jul 2002 15:12:19 GMT, Stefan Heimann wrote: > Does anyone know if there is something similar for python? Check this: http://pyana.sourceforge.net/. Look at examples: http://pyana.sourceforge.net/examples/ -- Johann From fperez528 at yahoo.com Fri Jul 26 19:36:06 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 17:36:06 -0600 Subject: performance problem in python 2.2 References: <7xn0sedslz.fsf@ruckus.brouhaha.com> <7x8z3y12uf.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Fernando Perez writes: >> The fact that one may spend a year's worth of cpu in computing an >> expression for which an analytic solution exists is orthogonal to >> the point I was making. > > It's a different point, yes, but related. Point 1, rather than bend > backwards trying to optimize Python or Perl, write cpu-intensive > code in a language that's closer to the machine. Point 2, rather > than bending backwards writing efficient cpu-intensive code, look > for a non-cpu-intensive way to solve your problem. Amen. I'd actually flip them in order of preference: 1. be smart. 2. when you can't, at least be efficient. Cheers, f. From bokr at oz.net Wed Jul 24 20:09:10 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 00:09:10 GMT Subject: Help On file IO References: Message-ID: On Tue, 23 Jul 2002 18:13:16 +0530, "jayant kawadkar" wrote: > > Hello , > > I want a help on File IO ,as I 'm new to Python langauge. > As I want to use the API : > > char* PyModule_GetFilename(PyObject *module) > > in my python programm > > What should I import for that I can use this . > > Now it is giving the error that: > > PyModule_GetFilename is not defined. To be unambiguous, it's best to copy an interactive example showing the error happening, and paste it into your post. Plz help the helpers ;-) > > > Plz help .... > That is getting the __file__ attribute of a module, it it exists (which it will if the module was imported from a file, not built-in, etc.) Example in Python source (or are you writing a C extension?) >>> import urllib >>> urllib.__file__ 'D:\\python22\\lib\\urllib.pyc' >>> import math >>> math.__file__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute '__file__' >>> math >>> urllib Regards, Bengt Richter From huaiyu at gauss.almadan.ibm.com Tue Jul 9 13:50:54 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 9 Jul 2002 17:50:54 +0000 (UTC) Subject: Splitting a string every 'n' References: Message-ID: Harvey Thomas wrote: >import re >rex = re.compile('....', re.DOTALL) To work with any int n, change to one of these rex = re.compile('.{,%s}'%n, re.DOTALL) # keeps remainder segment rex = re.compile('.{%s}'%n, re.DOTALL) # discards remainder segment > >for substring in rex.findall(string): > Huaiyu From jonathan at onegoodidea.com Wed Jul 3 04:34:08 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 03 Jul 2002 09:34:08 +0100 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: On 3/7/2002 7:41, in article eaef2e43.0207022241.62891b7e at posting.google.com, "Robert Kuzelj" wrote: > what is a feature of 2.2? that you cant distinguish between > a class and an instance? hardly! No, that really is a feature! Pretty much *everything* in the system is an object. This makes the entire language uniform in its operation. It makes instrospection easier and it allows metaclasses to change the behaviour of classes. > i am very well aware of this. but it doesnt solve my problem. Then perhaps you could explain your problem and maybe we can help. So far you've told us how you're going about something, but not why. Why do you need to differentiate between classes and "instances"? Perhaps there's another way to do what you want that will work. Jonathan From and-google at doxdesk.com Mon Jul 15 05:47:58 2002 From: and-google at doxdesk.com (Andrew Clover) Date: 15 Jul 2002 02:47:58 -0700 Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <2c60a528.0207120147.498bc1f3@posting.google.com> Message-ID: <2c60a528.0207150147.fa6e79@posting.google.com> Rich Harkins wrote: >> while cond1: >> dofoo() >> andwhile cond2: >> dobar() > So does this eqate to the following in current python? Yes, the latter: > while cond1: > dofoo() > if cond2: > dobar() > else: > break Except that any else-clause following the loop would be unaffected. >> if cond1: >> dofoo() >> andif cond2: >> dobar() >> else: >> doqux() > and this? Again, the latter: > if cond1: > dofoo() > if cond2: > dobar() > else: > doqux() > else: > doqux() I find myself writing structures like this very often, in many languages. I find both current solutions - repeating the else-clause as above, or using a temporary variable - quite unsatisfactory. > What if I get more complicated: > [if ... andif ... elif ... andif] Two possibilities: a. andif has higher precedence than elif, binds to last else/elif clause only b. this is too confusing to be usable, allow andif only after an if or andif, not else/elif. I prefer (b). -- Andrew Clover mailto:and at doxdesk.com http://and.doxdesk.com/ From timr at probo.com Thu Jul 25 02:05:51 2002 From: timr at probo.com (Tim Roberts) Date: Wed, 24 Jul 2002 23:05:51 -0700 Subject: Python on W2000 References: Message-ID: "tony papadato" wrote: >it is possible to generate an executable file and run it on >different machines without python installed on them ? Yes. There are several packages that bundle up the Python interpreter, your script, and all the DLLs and Python modules it needs in order to run into a single executable. When run, it basically creates a mini-Python installation and then runs the script normally. The McMillan installer is one way, http://www.mcmillan-inc.com/install1.html. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aleax at aleax.it Tue Jul 16 04:23:39 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 16 Jul 2002 08:23:39 GMT Subject: Webware 0.7/Singleton pattern References: <3D33D57C.6000709@mxm.dk> Message-ID: Max M wrote: > Michael Bub wrote: > > >> does anyone know how to get "safe" singleton classes to get rid of >> that problem? > > I belive that Alex Martelli has posted a singleton class to the group, > or to the coockbook. > > Oh ... guess I found it at: > > http://www.onlamp.com/pub/a/python/2002/07/11/recipes.html?page=2 I have also done a more complete write-up of the Borg non-pattern for IPC10 -- please see: http://www.aleax.it/Python/5ep.html Alex From shagshag13 at yahoo.fr Mon Jul 8 08:23:35 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 8 Jul 2002 14:23:35 +0200 Subject: Memory ? References: Message-ID: "Alex Martelli" > > That i can' t guess the size of my arrays (range from 0 to ???) > > Both the array.array type, and the vastly more powerful Numeric.array > type from the Numeric extension package, are arrays that can grow and > shrink. sorry to bother, i didn't find a way to append a numeric.array, should i do this by using "concatenate" ? or do i miss the "correct efficient" way ? thanks, s13. From psage at ncaustin.com Thu Jul 11 12:57:27 2002 From: psage at ncaustin.com (Paul Sage) Date: Thu, 11 Jul 2002 11:57:27 -0500 Subject: Learning how to program... but what's the best way? Message-ID: <03F53405C6ED434A986221919785A6A7106CB4@nca-postal.ncaustin.com> Depending on the interests, I have some other suggestions: 1)Gaming. Have her pick up Neverwinter Nights and try her hand at the scripting languages. I recommend this because it has a very active community to help her with questions. The only problem with this is it won't teach proper technique or discipline. I recommend some parallel learning with Python or something else. 2)Internet or Web Pages. Flash. Go with something that is going to be visually exciting quickly. Flash will start to point to some programming basics, even if it has some pretty non-standard functionality. 3)Straight programming. Sign her up on Python and get her on the list. I would especially recommend some community college pick up courses. Then have her pick another interest and see how an oft repeated easily automated task could help with that. Of course, there may be several other interests, but those are my main suggestions. From jdhunter at nitace.bsd.uchicago.edu Thu Jul 18 11:41:47 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 18 Jul 2002 10:41:47 -0500 Subject: Python robot web client? References: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> Are there any Python robot web clients around, sort of like Paul> Perl LWP? I mean something fancier than urllib, that parses Paul> the HTTP headers and remembers any cookies. It would also Paul> be great if it parsed the HTML enough to find the form Paul> fields, links, and so forth. I guess I can implement what I Paul> need, but thought I'd ask first if something like it is Paul> already available. You may want to take a look at Python-2.1.3/Tools/webchecker/websucker.py in the python src tree -- it mirrors web sites. I don't think it has support for cookies orforms, but it would be a starting point if you want to roll your own. John Hunter From tdelaney at avaya.com Wed Jul 24 20:21:18 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 25 Jul 2002 10:21:18 +1000 Subject: how to count lines in a file ? Message-ID: > From: Richard Jones [mailto:rjones at ekit-inc.com] > > Where? I'm looking at the latest library reference for file > objects, and it > makes no such statement. Unfortunately, it makes no statement > either way, and > there's a lot of art out there that takes advantage of the > close-on-collect > behaviour :( Pay particular attention to the third paragraph below. The issue is not whether such resources are closed when they are collected, but whether they are collected at all. 3.1 Objects, values and types Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether -- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. (Implementation note: the current implementation uses a reference-counting scheme with (optional) delayed detection of cyclicly linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the Python Library Reference for information on controlling the collection of cyclic garbage.) Note that the use of the implementation's tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a `try...except' statement may keep objects alive. Some objects contain references to ``external'' resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The `try...finally' statement provides a convenient way to do this. Tim Delaney From fperez528 at yahoo.com Thu Jul 25 12:40:00 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 25 Jul 2002 10:40:00 -0600 Subject: Completion in emacs mode References: Message-ID: Jacek Generowicz wrote: > Hi, > > I'm looking for the ability to do command completion in Emacs' python > mode. I haven't managed to get Google to show me anything really > pertinent to this quest. > > Any ideas ? Contact me privately if you want access to some still experimental code that does this. It was written by Alex Schmolck for integration with ipython, so I don't know if it works with plain python (ipython is better anyway :). We haven't released it publically yet because it's not 100% finished, but it's quite useable. You'll need 1. ipython, from http://www-hep.colorado.edu/~fperez/ipython/ 2. A patched (by Alex) python-mode.el, which I have and can give you. 3. A new ipython.el special mode file, which I also have (also written by Alex). This provides standard emacs-type completion (in a *Completions* buffer) for python keywords, attributes and filenames in the current directory (ipython has some basic shell-like functionality built-in). Cheers, f. From is at gras.de Tue Jul 16 10:42:29 2002 From: is at gras.de (Ingo Stöcker) Date: Tue, 16 Jul 2002 16:42:29 +0200 Subject: preview of object attributes Message-ID: Hello Py-Freaks, I have a list which contains objects. These objects have two attributes. My task is that the second attribute should be shown a a kind of preview window. but I don't know what to do? Are there any guys who can help me? Regards Ingo From gerhard.haering at gmx.de Wed Jul 24 16:41:38 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 24 Jul 2002 20:41:38 GMT Subject: PyXPCOM and SVG References: <3D3EEFE1.5090109@myrealbox.com> Message-ID: Trent Mick wrote in comp.lang.python: > [Johann H?chtl wrote] >> Hello ! >> >> I was thinking of using Mozillas new SVG and/or the gecko rendering >> engine and XUL capabilities in a wxpython-application using PyXPCOM >> bindings. > > Phew. I don't know how you would mix XUL and wxPython. Stupid question maybe. What does XUL have to do with Gecko? I had the impression that you could embed Gecko in win32 or gtk apps just fine without having to touch XUL at all :) Especially on Windows, I believe there are only one or two lines to be changed to replace wxPython's upcoming IE component (in 2.3.3) with the Mozilla COM component. The IE and Gecko controls are interface compatible and only differ in class name and clsid. I've just read about it this evening. URLs of interest for the win32 side: http://www.iol.ie/~locka/mozilla/mozilla.htm http://www.codeguru.com/controls/iemozilla.html Being able to use Gecko in the gtk flavour of wxPython would be extra cool, but I have no idea how to do _that_. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From hancock at anansispaceworks.com Thu Jul 18 12:01:07 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 18 Jul 2002 09:01:07 -0700 Subject: examples of a safe Unpickler? References: <20020719005706.13355.66062.Mailman@mail.python.org> Message-ID: <3D36E643.8BCB82F0@anansispaceworks.com> Kevin Altis said: > The Security section of the pickle module documentation: > > http://www.python.org/doc/current/lib/pickle-sec.html > > talks about creating a safe unpickler. > [...] > > So, are there examples of an unpickler (preferably based on cPickle for > speed)? It is not clear to me from the documentation what I actually need to > do. The docs seem to imply that if an object is not marked as > __safe_for_unpickling__ then an UnpicklingError exception might be thrown > just using the default Unpickler, but if so, I would need an example or two > of a pickle with a security problem to test this. Throwing an exception > would be fine. It would be nice if there was a separate > UnpicklingSecurityError exception. See: http://www.zope.org/Members/htrd/howto/MiniPickle I used a variation of this myself to pack a nested dictionary (representing state information for a tree) into a browser cookie. I believe it simply raises an "UnpicklingError" if illegal data is found, but if you want something special, just define a new exception and call that instead. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From petitmermet at mat.ethz.ch Tue Jul 30 07:07:29 2002 From: petitmermet at mat.ethz.ch (Marc Petitmermet) Date: Tue, 30 Jul 2002 13:07:29 +0200 Subject: python 2.1.3 with tkinter support on Solaris 9 References: Message-ID: In article , loewis at informatik.hu-berlin.de (Martin v. Lowis) wrote: > Maybe you have overdone that; please chose *one* of the strategies, > not all of them. Just using LD_LIBRARY_PATH should be enough. What > value are you using for that? I have tested all of them but none worked. > > Perhaps you don't have a file named libtk8.3.so on your system, > perhaps you can't execute it, perhaps it isn't the Tk shared library? > Many things can have gone wrong. I have a libtk8.3.so on my system, it is executable and it is in the shared library. In the meantime I could compile python with tkinter support but I had to make a soft link from /p1/local/tcltk/tk-8.3.4/libtk8.3.so to /usr/local/lib. I just have the feeling that the find_file function in the setup.py script does not work porperly, at least in my case. If it would have worked properly, it should have found the libraries according to Modules/Setup, shouldn't it? Regards, Marc From andersjm at inbound.dk Mon Jul 22 14:12:39 2002 From: andersjm at inbound.dk (Anders J. Munch) Date: Mon, 22 Jul 2002 20:12:39 +0200 Subject: Python very slow on the Sharp Zaurus - any idea why? References: Message-ID: "Alexandre Courbot" wrote: > Note that the Arm doesn't have any floating point unit, and that the > floating point operations are all emulated. But I never use any floating > point arithmetic in my game or in my Python scripts. Note also that I > had to cross-compile the Python library myself from Python 2.2 sources, > as there is no lightweight Python distribution for the Arm. But I don't > get what's wrong. Does Python use floating point arithmetic internally? > Is there something else I missed? Python uses floating point to check for integer arithmetic overflow. - Anders From sholden at holdenweb.com Mon Jul 1 10:25:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 10:25:09 -0400 Subject: geting python files for use on web References: Message-ID: <1CZT8.67970$F16.67238@atlpnn01.usenetserver.com> "Ali K" wrote in message news:l8sT8.231729$6m5.196131 at rwcrnsc51.ops.asp.att.net... > how do i install the files? Do I have the people from which i am getting my > free space install the files? Do I just upload them onto my freespace? > It's a little more complicated than that. Apart from anything else, it depends on the web server you are using. Generally speaking you will have, or be able to create, a /cgi-bin directory, and code from there should execute. You may also have to condition your server to understand that Python files are executable. There are many laternatives to this simple set-up, however, and you might consider getting a book or some web articles that tell you more about the web client/server interaction. If your web provider is helpful they may assist you, otherwise (for the majority of web houses) you might need a little more help from this group. You will almost certainly be tangling with the cgi module soon... regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From samschul at pacbell.net Tue Jul 23 15:32:32 2002 From: samschul at pacbell.net (Sam Schulenburg) Date: 23 Jul 2002 12:32:32 -0700 Subject: Problem with diferences in executinion References: Message-ID: It looks like I have a bad instalation of McMillians Installer. I was waorking OK last week, and This week It has given me problems on files that I had previously used. Sam Schulenburg In article , Sam says... > >In article , >samschul at pacbell.net says... >> >>If I execute the following code snipit from Python it executes the way >>I expected it. If I build a standalone exe with McMillan's installer >>the function call to startscsi() function in MaxPTI's __init__() is >>not in scope. >> >>Maxscsi.py is a file that initializes and loads MaxSCSI.dll which >>contains startscsi(). This DLL and Maxscsi.py have been used in other >>McMillan installer programs without any problems. This is the first >>time I have tried to use a class to instanuate the DLL. The whole idea >>behind this program is the desire to embed Python in an exe with some >>added methods to allow non programmers to write an external script >>file and execute it with the exe with the following call: >> >>"MaxPTI MyTest" >> >>Any Help would be appreciated >>Sam Schulenburg >> >>======================= MaxPTI.py/MaxPTI.exe contains =============== >> >>from Maxscsi import * # import scsi library >>from sys import * >> >>class MaxPTI: >> >> def __init__(self,Headless=0): >> startscsi(1,Headless) # Start scsi initializtion setting >> # Genericflag = 1,and Headless >> initscsi("MaxPTI","physicaldrive",1) # Locate drives >> setshowcdb(0) >> setlogerror(1) >> setpauseonerror(0) >> ..... >> ..... >> def Function1() >> .... >> .... >> >> def Function2() >> .... >> .... >> >>if __name__ == '__main__': >> a = MaxPTI(1) >> exec("from %s import MyScript"%(argv[1])) >> print 'Start Script' >> MyScript(a) >>=================== End MaxPTI.py ============== >> >>================== MyTest.py =================== >>def MyScript(a): >> print a.DeviceTable >> for i in range(a.DeviceTableLength): >> print a.DeviceTable[i] >> print a.DeviceTable[2][a.pSERIALNUM] >> print a.DeviceTable[2][a.pVENDOR] > >It has been requested that I provide a traceback to the above problem. The >following traceback shows that the initial import statment is not being >executed. This differs from what I reported in my first post, where I thought >the problem was in the __init__() method. > >J:\Python22\MaxPTI>MaxPTI MyTest >Traceback (most recent call last): > File "", line 18, in ? > File "iu.py", line 274, in importHook > File "iu.py", line 357, in doimport > File "Maxscsi.py", line 483, in ? > from MaxSCSI import * # Import SCSI libraries > File "iu.py", line 274, in importHook > File "iu.py", line 357, in doimport > File "Maxscsi.py", line 497, in ? > startscsi(GenericOk,Headless) # Set log filename and initialize SCSI >NameError: name 'startscsi' is not defined >J:\Python22\MaxPTI> > >Sam Schulenburg > From huaiyu at gauss.almadan.ibm.com Tue Jul 16 18:14:51 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 16 Jul 2002 22:14:51 +0000 (UTC) Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: holger krekel wrote: >Huaiyu Zhu wrote: >> holger krekel wrote: >> >Huaiyu Zhu wrote: >> >> Readability for machines does not have to come at the expense of readability >> >> for humans. A few years back I experimented with an indentation based data >> >> format that is: >> >> >> >> - as readable as emacs's outline mode >> >> - reduce to common conventions like this paragraph for simple cases >> >> - allow mixed nested structures of set, sequence, dictionary, and seqdict >> >> - can include binary data >> >> - can handle different encodings/encryptions in different elements >> >> - with average less than 5% bloat, in contrast to XML's over 100% bloat >> > >> >do you have any code or design documents for this? >> > >> >Sounds quite interesting. >> >> The basic idea is quite simple: consider a data structure as a tree; denote >> the type of branching at each node; indent the subtrees. It appears to me >> that indentation is easier to handle than quotes and escapes. Here's a >> simple example: >> >> ...snipped... >> >> OK, hope this makes sense. > >It does and it's very interesting. It does sound a lot like >http://yaml.org to me, though (They even have an RFC). >Don't you think YAML might be a superset of your ideas? Thanks a lot for this link. The basic idea is very similar, but apparently they have done a lot more of formal specification than I have ever attempted. There are several differences in the details, so neither is superset of the other. I'll comment on the differences once I have time to read through their docs. >Let me add some random thoughts/questions about your/yaml's scheme >(i hope i am not missing something obvious): Following comments only concern what my scheme does: >- how is a binary data-stream's size determined? What about > open-ended streams? Embedding of arbitrary data-streams > is very useful (IMO). It's determined by the block structure denoted by indentation. >- somehow your and yaml's scheme remind me of todays wiki techniques. > E.g. Wikis have methods of sequence-detection (bullets ...) and they > have a commitment to readability. Of course, they are generally more > concerned with graphical views than with beeing a concise persistence scheme. The emphasis is on using indentation and leading markers to denote structure, in contrast to markups, puctuations, quotes and escapes in the markup languages. >- Is there a canonical conversion between XML and your scheme/YAML? > Shouldn't be too hard, anyway... In principle they both can express anything. In practice I've never tried conversion between my scheme and XML. XML is too complicated in some sense: restriction to texts, white spaces, quotes, tags with names, specs of repeats, etc. I do not know if there is a syntax-free specification of XML data structures. In my scheme, the syntax comes after the abstract structures are specified. Structure marks are never buried in data. >- how do you express external addresses akin XPATH? > Ideas: > - Mappings are easy, just take the 'key'. > - Sequences are easy (take the sequence number) but not very robust > to deletions and insertions of items. > - tag-names (IDs) which can be associated with any item might be interesting. > readability is likely to suffer, probably. An address is not a data structure, but a particular data item. It has no meta-meaning in the scheme. I've experimented with alias nodes, sort of like symbolic links in file systems. I found life is easier without them. I also believe that one's document's meta data is another's plain data. >btw, I wonder whether some form of your and/or YAML's ideas should play a >role in the new persistence-SIG. While the actual persistence mappings >are not in the focus there are certainly some interesting connections >between the two areas. There are facilities for conversion among the data structures: set, seq, dict, seqdict, with various specifications. I do not see how yaml indicates the types of structures. >> If this is still interesting I'll dig the thing >> out. I have documents and code (perl and python) at home, but I'll have to >> ... > >this sure is useful. Especially for me since i work with a (perl-) >friend on a project which needs to address the persistence-question. And >we want to have it interoperable, simple and fast. I guess looking >at YAML might avoid that you have to dig too much into old harddisks :-) Yaml is very interesting. I'd say aobut 60-80% similar to what I did. I'm sure I have stuff that they don't have. I'll dig up my stuff anyway. If anyone is insterested in seeing a mess of code and doc ... :-) I started with bibtex, todo lists, etc, as I had a problem keeping track of my things. Then it drifted and I got distracted and eventually even lose track of this project itself. The hype on XML got me really depressed, as I thought no one would be interested in a direction I regard as fundamentally better than XML. Any new development that can make my life easier is very welcome. Huaiyu From spam at ob_scure.dk Mon Jul 8 17:45:45 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Mon, 08 Jul 2002 23:45:45 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: <3D2A0809.6020106@ob_scure.dk> Michael Hudson wrote: > They don't seem to be online yet, but Tim Couper's slides on "Selling > Python to a Fortune 500 Company" from EuroPython might be interesting > to read. > > They'll appear here: > > http://europython.zope.nl/sessions/presentations/all Page bookmarked, thanks! -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From b.maryniuk at forbis.lt Tue Jul 9 06:18:50 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 12:18:50 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) Message-ID: <200207091218.50549.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 11:56, Boudewijn Rempt wrote: > It's part of the kdebindings module: > http://developer.kde.org/language-bindings/java/index.html AFAIK, QT isn't KDE, right? It actually, *is*, but You can not run KDE so far simply on Winblows or MacOS or somewhere else as You can do this with wxWindows or Tk. And you can not use Java for very small and fast programs (console use) -- it'll start a half of hour... And also not for very-very-very large projects with GUI and other stuff. I've seen no one success project, written on Java. Even all the tools from the Oracle 8i-9i -- they always mostly fails or crashes in the middle of the work (JDeveloper, Oracle Installer, OAS etc). :( -- Sincerely yours, Bogdan M. Maryniuck "...Deep Hack Mode--that mysterious and frightening state of consciousness where Mortal Users fear to tread." (By Matt Welsh) From peter at engcorp.com Wed Jul 24 23:52:29 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Jul 2002 23:52:29 -0400 Subject: Requesting a reference for a book on NNTP References: <30770aa4.0207241752.ace193b@posting.google.com> Message-ID: <3D3F75FD.E9473E42@engcorp.com> TuxTrax wrote: > > Since I know that many programmers both amateur and professional, are > active and lurking, I would like to ask for a reference to a good > *beginners* book on the subject of NNTP and usenet that helps the > inexperienced to understand the information. I've generally found the RFCs themselves to be a pretty understandable description of how these things work. Have you looked, for example, at http://www.ietf.org/rfc/rfc0977.txt and any subsequent revisions that might have been made? They are, after all, the definitive source for such information. -Peter From torppa at polykoira.megabaud.fi Mon Jul 8 18:12:10 2002 From: torppa at polykoira.megabaud.fi (Jarkko Torppa) Date: 8 Jul 2002 15:12:10 -0700 Subject: signal.alarm() for less than one second? References: Message-ID: Jarkko Torppa wrote in message news:... > In article , Andrei Kulakov wrote: > > It looks like signal.alarm takes 1+ seconds as argument. I need > > something lower, like 0.5 second or so. > > Usual way to do input timeouts on unix is to use select. > > there is also setitimer syscall but it does not seem to be > wrapped into anything. I made an extension module for itimer, it has these functions alarm(seconds) -- deliver alarm with subsecond precission setitimer(which,secs,interval) -- setitimer to fire getitimer(which) -- get current value of timer Grab from http://polykoira.megabaud.fi/~torppa/py-itimer/ From rajarshi at presidency.com Wed Jul 17 15:21:42 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 17 Jul 2002 15:21:42 -0400 Subject: expect and python Message-ID: Hi, regarding my earlier post, it seems using Expect is better than fiddling with pipes. Are there and Expect like Python modules out there? TIA, From edream at tds.net Fri Jul 12 11:31:22 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 12 Jul 2002 15:31:22 GMT Subject: Making code 2.1 compatible References: Message-ID: <3D2EF644.256999D1@tds.net> Thanks for the reply Mark, > did you know that 2.2 has been deemed the release targeted for stability by > the pbf? pbf? Is that Guido? Oh, Google tells me it's the Python Business Forum. Ok, so pbf likes 2.2... I'm happy with 2.2. However, having 2.1 code in Leo would make Leo a bit more available to people until everybody changes over. Maybe everyone should just convert to 2.2...And Leo for that matter :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From dyoo at hkn.eecs.berkeley.edu Mon Jul 8 03:55:55 2002 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 8 Jul 2002 00:55:55 -0700 (PDT) Subject: [Tutor] Properties - when and why [using caching] In-Reply-To: <001d01c22610$f0919480$0334fea9@carol> Message-ID: On Sun, 7 Jul 2002, Arthur Siegel wrote: > Say self.W and self.U are each 3 element vectors referenced on > initialization, with attributes x,y, z. V is a calculated vector. V=W-U > > def get_V(self): > return self.W-self.U > > V=properties(get_V) > > But occasionally I need to access V's attributes individually. > > def V_homogenous(self): > return array((V.x,V.y,V.z,1.)) > > Have I not just made three calls to the vector subtraction > of the get_V method? Hi Arthur, Yes, but this actually isn't as bad as one might think. The "refactoring" folks, in fact, recommend something like this, turning attribute access into a method call. I think properties are there to disguise what looks like a simple attribute access with a full-fledged method that we can control. You're right that separate access to V.x, V.y, and V.z will cause Python to call get_V three times, and each time will compute that vector subtraction. But we can fix this! To reduce the cost of computing methods, we can use a cache that saves the last calculation of 'self.W-self.U'. That is, compute it once, and then cache it aside. ### def __init__(self): ## Somewhere within the initializer, let's make our class as being ## "dirty" self._dirty_V = 1 def get_V(self): if self._dirty_V: self._precomputed_V = self.W - self.U self._dirty_V = 0 return self._precomputed_V ### As long as the 'x', 'y', and 'z' attributes don't change, then there's no need to do that expensive vector subtraction again whenever we want 'V'. We should also attach, within each of the set()er property methods, a little switch to make 'V' dirty again. Notice that because get_V() is a method, we can do this optimization without disturbing the user of our class instance. This is a great demonstration of the advantage of properties. Without the use of properties, we can't smuggle this caching code within an attribute access, at least, not without writing really tricky code... *grin* > Could have done: > def get_V(self): > self._V = self.W - self.V > return self._V > > def V_homogenous(self): > return array((self._V.x,self._V.y,self._V.z,1.)) Yes, this is the same idea. We do need to make sure that get_V() gets called before V_homogenous(): otherwise, self._V may not be initialized by then if we're not careful. Hope this helps! From james.kew at btinternet.com Wed Jul 24 07:35:06 2002 From: james.kew at btinternet.com (James Kew) Date: Wed, 24 Jul 2002 12:35:06 +0100 Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: "Alex Martelli" wrote in message news:JCv%8.110249$Jj7.2629802 at news1.tin.it... > > When your __init__ (or any other method) *just* > delegates to the superclass, and nothing else, > simply remove that method's definition from > your class -- inherit it rather than going to > the trouble of overriding just to delegate, > which buys you nothing. I was wondering about this recently: I can see that leaving it out is more efficient, but leaving it in does make the class slightly easier to use: a) clients of the class don't have to wander up the class hierarchy to discover what the __init__ parameters are, and b) writers of subclasses of the class which add their own __init__ don't have to wander up the class hierarchy to discover which superclass to call __init__ on and what parameters to pass. I suspect the proper Pythonic answer to both is "document, don't code"? James From aleax at aleax.it Sat Jul 20 13:33:22 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 19:33:22 +0200 Subject: Funny behaviour of MySQLdb In-Reply-To: <15673.23606.257022.388489@localhost.localdomain> References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> <15673.23606.257022.388489@localhost.localdomain> Message-ID: On Saturday 20 July 2002 02:48 pm, Skip Montanaro wrote: > >> I just tried the single-threaded way, and that works... Hmm... > >> Nothing apparently different, except that I took out the base class > >> SocketServer.ThreadingMixIn from the definition of the server > >> class... > > Alex> Rule of thumb: always ensure a single thread interacts with any > Alex> given external entity, be it a file, a database, the user, or > even Alex> a global shared variable subject to updates. > > Hmmm... I'm not discounting your rule of thumb, but I use MySQL from a > multi-threaded application with no problems (at least no problems of which > I am aware). I maintain a pool of (currently five) connection objects in a > Queue. Each thread which needs to chat with the database calls .get(), > creates a cursor, chats, then returns the connection to the Queue. Guess > I'll have to go back and reread the MySQL docs and refine my stress tests. If MySQLdb.threadsafety >= 2, and there are no errors in your implementation (and you being quite a good programmer, I'd bet there probably aren't), you're supposed to be safe. If each "chat" is complicated enough and can't easily be encapsulated as a callable, you may even have some advantage wrt the architecture I'd consider even safer -- five dedicated threads, one per connection, all waiting for work requests on a single queue and returning results on a separate queue per requestor thread: you're saving a few resources by having 5 fewer threads and many fewer Queues around. But the moment problems should start appearing, good luck. You know as well as I do that there's no bug so deucedly hard to reproduce, and thus fix, as one due to multiprogramming (threading or otherwise) with all related issues. That's a good part of why I avoid multiprogramming when I can avoid it and wear braces AND a belt when I can't. Alex From mwh at python.net Fri Jul 12 05:31:51 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 12 Jul 2002 09:31:51 GMT Subject: try..catch..finally? References: <3D2DEEEA.9030702@NOSPAMREMOVETHISxs4all.nl> Message-ID: Irmen de Jong writes: > Mark McEahern wrote: > > not that i knew this from first hand experience--that's what google's for > > --but python did have a try-except-finally before the 1.0 release. > > you can read all about it here: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=3967d908.363887342%4 > > 0news.online.no > > // m > > Heh, I didn't know. I've boarded the ship at release 1.2 :-) > So I guess the answer to my question is AMBIGUITY. > A separate try..finally around the other try block is unambiguous, > in contrast to the try..catch..finally construct. Yeah, just get used to functions that start try: try: try: I have (see some functions in python_reader.py from pyrepl for examples). Cheers, M. -- please realize that the Common Lisp community is more than 40 years old. collectively, the community has already been where every clueless newbie will be going for the next three years. so relax, please. -- Erik Naggum, comp.lang.lisp From just at xs4all.nl Wed Jul 17 05:05:00 2002 From: just at xs4all.nl (Just) Date: Wed, 17 Jul 2002 11:05:00 +0200 Subject: Any Python distribution solutions for Mac? References: <080720021958161862%rodneys@nospam.io.com> <20020716140415308+0200@news.t-online.de> <170720020104082917%rodneys@nospam.io.com> Message-ID: In article <170720020104082917%rodneys at nospam.io.com>, Rodney Somerstein wrote: > Thanks for the response, Dinu. I was beginning to doubt that any Mac > users actually read this group. I have had one other response which was > just a me-too. Most Mac people hang out at the pythonmac-sig: http://mail.python.org/mailman/listinfo/pythonmac-sig There's also BuildApplication, which is not unlike py2exe, but currently it's only supported for MacPython, not MachoPython. Just From scrutinizer at gmx.at Thu Jul 25 16:54:43 2002 From: scrutinizer at gmx.at (Francesco S.) Date: Thu, 25 Jul 2002 20:54:43 GMT Subject: Which gui for slow (133 Mhz) pc References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> <3d42f3dc.5866543@news.utanet.at> Message-ID: <3d42636b.4941993@news.utanet.at> On Wed, 24 Jul 2002 17:41:40 -0400, Michael Gilfix wrote: >On Wed, Jul 24 @ 18:38, Francesco S. wrote: >> Following another thread, Qt seems to be also a very interesting >> alternative, I don't know now, if I should spend some time to examine >> the pyqt libraries, but this is another story, I think ... > Hello Michael, > GUI stuff always comes down to your needs really. But pretty much >all the toolkits out there can accomplish the same thing, and at >roughly the same speed (which is pretty decent to being with) for most >applications. I don't want to write "applications" now, at first I want to learn and maybe write some tiny utilities for myself and play around. >Wat you might want to ask yourself is: how portable >does my application need to be (do I want *nix and windows support, >for example) and do I need threading? That's when it can get a little >iffier and in that case, I've found wxPython to be best. > > -- Mike Hm, again, the three alternatives: Porbable is not the question now. Please correct me, if I'm wrong. 1) Tkinter: It is in startup time pretty good, and well documented , stable and straightforward. 2) wxPython is fast (after starting) and has many sophisticated widgets. 3) PyQt: It is "professional" and powerful and is praised from the most people here in this newsgroup. -- Francesco From jonathan at onegoodidea.com Tue Jul 16 11:55:27 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 16 Jul 2002 16:55:27 +0100 Subject: map del efficiency python2.2 and 2.1 References: Message-ID: On 16/7/2002 16:08, in article m28z4bn227.fsf at mother.paradise.lost, "John Hunter" wrote: > In the process of profiling, however, I found something surprising. > Most of the total execution time of the code is spent clearing the map > from memory, after all the lines in my script have executed (ie, the > equivalent of calling __del__ on a dictionary type. In python 2.1, > here is a typical execution time profile > > time to read file as string and split into seq: 1.000s > time to create map: 2.960s > total execution time: 9.87s > > 5.9s of the total runtime occurred *after* all the lines of my code > had executed. Since my program does nothing after reading the map, I > assume most of this time is spent freeing the map. If I comment out > the part of my program that creates the map, I do not have that long > delay at the end of the script. I don't think you're reading these statistics correctly. Looking at the output you include: > #cruncher1:~/dict/test> time python2.1 test_allwords.py > #seq has 1712676 items; elapsed time is 1.000 > #map has 856338 keys; time to load map is 2.960 > #4.400u 0.480s 0:09.87 49.4% 0+0k 0+0io 298pf+0w The numbers along the bottom line (as returned by time) represent: the user-space seconds spent on the CPU, the kernel-space seconds spent on the CPU, the actual "wallclock" runtime of the process, and thus the percentage of the runtime that it was actually on the CPU (as opposed to waiting for I/O, VM, or pre-empted by some other process). These numbers seem pretty consistent: 4.4 + 0.48 = 4.88 secs spent on the CPU. You account for this as 1.000 secs for the load of the sequence and 2.960 secs on the map creation, which leaves only 0.920 secs spent initialising and tearing down the Python interpreter. > Finally, this time is dramatically longer in python 2.2. Here are > typical runtimes in 2.2 I think there is something bogus with your 2.2 install. Even reading the numbers correctly they still leave 10 secs of CPU time unaccounted for and you'd definitely notice the Python interpreter wasting that much time starting and stopping. Ignoring the numbers, how does the program actually seem to you? With the runtime in the region of 10 to 27 seconds you should be able to gauge where the time is going by just counting in your head as it runs. Does it look like it's spending many seconds finishing up? I modified your script to explicitly delete 's', 'seq', and 'm' and time this. On my (twice as slow) machine it took 2/3rds of a CPU second to deallocate all three. Jonathan From codeapocalypse at msn.com Tue Jul 9 11:49:29 2002 From: codeapocalypse at msn.com (Brian) Date: 9 Jul 2002 08:49:29 -0700 Subject: How can I retrieve the ID of the last record I added? References: Message-ID: Sandeep, Within the transaction, after your insert, perform a SELECT @@IDENTITY. This should return the value for which you're looking. From jb at cascade-sys.com Fri Jul 26 23:12:52 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 26 Jul 2002 20:12:52 -0700 Subject: Numeric data question References: <_y709.121243$Jj7.2823038@news1.tin.it> Message-ID: <3D420FB4.527F3D93@cascade-sys.com> Alex Martelli wrote: > Not a problem any more since Jan 1. Sad to think of an Italy without Lira -- the distinctive currency was part of the charm. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From boud at valdyas.org Fri Jul 5 16:24:19 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Fri, 05 Jul 2002 22:24:19 +0200 Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: <3d260494$0$12308$e4fe514c@dreader4.news.xs4all.nl> Alex Martelli wrote: > So here's approach 2 in a clear, multistatement way: > > auxdict = {} > for name,count in myDict.iteritems(): > auxdict.setdefault(count, []).append(name) > for key in range(min(auxdict.keys()), max(auxdict.keys())+1): > for name in auxdict.get(key, []): > print key, name > I really should read the documentation for each new release... I had completely missed the arrival of 'setdefault'. Probably means that I'm stuck in the 1.5.2 ages or something :-(. -- Boudewijn Rempt | http://www.valdyas.org From peter at engcorp.com Mon Jul 22 19:53:29 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 19:53:29 -0400 Subject: Alex Martelli is off the net for a few days :-( References: <200207221011.g6MABTVa009663@ratthing-b246.strakt.com> Message-ID: <3D3C9AF9.BB6D1AC7@engcorp.com> Gerhard Haering wrote: > > * Laura Creighton [2002-07-22 12:11 +0200]: > > Some construction workers have severed his phone and internet lines. > > Expect him back in a few days, not a few hours. :-( > > Laura, don't lie. I saw you sneek in at night to cut off his cables in order to > make him work productively again ;-) Ouch! Is "cut off his cables" a euphemism for something very painful? It sure sounds bad... does this make him the martelli-bobbit instead of the martelli-bot? And do they ever grow back? From tdelaney at avaya.com Mon Jul 15 19:43:39 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 16 Jul 2002 09:43:39 +1000 Subject: isA function? Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > "Delaney, Timothy" wrote: > > > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > > > have the right signature is inadequate in this > circumstance, though > > > it may be acceptable for you when doing traditional unit testing, > > > writing tests after the fact. > As for indirect insult -- I don't understand why you think > that, unless > you find "traditional" insulting -- but in any case I didn't mean > it to be insulting, indirect or otherwise. Apparently my > writing style > frequently causes people to think that (apart from the times when I > *do* intend to insult), for which I apologize. I'm trying to improve. The statement came across as "it's obvious that you write your unit tests after your code" - and coming from such a staunt promoter of writing unit tests before coding this comes across as an insult. If you didn't intend it to be, I apologise. The "incorrect" bit was referring to this particular bit (that I write unit tests after the code) and was addressed in my next statement (including an admission that it's impossible to completely write unit tests before the code in Java ...). Anyway, bygones until the next misunderstanding ;) I admit i was perhaps a little strong before and didn't quite get the case you were presenting (I realised with the next email as you observed). There are cases for type tests in unit tests, but they should be extremely localised. Tim Delaney From grumble at lycos.com Tue Jul 16 17:41:01 2002 From: grumble at lycos.com (jcm) Date: 16 Jul 2002 21:41:01 GMT Subject: Dictionaries References: Message-ID: Dictionaries are unordered. Maybe "dictionary" is a misleading term, since dictionaries (the books) are in alphabetical order. "map" might be a better way of thinking of them. The order entries in a dictionary are printed is basically arbitrary. Marcus Vinicius Laranjeira wrote: > Hi folks, > I got a big doubt... how python manages data in dictionaries ? for example: > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> dic = { 'R1': 1} > >>> dic > {'R1': 1} > >>> dic['R2'] = 3 > >>> dic > {'R1': 1, 'R2': 3} > >>> dic['R4'] = 2 > >>> dic > {'R4': 2, 'R1': 1, 'R2': 3} > >>> > I created a dictionary with one key 'R1' and a value of 1. Then, I inserted > a new item with a key 'R2' and a value of 3... It worked like I though it > would: appended the new item at the end of the dictionary. > But why when I insert a new item with a key 'R4' and a value of 2 it > inserts it in the begining of the dictionary ???????? > How can I change the order of the items in a dictionary !?!?!? > Thanks a lot, > Marcus From eric.brunel at pragmadev.com Mon Jul 29 07:36:37 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 29 Jul 2002 11:36:37 +0000 Subject: Size in byte of a string ? References: Message-ID: Shagshag13 wrote: > [sorry for the previous incomplete post] > > hello, > > i had the following problem : i had huge files > 1,5 go. each of theses > files contain some other small files and they are separate by a header. i > need to do some kind of random access to the small files so i wish to > write a script which would build some kind of a table of content for > theses huges files. > > i would like to have something like > samllfile_header_name_i : start_at_byte : end_at_byte > > and i will do : > f.seek(start_at_byte) > samllfile_header_name_content = f.read(end_at_byte) > > but to do this i need to be able at the building time to know how much > bytes take a string ? Eeeer, len(string).... But you should open your huge file as binary, not text: f = open(fileName, 'rb') so that everything in the file will be kept untouched. With this, you will actually get '\r\n' at the end of each line instead of a single '\n' HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From tjreedy at udel.edu Sat Jul 27 13:39:06 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Jul 2002 17:39:06 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> Message-ID: <_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> "Tim Gahnstr?m /Bladerman" wrote in message news:R5x09.17790$p56.5752496 at newsb.telia.net... > I want to make all variables mutable. In a real sense, Python does not have variables. It has objects, each of which has 1 or more named or unnamed references thereunto. Which do *you* think of as variables: objects, references, or names? If objects, you should look to another language since immutability of certain types of objects is an integral part of Python (the operation of dicts, for instance.) I believe most people think of variables as names, which works best (fewest surprises) within the Python data model when bound to immutable data types. For example: x = 2 ... y = x ... (many lines) x = x*x # what should now be the value of y? 2 or 4? # immutability of ints guarantees 2, which is what most people expect > When you want to make functions like inc(x) where inc is supposed to > increase the value of x by one. How is that done in Python? You 'mutate' names most easily by rebinding them to a new value with the binding (assignment) operator '=' as in 'x = x+1', 'x+=1', or even x=inc(x)'. With work, you could make inc('x') work for global var x by fiddling with the globals dict (but this cannot be done for local function vars). Note that in C, you would also have to 'quote' x, though with the '&' operator, as in inc(&x). > That is my view of CBR, maybe that is not the correct definition . To me, call by reference means that the function gets a reference to the actual argument instead of an anonymous copy. However, for Python immutables, the effect is the same, except for avoiding the creation and usual destruction of the copy. > and I don't need CBR If you work with instead of fighting the Python data model, you can probably do what you want without completely reworking the interpreter. Terry J. Reedy From richie at entrian.com Thu Jul 4 06:13:09 2002 From: richie at entrian.com (Richie) Date: Thu, 04 Jul 2002 11:13:09 +0100 Subject: Web templating/db tool with best designer/coder separation? References: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> <4s76iu4vfbprgirk01oe1c9ejvhsepcj6d@4ax.com> Message-ID: > > The biggest problem I can see is that I'm using object attributes to > > represent both HTML tag attributes and child objects. > > I don't think this really is a big problem. I think I agree. The purist in me wants the two to be unambiguously separated, but the pragmatist wants a simple API that lends itself to intuitive code. > I don't (yet) see the advantage of having different classes mirroring > the different HTML tags. Only that certain tags could behave in friendly ways; the Input class could know that its 'size' attribute is an integer, and return an integer for its value rather than a string, for instance. It's not necessary, and could be too much black magic. > Is there really a need for a DOM-like access where each tag and sub-tag > of interest has to be tree-like identified? No, not at all - the hierarchy would only include things with 'id' or 'name' attributes, so if you only needed to replace one thing you'd only give that thing an 'id' attribute and it would be at the top of hierarchy. If you do *need* a deep hierarchy, there's no reason you can't shortcut straight to one element, as long its name is unambiguous: >>> page = Template.Page( complicatedHtml ) >>> page.topsection.userinfo.loginform.username == page.getElement( 'username' ) True Your "forest of sparse subtrees" idea (nice phrase!) is no problem. > In a perfect world, we had even two layers of template substitutions: A > 'low-level' one based one a Python API (like yours above), and a higher > level one that specifies the substitutions in a more condensed way, > (a little context-specific, mayve Quixote-like language). I'm only really interested in what you call a low-level interface - two languages, HTML and Python, are enough for me! But I think the low-level interface should work with any other interface - after all, it just takes HTML, manipulates it, and outputs HTML. There's no reason why the HTML couldn't have come out of Quixote. -- Richie Hindle richie at entrian.com From unlearned at DELETETHIS.learn2think.org Tue Jul 30 09:36:09 2002 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Tue, 30 Jul 2002 07:36:09 -0600 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> Message-ID: <3d46964b$1_2@hpb10302.boi.hp.com> "John Roth" wrote in message news:ukb31ell2rh643 at news.supernews.com... > for word in 'fee fie fo fum'.split(): > Button(frame, command = def (): > print word > ) > > This isn't really the world's best example, because IMO, the > lambda form is easier to read for something this small. However, > it does give the guts of the idea: > 2. The remainder of the syntax exactly models def, including > statement indentation within the expression. Notice that the > first statement in the anonamous function has to be indented > two from the preceeding line, because the continuation of > the expression has to still be indented from the line with the > 'def', and dedented from the statements. IIRC, there's no such ting as "indenting two" in Python as the size of an indentation is automatically detected as you go along, making the following indentation style valid (although no one would ever want to do it): toplevel secondlevel thirdlevel secondlevel thirdlevel fourthlevel secondlevel toplevel -- Daniel Fackrell (unlearned at learn2think.org) When we attempt the impossible, we can experience true growth. From fredrik at pythonware.com Thu Jul 4 11:25:00 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Jul 2002 15:25:00 GMT Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> <3D245020.5030007@mxm.dk> Message-ID: Max M wrote: > # the basic sort > sortedList = [(key, theDict[key]) for key in theDict.keys()] > sortedList.sort() if the dictionary is mapping words to counts, I assume you meant: sortedList = [(theDict[word], word) for word in theDict.keys()] which can also be written sortedList = [(count, word) for word, count in theDict.items()] or in more recent versions: sortedList = [(theDict[word], word) for word in theDict] or sortedList = [(count, word) for word, count in theDict.iteritems()] (etc) From whisper at oz.net Fri Jul 12 16:17:56 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 12 Jul 2002 13:17:56 -0700 Subject: Is count supposed to still work? Message-ID: Whether or not you explicitly import string, count(mystring, substring) isn't working ("NameError: global name 'count' is not defined") (N.B. this statement is in a method of a class), but mystring.count(substring) does. However, count is not listed as deprecated in the python 2.2.1 doc. Even deprecated, it should still work. FWIW, I wish none of these where deprecated. Maybe it's incorrect, but I tend to think of an attribute of something, not something's attribute. Both ways are useful IMO. Sometimes len|count|int|float(thing) is nice and sometimes thing.len|count|int|float() works better. Not a different way to do something, a different way to express the same thing. David LeBlanc Seattle, WA USA From aleax at aleax.it Sat Jul 20 15:59:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 19:59:53 GMT Subject: A better self References: Message-ID: brueckd at tbye.com wrote: ... >> > 6) Have Python generate the function bodies for you, e.g: >> > >> > class SomeClass: >> > method = MyCoolUnboundMethodMaker('arg:x = y*z + t*arg') >> >> Hmmm...what's that? > > Just an idea - since Python is so dynamic, instead of writing the > function you write a string describing the function and have another > function read it and generate a method that does all the 'self.' stuff. > Obviously you'd have to think it through some, but this is definitely > possible. > > In the above example, I assume MyCoolUnboundMethodMaker would read > the string, and use it to generate a string like this: > > '''def NewMethod(self, arg): > self.x = self.y * self.z + self.t * arg > ''' > > after which it would exec the string and then do a 'return NewMethod', and > bingo, your class now has a method that performs that operation. It'd take > some work to get it right the first time, but from then on you could reuse > it for all your numeric work. Indeed, code generation is not a bad idea. However, I think I would take a different approach to it, based on hacking bytecode in a metaclass rather than generating and compiling source. It's just py-in-the-sky musing, but -- imagine being able to code, e.g.: class Myself(Selfer): __slots__ = 'x y z'.split() def __init__(ax, ay, az): x, y, z = ax, ay, az def compute(): return x**y/z and have type(Selfer), e.g. SelferMeta, tweak the code so it's just as if you had put self in all the needed places. It should be feasible (with the obvious limitations -- all the slot names become reserved as variable names and you can't use them for any argument, global, local, etc). The point is that SelferMeta.__new__ gets to look at all of class Myself's dictionary *and tamper with it as needed* before delegating the rest to class type. Specifically, it would get to look at the various methods, already compiled down to bytecode... and change the bytecode as needed, i.e., each of the various LOAD_GLOBAL, STORE_FAST, LOAD_FAST, would be checked to see if the name it refers to is in __slots__, and, if so, transformed into LOAD_FAST+LOAD_ATTR, or LOAD_FAST+ STORE_ATTR. Of course, all the arguments of the various JUMP_* operators would have to be adjusted as the code's length changes. Hmmm, would you want to allow calling methods by bare-name, too, or would self.name() be still required there? No matter -- it's your language, design it as you wish, of course. Implementation is pretty obvious anyway. Oh I was almost forgetting -- insert a first argument named 'self' if not already present, and then change any LOAD_GLOBAL for 'self' to LOAD_FAST instead, of course. Sounds like about a week's worth of serious hacking, and all in Python -- no C needed. Me, I like 'self' -- but, as you see, those who dislike it have only a modest effort to spend to make it optional in their own classes. Not right now (I should be writing the Nutshell, darn, NOT reading and writing on c.l.py...!!!), but when the Nutshell's done I'll be available for only moderately outrageous hourly rates (Strakt only takes 40 hours a week of my time, as Agile development principles dictate), and I'm quite willing to make a fixed price bid for this if we can nail down the specs to something easy to implement this way. I'm sure lots more people who are comfortable hacking on bytecode will also be happy to bid (assuming every self-hater is unable or unwilling to dirty his or her hands with this approach). The point is: custom metaclasses allow you to do a LOT of things more productively than by whining on c.l.py. Not all, by a long shot, since a class with a custom meta must still be syntactically valid Python (what you can't express that way you must hack into docstrings, or via naming-conventions, and the like). But a heck of a *LOT*. So why not 'import dis' and start studying bytecode on small examples, and how you could hack on it? DIY is cheaper and more fun -- and you're sure to learn a lot even if you end up throwing the results away!-) Alex From gerhard.haering at gmx.de Wed Jul 17 18:36:04 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 00:36:04 +0200 Subject: Sharp Zaurus In-Reply-To: <1026919964.826307@irys.nyx.net> References: <1026919964.826307@irys.nyx.net> Message-ID: <20020717223604.GA775@lilith.my-fqdn.de> * sarayu balu [2002-07-17 09:32 -0600]: > Hi, > Is there any Python, more appropriately Jython, for this PDA ? Yes. > Is Jython Open Source ? Yes. Google (http://www.google.com/search?q=python+sharp+zaurus), second hit: http://www.riverbankcomputing.co.uk/zaurus/index.php I'm using that package on my iPAQ, too. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From shagshag13 at yahoo.fr Fri Jul 19 08:38:37 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 19 Jul 2002 14:38:37 +0200 Subject: file ops on the fly ? References: <21TZ8.101254$vm5.3505549@news2.tin.it> Message-ID: "Alex Martelli" a ?crit dans le message de news: 21TZ8.101254$vm5.3505549 at news2.tin.it... > Shagshag13 wrote: > > > hello, > > > > is it possible (and how) to do "on the fly" reading and updating on file ? > > You can open a file for 'r+b' and then call both read and write on it, > moving around with seek and possibly tell. This is hardly ever useful > on a text file, though. But I guess much depends on what you mean by > "on the fly" in this context -- maybe the simulation of inplace edits > for text files offered by standard module fileinput is all you need? thanks, i'm going to look at fileinput... ans yes i'm working on big file (>1go). From a sequential reading (line by line) i need to do line insertion and/or line deletion in my file. And i don't wish to create a new (wasting place) file. s13. From see_reply_address at something.invalid Tue Jul 16 23:45:24 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 17 Jul 2002 15:45:24 +1200 Subject: inheriting from C types References: <878dc260.0207161005.6fec78ec@posting.google.com> Message-ID: <3D34E854.8020200@something.invalid> Martin v. Loewis wrote: > > What is k.__mro__? I believe it stands for Method Resolution Order, and it contains a flattened list of all the base classes, in the order they should be searched for methods. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From johnboik at sbcglobal.net Wed Jul 3 14:37:19 2002 From: johnboik at sbcglobal.net (John Boik) Date: Wed, 03 Jul 2002 18:37:19 GMT Subject: newbie question on PATH vaiable and running python on win xp Message-ID: Hi: I would like to be able to run python from the command line from any directory. Right now I can only run it from the Python22 directory. I tried putting the Python22 directory in the windows PATH variable, but still python only would run if I was in the Python22 directory. I also tried putting Python22\python.exe in the PATH variable, but that did not help either. Any solutions to this? Thanks. John From fredrik at pythonware.com Wed Jul 24 21:00:26 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Jul 2002 01:00:26 GMT Subject: Tk Dynamic Menus problem References: <_mH%8.156269$uw.92148@rwcrnsc51.ops.asp.att.net> Message-ID: Jeremy Bowers wrote: > > I'm not exactly sure why it's printing '3', but you do have a scoping > > problem there. > > Replace 'lambda: printFunc(i)' with 'lambda i=i: printFunc(i)'. Supplying i > > as a keyword arg for the lambda brings i into the labmda's scope. > > Thanks, that did it. > > I would be interested in a bit more explanation though. In the "real" > application, "i" were instances, not numbers (if that matters). Why would > the 'i' in the previously created lambda commands "shift" to follow the > outside value of i? in your original code, your lambda contained a reference to the name "i" in an outer scope. when the lambda was called, it would fetch the *current* value of "i" from that scope (that is, the last value that the variable had before you returned from the function). in contrast, the "i=i" pydiom binds the *value* of the outer "i" to a local lambda variable with the same name. if you re- bind the outer "i", the local variable still points to the same value. From kristian.ovaska at helsinki.fi Tue Jul 30 04:06:17 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Tue, 30 Jul 2002 11:06:17 +0300 Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com><_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: "Tim Gahnstr?m /Bladerman" : >The thesis is not about making a CBR language but make an IDE with debugger >for a language suited for novices. Well, you've got the right language. I think Python is one of the easiest languages to learn. It's precessor, ABC, was actually designed to be a teaching language, I think. I have switched to using Python (in a slighty pseudoish way) as my pseudo language, and people can read it fine even if they've never seen Python code before. Someone has said, "Python is it for imperative languages", and I have to agree. Like many programmers, I used to dream about designing my own (imperative) language, but now I have to admit that my dream language would look too much like Python to be designed. Damn Python! -- Kristian Ovaska From aleax at aleax.it Wed Jul 24 08:19:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 12:19:08 GMT Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> Message-ID: <0Xw%8.110704$Jj7.2636718@news1.tin.it> Keith S. wrote: > I am writing a small application that has a command line > for entering Python commands, and a message window to show > the Python output. > > I've used PyRun_SimpleString(cmd) to execute the command > typed in the command line, and this works fine for simple > statements e.g. print 'hello', but for more complex > expressions e.g a for loop I get an 'Unexpected EOF while > parsing' syntax error. > > I'm probably missing something obvious here, but I can't > see it - any ideas? You may have forgotten to conclude the string with a '\n', which is typically needed from the point of view of Python's syntax (for "dedent"...). If it's not that, I don't know -- not seeing any examples, it's too hard to keep guessing. Alex From claird at starbase.neosoft.com Tue Jul 9 14:29:34 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 9 Jul 2002 13:29:34 -0500 Subject: expect module and/or functionality? Or SSH wrapper module? References: Message-ID: In article , cqx wrote: > >Is there a more up-to-date expect-like module than >the ExpectPy-1.9b1 package available on SourceForge? > >I'm actually more interested in a pure python expect module if >possible. I mostly need it as an interface to 'ssh'. . . . This is a poorly-documented topic. You need this as an interface to ssh. That's good to know. Are you certain you must use passwords or passphrases in your application? Can you not rely entirely on stored keys? If you can, your requirement for Expect-like capabilities goes away. If not, no, you can't Expect with pure Python; there's no practical way to get the pseudoterminal munging right without calls into the C run-time library that Python itself can't access. I'm working on techniques to use standard distribution instal- lations of (Tcl-based) Expect and (pure) Python to achieve general results. The idea is that many hosts--essentially all Linuxes, for example--are already equipped with these executables, so all you'd need to install are your pure-Python scripts. I don't have these ready yet, though. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From zopestoller at thomas-guettler.de Thu Jul 25 11:44:53 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Jul 2002 17:44:53 +0200 Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> <34R%8.138298$vm5.4494921@news2.tin.it> <3D3FFC94.60108@thomas-guettler.de> <3D4005CD.4060404@thomas-guettler.de> <3d400710.533379375@news.skynet.be> Message-ID: <3D401CF5.4030904@thomas-guettler.de> henk_derudder at hotmail.com wrote: > On Thu, 25 Jul 2002 16:06:05 +0200, Thomas Guettler > wrote: > > >>Alex Martelli wrote: >> >> >>>Thomas Guettler wrote: >>> ... >>> >>> >>>>>Many Python functions expect to get arguments of specific types >>>>>(or polymorphic to such types, i.e., supplying all necessary >>>>>methods and operations with equal signatures). >>>>> >>>>>Having them accept arguments of wrong types, with silent coercion, >>>>>would hurt all careful developers, by hiding bugs. >>>>> >>>>> >>>>I agree, but than the exception should have a better message: >>>> >>>> >>>Should it? Maybe I should have written than types supplying all >>>necessary methods and operations with equal signatures are OK >>>too. >>> >> >>Dont't take this to serious, I just wanted to know >>what other people think >> > > Alex does not take it too serious. He is trying to explain how Python > works and should work at its fundaments. The more one understands this > the better one can program in Python. Just take his explanation for > very granted :-) I know how python works. But I know how newbies think, too. I know what's wrong if I see this stacktrace, newbies might not. I like python because it is much more newbie-friendly than perl or java. thomas From ld at nospam.com Fri Jul 5 20:14:36 2002 From: ld at nospam.com (Larry) Date: Sat, 06 Jul 2002 00:14:36 GMT Subject: Client sockets without os.fork() Message-ID: When a client connects in unix/linux, I could simply use the os.fork() to create a nice new process to deal with the newly requested session. I now have a need to do this in windows. Can anyone relay a fairly easy way to put the newly created socket into it's own thread so that it can go about doing it's business while the orginal daemon can sit and listen for new connections? Thanks, Larry From david.levy at xrce.xerox.com Tue Jul 23 08:27:40 2002 From: david.levy at xrce.xerox.com (David Levy) Date: Tue, 23 Jul 2002 14:27:40 +0200 Subject: Python UDDI implementation References: <3D3C104D.1EDB2D48@xrce.xerox.com> <915a998f.0207220933.44a332ef@posting.google.com> <3D3D071F.BADCBD13@xrce.xerox.com> <6E449FA9D58D737A.5DF5F4A9FA118F2D.539821FD244E28D6@lp.airnews.net> Message-ID: <3D3D4BBC.D4A650CF@xrce.xerox.com> thanks !! no python implementation on the way ? !! my boss don't like *Java* hihi Cameron Laird wrote: > In article <3D3D071F.BADCBD13 at xrce.xerox.com>, > David Levy wrote: > >Thanks > >I know, this library was released last week > >However, it is just an interface, not the repository itself ! > >There are few ones available : jUDDI, .net, IBM's one, but no one in > >Python or else I think ... > > > >I need the server side ;) > . > . > . > Yet another Java-based one (Tomcat, in fact) appears at http://freshmeat.net/projects/soapuddi/?topic_id=250 >. > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://starbase.neosoft.com/~claird/home.html -- _____________________________________________________________ David Levy Xerox Research Centre Europe 6, ch. de Maupertuis F - 38240 Meylan Email david.levy at xrce.xerox.com http://www.xrce.xerox.com From pinard at iro.umontreal.ca Sat Jul 13 09:50:06 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 13 Jul 2002 09:50:06 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: References: Message-ID: [Jonathan Hogg] > To summarise the advantages of using XML as I see them: > * Standardised parsing (PyXML etc.) > * Standardised validation (DTDs, XSchema) > * Standardised editing (XML-aware editors) > * Standardised querying (XPath, XQuery) > * Standardised transformation (XSLT) > * Standardised storage (XML:DB) This is no more advantage being `XML-standardised' for the only sake of being `XML-standardised' than going `XML' for the only sake of going `XML'. In the table above, `standardised' like a buzzword. As a Python lover, I'm tempted to replace `standardised' by `easy' and `legible' wherever I can. For simple system tables, like the one that was given as example previously in this thread, I quite doubt the Linux kernel will soon go to the lengths of XML parsing, querying, and database storage. > I really am willing to eat humble pie here and admit that I'm mistaken if > someone can give me a similar list of good reasons to *not* use XML for > off-line hierarchically structured data. Any file is a hierarchy of some sort. We often see a file being a sequence of lines, a line being a sequence of fields or tokens, and tokens being a sequence of characters. In many, many, really many applications, this organisation in lines and fields is wholly satisfactory. Reusing the enumeration above, it is easy to parse, easy to validate, easy to edit, easy to query, easy to transform and easy to store. Let's be honest. People are comfortable with lines and fields, examples and tools merely _abound_. XML becomes more sensible when you have a _lot_ of structure, something which is complex, difficult, and which you have to exchange with away parties. For simple things, it is just annoying and heavy overkill, really... Speaking for my own situation only, as a Python lover, XML is gross overkill even for quite complex things. It is extremely simple to pickle rather complex structures, transmit them over wires to applications on other machines, and unpickle them there. Using Python as an API for such usages is natural and very comfortable, and not to say, immensely faster than XML. Of course, I would prefer XML is I had to speak outside a Python environment, with people offering nothing simpler than an XML interfaces. I've looked into some of these fashioned avenues. So far, they invariably seem extremely complex and hairy to me, at least for what they provide. XML is there to give users a reinsurance on the fact they have a last-resort control, after all, to inspect what is going on, or to intervene if they ever need to. So, for them, I really understand how valuable XML may be. It's a good thing. In my simple situations, Python is much, much better than XML as a solution. Moreover, Python offers me a good set of XML tools and interfaces if I have no choice than communicate with an outside world groking XML! For one, when I really need a marking language for my users, without having XML imposed from the outside, SGML is often a better solution, as it is closer to humans than XML. There might also be better solutions than SGML, too. XML is mainly there to help implementors. Surely, I like humans far more than I like machines, and this feeling mainly drives my efforts. :-) > Perhaps I'm missing something blindingly obvious here, but what benefits > would I gain from coming up with my own format? For simple things? Ease, speed, simplicity, readability. Don't fear it. The world will survive, you know, even if you sometimes don't use XML. :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mgerrans at mindspring.com Wed Jul 10 01:30:16 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 9 Jul 2002 22:30:16 -0700 Subject: A better self References: Message-ID: > I have no problem with "self" (or whatever) being equivelent to a leading > '.', but '..' would be confused with "up directory" syntax of U*x - although > it's tempting to suggest it as an alternative for global . In keeping with that concept, '..' would be referring to the base class (equivalent to java's "super"). Or would that be mixing metaphors? (in Ruby, mixin metaphors). From graumann at clyde.caltech.edu Fri Jul 19 14:07:20 2002 From: graumann at clyde.caltech.edu (Johannes Graumann) Date: 19 Jul 2002 18:07:20 GMT Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: Chris Liechti wrote: > Johannes Graumann wrote in > news:ah9cvk$st at gap.cco.caltech.edu: >> Basicely I have two lists, one containing the future string-names >> and one containing the values I want to give them. The order is >> identical in both. Right now I'm solving this by a dictionary, but >> I would really prefer to have straight strings as a result of my >> operation. > i think i don't understand what you exactly want... maybe you could > illustrate you problem with an example of data and how the result should > look like or a few lines from the interactive prompt, like: Sure! Here is what I wrote: def listreadout(list): if len(list) != (len(otherlist)): print '\n\t%d element(s) given, but %d reqired by listreadout!' % (len(otherlist), len(list)) meckerei()#sys.exit() and some more complaints in here ... global lexicon lexicon = {} for index in range(len(list)): lexicon[list[index]] = otherlist[index] Could be made much more elegant with what Chris gave me ... ;0) >>>> names = ["one", "two", "tree"] >>>> values = [1,2,3] >>>> dict(zip(names,values)) > {'tree': 3, 'two': 2, 'one': 1} BUT: what I really want is (in therms of Chris's example): >>>names = ["one","two","three"] >>>values = [ 1,2,3] --> DO SOMETHING HERE >>>print one 1 Joh -- From brueckd at tbye.com Mon Jul 1 00:46:40 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sun, 30 Jun 2002 21:46:40 -0700 (PDT) Subject: I'd give up Perl tomorrow if only... In-Reply-To: Message-ID: On 30 Jun 2002, Aahz wrote: > >I suggest that you be a Perl programmer for a while, and see what having > >CPAN accessible and authoring for it really is like. You explicitly state > >you aren't familiar with it. I've been author of a couple CPAN modules > >for about 4 years now, and an extensive user for just as long, and have > >been a Python module writer for just over a year now. Python is a great > >language, but in terms of a reusable code repository, *nothing* comes > >close to the jewel that is CPAN. There is a reason you'll hear this over > >and over from people coming to Python from Perl. > > But somehow one doesn't hear it very often from people who've been using > Python for a long time Just to chime in - Aahz hit the nail on the head here... for whatever reason, *not* having a CPAN thingy just isn't that painful right now. Maybe someday it will be, and when that time comes we'll build one, but among long-time Pythonistas there just aren't that many people who are clamoring for it, including those who were long-time Perl folk in a previous life. It's great that people are trying for it because it *will* be useful, and eventually an implementation will get done and reach critical mass and become the standard, but not yet. I'm fully confident that if a CPAN-like system will be critical in the future, Guido will fire up the time machine, come back, and have somebody start working on it so it'll be done in time. -Dave From cliechti at gmx.net Sun Jul 21 07:33:47 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Jul 2002 13:33:47 +0200 Subject: wxMDIChildFrame References: Message-ID: Kevin Doyle wrote in news:pan.2002.10.20.19.13.44.213253.1677 at acrossthebigpond.com: > > I am new to wxPython and Linux, moving from MS. I am using the latest > release of wx and Python 2.2. ... > Any help or pointers in teh right direction would be great. did you had a look at: \Python22\Lib\site-packages\wxPython\demo\MDIDemo.py > One other question. Should I use MDI at all? i think it useful when you open a lot of windows and don't want to have an icon for each in the taskbar. however on linux its not so common as there you have multiple desktops and its easier to keep oversight. chris -- Chris From mhuening at zedat.fu-berlin.de Tue Jul 30 07:29:54 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 30 Jul 2002 11:29:54 GMT Subject: Pmw.MenuBar hotkeys References: Message-ID: Martin Franklin wrote in news:mailman.1028026245.27720.python-list at python.org: > This last bit on information is the problem (Windows!!!!) I can get > your example working on Linux without change but on windows (2000 in > my case) I can't. I dug around google but can't find a solution, > idle uses Tkinter Menu's and it works there but I don't understand > the code! Sorry I can;t be of more help > Thanks. At least now I know that the problem is not in my code. Matthias From amuys at shortech.com.au Thu Jul 11 20:21:31 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 11 Jul 2002 17:21:31 -0700 Subject: COCOMO - appropriate for languages like Python? (fwd) References: <200207102307.g6AN72822540@panix1.panix.com> Message-ID: <7934d084.0207111621.79c7865c@posting.google.com> Mike Brenner wrote in message news:... > Hi aahzpy! > > I am very interested in this problem, and would like to help, but I don't know what you mean. > > I viewed this message in textpad, microsoft word, wordpad, and netscape 4.79, and the two paragraphs below look the same. > > Is this possibly an Internet Explorer problem? Or is it a side-effect of the automatic reposting of python-list at python.org messages to comp.lang.python? > > Or it is a side-effect of translating from Windows format files to Linux format files? > None of the above. It's a side-effect of you relying on every viewer failing to display the text as you typed it. As there exist viewers that will honour your request to display each paragraph on a single line, this will cause problems for those people who through choice or necessity use such viewers. I'm taking the time to explain this as your post looked very interesting, however unfortunately I am one of those people who (in my case, by necessity) use just such a viewer. If you would like to see what your post looks like to such as I, I suggest you use google: http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&safe=off&selm=mailman.1026318496.22583.python-list%40python.org Andrae Muys From tim.one at comcast.net Tue Jul 16 18:44:55 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 16 Jul 2002 18:44:55 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty In-Reply-To: <61957B071FF421419E567A28A45C7FE514A5C5@MAILBOX.nameconnector.com> Message-ID: [Geoffrey Talvola] > Now that I think of it, maybe a Queue just isn't the right tool for this > job. Queues are basically designed for the case where you want > block on an empty queue. Also to block put() on a full Queue -- bounded queues are a natural approach to mediating between producers and consumers with different rates of production and consumption. > But for this use I never want blocking. Perhaps a simple > combination of a list and a lock would be better, or even a list alone > without a lock: > > try: > instance = cachelist.pop() > except IndexError: > instance = new_instance() > # use the instance > cachelist.append(instance) > > As long as pop() and append() are atomic, which I believe they are, then > this ought to work. They're atomic, yes. If the number of instances can't outnumber the number of threads, though, then a dead simple approach is to give each thread its own instance at start and skip all this queue fiddling. From brueckd at tbye.com Sat Jul 6 02:46:56 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 5 Jul 2002 23:46:56 -0700 (PDT) Subject: sending a file through sockets In-Reply-To: <3D253AA6.1090806@nowhere.org> Message-ID: On Fri, 5 Jul 2002, Bryan Olson wrote: > > Anyway, here's some sample code, but if > > you're not already familiar with sockets then you should spend a little > > time experimenting with them. > > Did you test this? Heaven's no! ;-) I shoulda included the standard 'not tested' disclaimer, although I use similar code all the time... > The Python library uses the empty string for > INADDR_ANY, which is fine for bind(), but I don't think it's legal for > connect(). Try it and be amazed! ;-) > I understand it's a basic demo, but I'll note that any real application > requires some time-out discipline to avoid very long hangs. Depends on your definition of 'real' of course. The simplest thing to do is just import timeoutsocket and set a default timeout and then the posted code works without modification. In my really real (production) code I usually use poll anyway, but I don't think that would have helped the OP much. > Also on > most Unix systems we'd need to watch out for signals that force system > calls to return. Hmm.. really depends on your application and which signals. For example, signal 2 gets translated into a Python KeyboardInterrupt, so you wouldn't handle it any differently. Most other signals kill the interpreter, which is fine with me. -Dave From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 10 11:32:57 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 10 Jul 2002 15:32:57 +0000 Subject: Fwd: Re: newbie: binding args in callbacks Message-ID: <200207101436.g6AEao719568@helios.gatwick.geco-prakla.slb.com> Whoops I sent to OP only! ---------- Forwarded Message ---------- Subject: Re: newbie: binding args in callbacks Date: Wed, 10 Jul 2002 14:59:46 +0000 From: Martin Franklin To: "Edward K. Ream" On Wednesday 10 Jul 2002 1:54 pm, Edward K. Ream wrote: > This question was asked a while back, and I don't see it in the FAQ or > in the archives... > > I would like to create a set of Tkinter callbacks that vary only in the > bindings of a single argument. For example, I would like to do: > > for val in vals: > b = Tk.Button(...,command=self.myCallback(val)) > > But this doesn't work: it executes callback, rather than returning the > callback function with the second arg bound to val. > > I also tried: > > for val in vals: > callback=lambda None:self.myCallback(x=val) > b = Tk.Button(...,command=callback) > > But that doesn't quite work either. When the callback executes I get: > TypeError: () takes exactly 1 argument (0 given) > > Can someone explain how to do this? Thanks. Create a callback class that uses the built in __call__ method class Callback: def __init__(self, value): self.value=value def __call__(self): ## do somthing with self.value if callable(self.value): self.value() ## so the GUI build looks like for val in vals: b = Tk.Button(...,command=self.Callback(val)) b.pack............... Example.... [bpse at m-franklin dev]$ python Python 2.2.1 (#3, May 29 2002, 20:32:44) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import * >>> >>> root=Tk() >>> class Callback: ... def __init__(self, value): ... self.value=value ... def __call__(self): ... try: ... self.value() ... except: ... print 'Cannot call', self.value ... >>> b=Button(root, text='Press ME!', command=Callback(1)) >>> b.pack() >>> Cannot call 1 Cannot call 1 Cannot call 1 Cheers Martin > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream at tds.net > Leo: Literate Editor with Outlines > Leo: http://personalpages.tds.net/~edream/front.html > -------------------------------------------------------------------- ------------------------------------------------------- -- Martin Franklin Initial Software Solutions (44) (0)1293 556629 / (44) (0)1234 888960 mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 10 15:32:32 2002 From phr-n2002b at NOSPAMnightsong.com Fri Jul 19 21:42:03 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 19 Jul 2002 18:42:03 -0700 Subject: Session ID & Security References: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> <3D38B779.3090602@removethisandallhyphens-o-n-e.net> Message-ID: <7xwurrkwes.fsf@ruckus.brouhaha.com> - c o v e n t r y - writes: > Why bother reinventing the wheel for a shared memory implementation > when you could just use the filesystem like everyone is used to, just > on a ram disk? > > Linux and the BSDs have the capability to do this... I'm not aware that Linux and BSD can do synchronous, atomic file operations. I'm not terribly up on this stuff though. What semaphore mechanism would you use? From steve.coates at talk21.com Mon Jul 8 16:20:15 2002 From: steve.coates at talk21.com (Steve Coates) Date: 8 Jul 2002 13:20:15 -0700 Subject: List assignment, unexpected result Message-ID: A friend of mine recently sent me some code and asked if I could predict what it would do. I guessed wrong. Code as follows:- grid = [['.'] * 4 ] * 4 grid [0][0] = '0' grid [1][1] = '1' grid [2][2] = '2' grid [3][3] = '3' for i in grid: print i The intent is clear i.e. fill the diagonal with 0,1,2,3; but the result is somewhat different. Could anyone explain why this doesn't work as expected - and even better, come up with an assignment for 'grid' that would work. My only suggestion was an explicit [['.','.','.','.'],['.','.','.','.'],etc. but it gets a bit cumbersome for large grids. Thanks Steve From syver-en+usenet at online.no Mon Jul 29 12:04:45 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 29 Jul 2002 16:04:45 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: Tim Daneliuk writes: > On a related note, where in the docs are values for KEY_READ, > KEY_WRITE, > > and so forth, defined? I cannot seem to find these... Can't you just do _winreg.KEY_WRITE instead of bothering with the exact values? Or if you really want to know: print _winreg.KEY_WRITE in a python console. -- Vennlig hilsen Syver Enstad From peter at engcorp.com Mon Jul 15 00:15:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Jul 2002 00:15:33 -0400 Subject: isA function? References: Message-ID: <3D324C65.CFB08B47@engcorp.com> Roy Smith wrote: > > "Delaney, Timothy" wrote: > > What would be more useful though is to simply try to use the functionality. > > If it works, why is there a need for it to be a particular type? If an > > attribute is missing, the unit test will fail. If the semantics are wrong, > > and it passes, the unit test needs an additional case added. > > But, what you're arguing is that the API is defined wrong, not that the > unit test is written wrong. If the API says, "foo() returns an object > of class bar", then it's the right thing for the unit test to determine > if, indeed, foo() returns an object of class bar. > > Now, if you want to tell me that I should change the definition of foo() > in the API to be, "returns something which has these three methods and > these seven data items", well, OK, that's might be a point worth > arguing. But, it's not the job of the unit test writer to decide that > the API isn't designed right. Also, since some rely on the unit tests to tell them when code is broken, if such a test were written "looser" so that it allowed *any* such object (which supported those three methods) then it would be possible that code breakage might not be caught by the unit tests. For example, a unit test for a factory function might be checking that instances of several different classes were being returned depending on the parameters passed in. If the code were broken so that only a single class was represented in the returned objects, Timothy's test would continue to pass (bad!) while yours would fail - just as you'd want - alerting you to the bug. Unit testing is *not* normal coding: sometimes you want to do things in unit testing which you would consider very bad style in regular code, and yet it's exactly the proper way to proceed in the tests. This is one reason I find Python *so* effective for test-driven development: it easily lets you bend the rules when you want to, and in unit testing you tend to want to more often than normal. -Peter From peter at engcorp.com Thu Jul 11 23:41:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Jul 2002 23:41:10 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> Message-ID: <3D2E4FD6.CDEB601A@engcorp.com> Jeremy Bowers wrote: > > (Thought: XML should never be your *first* choice of file format. It is > the choice of *last* resort, when you absolutely *need* easy parsing in > multiple languages or environments and can't get it any other way. It is > then a much better choice then other formats, but only under those > limited, albiet extremely popular, conditions.) I have to disagree with those who say, in effect, that XML is such an unsuitable technology that it is truly a last resort. XML was adapted from SGML to meet several key goals. Among those was the desire to make a format which was easily human-readable and editable using simple tools like text editors. For some people, this is a *hugely* beneficial benefit of using XML even for storage of simple data structures, which binary and/or specialized formats such as pickles do not have. In addition, it leaves open the possibility of very easily processing the data using one of the steadily growing number of XML utilities. One extremely simple example of this sort of thing is using IE to load an arbitrary XML file to observe that the file is in fact well-formed, and to get a quick idea of the structure of it. Not quite so simple with some other formats. It's obviously a religious issue, but I get the feeling that while some buy into the XML hype wholesale, and overuse it to their detriment, others are now jumping on some anti-XML bandwagon (possibly) without having really put it to the test. I often find that a choice to use XML opens up interesting avenues which would not even have occurred to me had I started off with another format, and so far I'm not sure I regret any particular case where I've used it. Now I'm *not* saying XML is always a first choice, and certainly a pickle is quite likely the Simplest Thing That Could Possibly Work and therefore a good first choice, but I do not think it deserves to be relegated to the abyss of "last resort". -Peter From gh_pythonlist at gmx.de Fri Jul 12 02:43:50 2002 From: gh_pythonlist at gmx.de (Gerhard Haering) Date: Fri, 12 Jul 2002 08:43:50 +0200 Subject: Guido van Rossum Tutorial - .PDF or other format? In-Reply-To: References: Message-ID: <20020712064350.GA15552@gargamel.hqd-internal> * David Wright [2002-07-12 16:30 +1000]: > Greetings > > Could someone please advise if this suberb document is available on the > Web in a printer friendly format, such as .pdf or even .doc. (other than > the hypetext version on line and on my PC). Yes, I'd like the *address* > too ;-) http://www.python.org/ftp/python/doc/2.2.1/pdf-a4-2.2.1.tgz with variations of paper size and zip vs. tgz. and it was pretty straightforward to find using www.python.org ;-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 16.6 ?C Wind: 3.6 m/s From roy at panix.com Sun Jul 7 17:49:13 2002 From: roy at panix.com (Roy Smith) Date: Sun, 07 Jul 2002 17:49:13 -0400 Subject: is this a bug? References: <1026076470.877638@master.nyc.kbcfp.com> Message-ID: "news" wrote: >>>> "aa" in ("aa") ("aa") is not a tuple. ("aa",) is. One of Python's little warts. From sethtoday at hotmail.com Mon Jul 29 17:54:02 2002 From: sethtoday at hotmail.com (Seth Ainsley) Date: Mon, 29 Jul 2002 21:54:02 +0000 Subject: MIDI Music Message-ID: An HTML attachment was scrubbed... URL: From jimb417 at NO* Wed Jul 31 23:43:57 2002 From: jimb417 at NO* (Jim) Date: Wed, 31 Jul 2002 21:43:57 -0600 Subject: PyQT3.3 problem Message-ID: I'm having trouble with this code which displays two pushbuttons and one label. I want to change the text in the label when one of the buttons is clicked: from qt import * import sys class Widget(QWidget): def __init__(self, parent = None, name = None): QWidget.__init__(self, parent, name) hello = QPushButton( "Hello There!", self ) hello.setGeometry(80, 80, 100, 120) button = QPushButton( "Text", self ) button.setGeometry( 200, 200, 40, 40 ) label = QLabel( "This is some text", self ) label.setGeometry( 80, 220, 100, 20 ) self.connect( hello, SIGNAL( "clicked()" ), qApp, SLOT( "quit()" ) ) self.connect( button, SIGNAL( "clicked()" ), qApp, self.buttonClicked()) def buttonClicked( self ): label.setText ( "Set" ) app = QApplication (sys.argv) a = Widget() a.setGeometry( 100, 100, 300, 300 ) a.setCaption( "This is a widget") app.setMainWidget( a ) a.show() app.exec_loop() What is the proper way to implement the custom slot correctly? I wrote this from scratch ( not using Qt Designer ) When I run this code, this error pops up: File "pyExample.py", line 27 in ? a = Widget() File "pyExample.py", line 19 in __init__ self.connect( button, SIGNAL( "clicked()" ), qApp, self.buttonClicked() ) File "pyExample.py", line 22 in buttonClicked label.setText( "Changed" ) NameError: global name 'label' not defined Mutex destroy failure: Device or resource busy How can 'label' be global when it is a member of the class Widget? The docs aren't very clear on this. Can anyone out there give me a nudge in the right direction on getting this to work. If you comment out line 19, the widget will display onscreen( of course the button labled "Text" will do nothing when clicked, the other button closes the program ) Thanks for reading this and for any assistance. Jim -- Registered Linux User #269187 http://counter.li.org From fredrik at pythonware.com Sat Jul 27 17:18:18 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 21:18:18 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: (reset) Alex Martelli wrote: > I can defend my position well, unless it's some variation of "gotta keep arguing", I'm not really sure what your position is. > > If you like lambdas, use them. All the best pythoneers do, so why > > shouldn't you? > > On the other hand, implied put-downs such as this one it's an observation based on grep + a considerable amount of freely available code... ...cannot judge code that I haven't seen, though. so feel free to consider yourself a great pythoneer, even if the strakt code- base is completely free from lambdas and print >> etc. From aleax at aleax.it Wed Jul 24 04:44:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:44:45 GMT Subject: format strings or page tempaltes References: Message-ID: <1Ot%8.109792$Jj7.2621183@news1.tin.it> Jeff Davis wrote: ... > Is this possible with the string format syntax? If not, could someone > recommend a good template module or something similar? It's quite possible, but a good templating system is a better idea. The first "real" task I once did in Python was a tiny templating system -- I was truly amazed at how much I could accomplish in a few dozen lines, it was part of what truly hooked me on Python. You can find it as YAPTU in the cookbook, both online and printed. But a real templating system is something else again. I've now personally dumped YAPTU usage and, after careful examination of all the various offerings around, switched to Cheetah instead. Give Cheetah a try. You won't regret it. Alex From linuxbrad at rogers.com Sun Jul 7 20:28:45 2002 From: linuxbrad at rogers.com (Brad Fonseca) Date: Mon, 08 Jul 2002 00:28:45 GMT Subject: Getting IDLE 0.8 to recognize Pyhthon 2.2.1 Message-ID: <115W8.7627$Xg%.3561@news01.bloor.is.net.cable.rogers.com> Hi! I've upgraded to python 2.2.1 but when I start IDLE it still starts Python 2.1.1. How do I get IDLE to start Python 2.2 Regards, -- --- Brad Fonseca From sjoerd at acm.org Mon Jul 8 11:36:35 2002 From: sjoerd at acm.org (Sjoerd Mullender) Date: Mon, 08 Jul 2002 17:36:35 +0200 Subject: freeze path problem (on nt) In-Reply-To: <9a6d7d9d.0207080658.3d8181d8@posting.google.com> References: <9a6d7d9d.0207080658.3d8181d8@posting.google.com> Message-ID: <200207081536.g68FaZH14936@indus.ins.cwi.nl> I remember we had problems with this too. If I remember correctly, this had something to do with the registry (of the installed Python) messing things up for the frozen application. What we ended up doing is ignoring the registry completely (see PyWin_FindRegisteredModule in PC/import_nt.c) in the frozen application. This meant that we had to compile Python separately for our frozen app. I'd argue that a frozen Python application should *never* use the registry of an installed Python. You don't have control over it, and it may well be a different (and incompatible) version. On Mon, Jul 8 2002 Aaron Watters wrote: > Hi guys. I have the following problem. > > I use tools/freeze to build a frozen exe (X.exe) for windows using vc++ 6. > > If I run it on a machine without a python installation it runs fine. > But if I run it on a machine with python and a package called > > rlextra.rml2pdf > > then the import > > from rlextra.rml2pdf import rml2pdf > > imports the python module from the file system in preference to the > frozen pyc that is compiled into X.exe. This is a problem, of course > if the version of rml2pdf on the file system differs from the one in X.exe. > > It must have something to do with sys.path and/or those goofy *.pth files > right? > > Anyway, how do I prevent X.exe from trying to import stuff from the > file system first before looking internally... anybody got a clue? > > thx in advance > > =- Aaron Watters > > === > JUVENILE COURT TO TRY SHOOTING SUSPECT > -- from "real headlines" (that should work...) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sjoerd Mullender From debl2nonospammyyy at bellatlantic.net Thu Jul 11 00:19:58 2002 From: debl2nonospammyyy at bellatlantic.net (David Lees) Date: Thu, 11 Jul 2002 04:19:58 GMT Subject: How to replace multiple-line text Message-ID: <3D2D0782.45FCEC98@bellatlantic.net> I would like to process a code file and substitute one multiline block of code for another. I know how to do this in Python by brute force scanning through on a line by line basis until the first line of the pattern is found then looping over the rest of the lines in the target pattern for a match, then substituting in an output string multiline substitution. But I am sure there is a neater solution, perhaps using regular expressions. Could someone point me towards sample code or something similar that I could modify. Thanks in advance. David Lees From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 11:44:42 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 10:44:42 -0500 Subject: Make me beautiful (code needs help) References: Message-ID: >>>>> "Mark" == Mark writes: Mark> Now, the other problem, is that in general, I want to fill Mark> data["new"] with an arbitary function of the values in Mark> data["A"]. As a dumb example, I might want to fill Mark> data["new"] with copies of the mean (average) of data["A"]. Mark> So, in some cases, the new values are relative to the Mark> current location (ie i and i-1) and in other they are Mark> absolute (ie all of them). Mark> I can certainly hack through this, but I'm looking for Mark> something pretty. I know python is up to it. Mark> Regards, Mark Well, you can just write the functions you want, design the functions to operate on lists, and call them. If you are using python 2.0 or later, you can use list comprehensions (as Emile's example demonstrates) http://www.python.org/peps/pep-0202.html Here are some more examples: def diff(x): return [None]+[a-b for b,a in zip(x,x[1:])] def square(x): return [val*val for val in x] def mean(x): return reduce(lambda a,b: a+b, x)/float(len(x)) data = {} data["A"] = [1,2,4,10,50] data["New1"] = diff(data["A"]) data["New2"] = square(data["A"]) data["New3"] = mean(data["A"]) print data["New1"] print data["New2"] print data["New3"] If you plan to be using large lists and/or performance is an issue, you should take a look at Numerical Python, which has lots of built in functions (diff, mean, std, etc...) for operating on lists http://www.pfdubois.com/numpy/ Cheers, John Hunter From clpy at snakefarm.org Fri Jul 19 17:47:12 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Fri, 19 Jul 2002 23:47:12 +0200 Subject: Recursion References: <1ffkjwu.1rdosep1g6a6qzN%smurf@noris.de> Message-ID: <3D3888E0.3050607@snakefarm.org> Matthias Urlichs wrote: > Abhijit Soman wrote: > >> def showbits(x): >> if x != 1: >> showbits(x >> 1) >> if x & 01: >> print 1, >> else: >> print 0, > > > It's interesting that nobody seems to have caught the infinite recursion > when you try to show a value which happens to be zero... > ... which, of course, we would elegantly resolve by saying: try: showbits(foo) except RuntimeError: print 0 ;-) cg. From max at alcyone.com Mon Jul 8 18:47:17 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Jul 2002 15:47:17 -0700 Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> <3D29F478.4528312C@alcyone.com> Message-ID: <3D2A1675.4B61F2BC@alcyone.com> Glyph Lefkowitz wrote: > I would like to respond to the ageist, patronizing tone of this > message, and > let the enduring and superior maturity of the poster (who was, if I > recall > correctly, banned under the pseudonym "xihr" for spreading exactly > this kind of > FUD) speak for itself: > > http://www.alcyone.com/xihr/ So what's that have to do with anything? Are adults not allowed to have senses of humor? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From spinwing at inwind.it Wed Jul 24 06:58:38 2002 From: spinwing at inwind.it (Stefano Vedovelli) Date: Wed, 24 Jul 2002 10:58:38 GMT Subject: GUI toolkits Message-ID: Hello all in my spare time I am writing a tool in python, with the intention of deliver it under GPL. I am now starting to approach the GUI part. I have read a lot about Tkinter, PyQT and wxWindows, but I am now actually even more confused. As the interface will be "quite" rich, I'd like to know the opinions of people who already faced this decision, which tool they have chosen and why. Tia Regards Stefano Vedovelli From m.laranjeira at datacraft.com.br Wed Jul 3 16:29:42 2002 From: m.laranjeira at datacraft.com.br (Marcus Vinicius Laranjeira) Date: Wed, 03 Jul 2002 17:29:42 -0300 Subject: Reportlab Message-ID: <5.1.1.6.0.20020703172801.00a01590@imap.datacraft.com.br> Does anyone here uses Reportlab to create charts !? I need some help about this, but I could'n find anywhere .... Since reportlab is a library to create graphics, pdf and charts with python... I hope someone here uses it ! then we could talk in pvt ! Thanks, Marcus From claird at starbase.neosoft.com Mon Jul 1 14:29:40 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 1 Jul 2002 13:29:40 -0500 Subject: Newbie that don't understand References: <3d1e262f.3755054@news.clara.net> <3D1E4F80.D8EFBB3E@engcorp.com> <3D1E56EC.7080203@SPAMnwinternet.com> Message-ID: In article <3D1E56EC.7080203 at SPAMnwinternet.com>, Jim wrote: . . . >chemistry, like a battery). Electrons leave the negative >terminal and flow towards the positive terminal (blame >this on whoever decided protons were positive and electrons >negative). The electro-motive force (emf, which is what . . . It was a collective decision. Like several other historical puzzles, it took all of us working together to reach this confusing state. Franklin and contemporaries figured out that it was good to identify a polarity attribute of static electricity. At the macroscopic level, this binary distinc- tion is arbitrary. They happened to choose the one where electrons--which happen to be the charge carriers for con- ventional Terran electronics--are called "negative". Electrons weren't identified conceptually for over a century, by J. J. Thomson and peers. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From shagshag13 at yahoo.fr Tue Jul 2 11:03:06 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 2 Jul 2002 17:03:06 +0200 Subject: what can i expect... Message-ID: hello, what can i expect if i change my python application to java ? (or when do you think it's time to change parts of python code to java ? for what purposes ?) thanks in advance, s13. From observer at NOSPAM.space.pl Mon Jul 15 10:45:24 2002 From: observer at NOSPAM.space.pl (Johann) Date: Mon, 15 Jul 2002 16:45:24 +0200 Subject: uniform interface for MySQL & MSSQL Message-ID: I would like to write a hybrid application which works on Linux and Windows platform so I need the same API for SQL (MySQL and MSSQL2K). I would like to use Python Database API Specification v2.0 (http://www.python.org/peps/pep-0249.html) and I found a nice implementation such interface at http://www.nmt.edu/tcc/help/lang/python/dbhelpers.html. The problem is there is no mssql module, only sybase, oracle and mysql. I tried to use sybase on mssql but it's does not work because I have "no ctsybase Python module". I do not want to use odbc because I want to move internal db cursor by arbitrally number of records. -- Johann From wesc at deirdre.org Tue Jul 9 15:09:13 2002 From: wesc at deirdre.org (wesc at deirdre.org) Date: Tue, 9 Jul 2002 12:09:13 -0700 (PDT) Subject: ANN: BayPIGgies mtg Wed 7/10 7:30pm Message-ID: <200207091909.g69J9Dp03231@alpha.ece.ucsb.edu> BayPIGgies/Silicon Valley-San Francisco Bay Area Python Users Group When: July 10, 2002 @ 7:30pm Agenda: Internet Programming with Python Where: Stanford University, Palo Alto, CA Continuing the high-level talks for the O'Reilly OSCON 2002 conference coming up in a few weeks, I will give an introductory talk on various forms of Internet programming using Python: - Network Programming (client/server, socket module) - Internet Client Programming (FTP, NNTP, POP3, telnet) - CGI Programming (CGI basics, cgi module) The full description of the tutorial I will be presenting can be accessed here. I will also be giving the "now"-annual intro to the complete newbie BOF: What is Python? Upcoming Meetings: 8/14: looking for a guest speaker! 9/11: Using a Model-View-Controller Architecture to Create a Python/XML-based Web Application Framework We are actively seeking speakers for BayPIGgies, esp. August! If you would like to give a talk at one of our meetings (any Python related topic), contact us to coordinate! more info including directions: http://www.baypiggies.net hope to see some of you tomorrow evening! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://deirdre.org/baypiggies wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From mf at mrinfo.de Fri Jul 19 10:44:54 2002 From: mf at mrinfo.de (Marko Faldix) Date: Fri, 19 Jul 2002 16:44:54 +0200 Subject: Anybody using 4suite for xslt processing? Message-ID: Hi, sometimes I think I am first man on earth want to process xslt. I got python on windows 2000 Server with iis and 4suite, I could change to linux if necessary. The following script: ############################################### from Ft.Xml.Xslt import Processor xslfilename = "abc.xsl" xmlfilename = "abc.xml" path = "C:\\serverdirectory\\me\\python\\" xslfile = path+xslfilename xmlfile = path+xmlfilename processor = Processor.Processor() processor.appendStylesheetUri(xslfile) result = processor.runUri(xmlfile) print 'Content-type: text/html\n' print result ############################################### throws this in browser: ::: Using minidom Traceback (most recent call last): File "C:\home\marko\python\bxslt.py", line 15, in ? processor.appendStylesheetUri(xslfile) AttributeError: Processor instance has no attribute 'appendStylesheetUri' But documentation contains method 'appendStylesheetUri'. Somebody any idea? I am at the point that installation is ready and try to process our first xslt to see that it can be used for it. -- Marko Faldix M+R Infosysteme Hubert-Wienen-Str. 24 52070 Aachen Tel.: 0241-93878-16 Fax.:0241-875095 E-Mail: marko.faldix at mplusr.de From fredrik at pythonware.com Sat Jul 27 19:32:45 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 23:32:45 GMT Subject: xrange questioin References: <3d43234e$1@duster.adelaide.on.net> Message-ID: Gerald Squelart wrote: > Ok, let me rephrase Chris' question for a simpler case: > What is better: for x in range(n) or for x in xrange(n)? > (with n is relatively small, like 10 or 100) for in range() is usually a few percent faster, but if you do some- thing inside the loop, you'll hardly notice the difference. if performance matters a lot, I suggest benchmarking. From marklists at mceahern.com Thu Jul 4 13:11:11 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 4 Jul 2002 12:11:11 -0500 Subject: metaclass & __slots__ In-Reply-To: <02070418471803.27180@arthur> Message-ID: [Alex Martelli] [snip] > But, let's get into details: [snip] Alex, thank you for this very patient explanation of the fine details of Python class creation. This helps me tremendously. // mark - From whisper at oz.net Mon Jul 22 15:11:28 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 22 Jul 2002 12:11:28 -0700 Subject: Anybody using 4suite for xslt processing? In-Reply-To: Message-ID: > My installation of 4suite dropped the respective directories to > > Python22\Lib\site-packages\Ft > > so I have to use Ft.Xml.Xslt - without Ft 4suites classes can't be found. > > In Python22\Lib\site-packages\Ft\Xml\Xslt there is a file called > Processor.py which contains class Processor. Indeed, inside this class I > can't find appendStylesheetUri. appendStylesheetUri in Python22\Lib\site-packages\Ft\Server\Server\http\ My 4suite version is 12.0.a2 > Then I searched for string "appendStylesheetUri" in the whole tree > \Python22 and found nothing that implements this. > > Is the installation gone wrong? Also found it in: python22\lib\site-packages\_xmlplus\xslt\processor.py python22\lib\site-packages\_xmlplus\xslt\_4xslt.py These last 2 are from PyXML 0.7.1, which is probably what you want. N.B. pyxml should be installed before 4suite. Dave LeBlanc From gerhard.haering at gmx.de Tue Jul 9 06:21:07 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 12:21:07 +0200 Subject: [OT] Corrections about Java In-Reply-To: <200207091157.18646.b.maryniuk@forbis.lt> References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091137.11467.b.maryniuk@forbis.lt> <20020709094938.GA1489@lilith.my-fqdn.de> <200207091157.18646.b.maryniuk@forbis.lt> Message-ID: <20020709102106.GA1792@lilith.my-fqdn.de> * Bo M. Maryniuck [2002-07-09 11:57 +0200]: > On Tuesday 09 July 2002 11:49, Gerhard H?ring wrote: > > Works for me. > I meant: > some_loop_forewer { > try { > break; > } finally { > continue; > } > } > > Perhaps 1.3.1 just fixed here... No, endless loop in my JVM, too. Btw. Python sorts this out in that continue inside a try-block is illegal. > > Btw. Python had a similar problem in 2.0, IIRC. > At least Python 1.5 no. Wow, do you drive an antique car, too? ;-) http://python.org/sf/220983 http://python.org/sf/215143 http://python.org/sf/210830 And this was the one I remembered: http://python.org/sf/462937 Looks like it's a tricky problem. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 28.1 ?C Wind: 2.6 m/s From jonathan at onegoodidea.com Thu Jul 4 17:40:44 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 22:40:44 +0100 Subject: metaclass & __slots__ References: Message-ID: On 4/7/2002 17:47, in article mailman.1025801286.31332.python-list at python.org, "Alex Martelli" wrote: > More generally, in your __init__ (whether of a metaclass or > any other class): call the superclass's __init__ AFTER you have > performed modifications to the arguments, if you need to change > the arguments and the superclass's __init__ is going to take > some action based on them. Metaclasses are no different (in > this or most other respects) from any other class. Unfortunately, you can't set or modify __slots__ in the __init__ method of a metaclass. The damage has already been done by the time you get to the __init__ method: >>> class foo( type ): ... def __init__( cls, name, bases, dict ): ... dict['__slots__'] = ['x','y'] ... super(foo,cls).__init__( name, bases, dict ) ... >>> class bar: ... __metaclass__ = foo ... >>> b = bar() >>> b.x = 10 >>> b.foo = 'heck' >>> b.__dict__ {'x': 10, 'foo': 'heck'} >>> You need to make the change in the __new__ method before the class is allocated: >>> class foo( type ): ... def __new__( cls, name, bases, dict ): ... dict['__slots__'] = ['x','y'] ... return type.__new__( cls, name, bases, dict ) ... >>> class bar: ... __metaclass__ = foo ... >>> b = bar() >>> b.x = 10 >>> b.foo = 'heck' Traceback (most recent call last): File "", line 1, in ? AttributeError: 'bar' object has no attribute 'foo' >>> b.__dict__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'bar' object has no attribute '__dict__' >>> See my other post for more on this. Jonathan From jim at dsdd.org Wed Jul 31 04:24:22 2002 From: jim at dsdd.org (Jim Meier) Date: Wed, 31 Jul 2002 08:24:22 GMT Subject: Nested stream line iteration References: Message-ID: On Tue, 30 Jul 2002 06:11:57 -0600, Lars Lundgren wrote: [snip] > for line in fileinput.input(filename): > [m,t] = string.split( line ) > build( m,t ) > [snip] > When I run it I get the following error: > > raise RuntimeError, "input() already active" > RuntimeError: input() already active > > As I understand it, this means that it is not allowed to nest input() like > I do. Is that correct? > > Then is there a working solution to my problem? > I don't know about fileinput, but the idiom i would use here is a simple: for line in open(filename).readlines(): ...(stuff).. -Jim From mwh at python.net Fri Jul 26 06:30:54 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 10:30:54 GMT Subject: Just starting out References: <1763824.4DULROvNVE@CoReKill@localhost> Message-ID: Alex Martelli writes: > Other smart editors such as SciTE (a tiny elegant wrapper on the > Scintilla component that IDLE and others use) I thought IDLE used Tk's Text widget. Cheers, M. -- US elections For those of you fearing that the rest of the world might be making fun of the US because of this: Rest assured, we are. -- http://www.advogato.org/person/jameson/diary.html?start=12 From skip at pobox.com Tue Jul 23 17:59:34 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Jul 2002 16:59:34 -0500 Subject: list to string In-Reply-To: References: Message-ID: <15677.53702.74096.508808@12-248-11-90.client.attbi.com> David> fn = file('foo.txt') David> txt = fn.readlines() David> str = ?something?(txt) # or txt.?something?()... Assuming what you really want is to get the contents of the file in one gulp, this should work: fn = file('foo.txt') str = fn.read() -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From aleax at aleax.it Fri Jul 26 09:57:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 13:57:12 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: Jonathan Hogg wrote: > On 26/7/2002 12:33, in article Ora09.122577$Jj7.2838699 at news1.tin.it, > "Alex Martelli" wrote: > >> (BTW, I've been programming for over _25_ years now -- more than >> half of my life...). > > Hmmm... over 18 years, about 2/3rds of my life. Never thought of it that > way before. > > I don't recall ever intending to be a computer programmer... Me neither: I wanted to design hardware. I chose electronic engineering, then hardware design specialties within that, a thesis in the HW field, and jobs with Texas Instruments, then with IBM Research, each meant to be about hw design. Each and every time the "hw" job turned out to be about designing, coding and/or maintaining programs to test, design, simulate and/or exercise hardware. At which point I resigned myself to the fact that the universe wanted me to do software, not hardware, and learned to like it. Haven't even _pretended_ to design a chip in 20 years now. Alex From CousinStanley at HotMail.com Sat Jul 13 12:26:02 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Sat, 13 Jul 2002 09:26:02 -0700 Subject: pyCard_turtleTimes References: Message-ID: Neil ... Thanks for the reply ... Kevin's suggestion to turn off Auto-Refresh for the pyCard turtle samples made a DRAMATIC difference in the plot times ... AR AR NO AR Neil Stan Stan ChaosScript2and3 ...... 157 ............. 1306 ........ 18 hopalong ...................... 554 ............. 893 ........ 46 madness ...................... 482 ............. 2771 ........ 53 Your results using a 600 MHz processor with a video card are much better than mine using a 250 MHz processor and on-board video, which is certainly expected, but not as disturbing as the 15 minute / 15 second comparison mentioned in my original post, and re-inforce my thoughts that I STILL need to go to the 'puter store ... I don't consider these applications central to my efficiency, but perhaps a glimpse into the performance of the PythonCard samples and Python itself and am quite relieved that turning off the Auto-Refresh option made a HUGE difference ... Cousin Stanley From emile at fenx.com Wed Jul 10 08:24:49 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 10 Jul 2002 12:24:49 GMT Subject: Learning how to program... but what's the best way? References: <3D2BB54C.90500@earthlink.net> Message-ID: "Hans Nowak" wrote in message news:3D2BB54C.90500 at earthlink.net... > > Hi, > > I know a 14-year-old who wants to learn programming. Of course I'd recommend > Python, and I also know the way to all the tutorials, non-programmers > introductions, etc. But... > > The problem is, I don't expect my student to swoon over "hello world", or to > get excited about doing basic mathemathical computations. Nor will standard > computer science stuff about bits, bytes, hexadecimal numbers etc be appealing. > Sure, those concepts are important, and will be dealt with in due time, but > what I'm looking for right now is a way to capture people's interest-- to do > something funny, or cool, or useful even for someone who doesn't know programming. > > To give an idea of what I have in mind: A good start could be, for example, > some kind of game that can be scripted in Python, and therefore extended at > will. The "student" could say, "I want the game to do this-and-that", then > proceed to implement it. Unfortunately, I know of no such game, and have no > time to write it <0.3 wink>. > > Besides this, does anyone have ideas about what would be a good starting point > here? > I had this come up last month with my older daughter, although she's 3 years younger and that would make a difference. I got her an account on freezope last year and she's enjoyed playing with html, but now she wants to make games, like she plays on neopets. If you don't know of neopets, you're missing out on the new 'Barney', so no loss ;-)). I put a copy of Solar Wolf (Thanks Pete!) on her system, and showed her how she could make minor modifications. I also got her started with turtle, specifically following along with the demo code. Now I wait and see when the next set of questions come up. With html it took about two-three months before I was asked about links, and a few months later about adding sound. At that point, I got her a hard copy tutorial she could follow. This time, when it gets to that, I'll look to the newbies page at python.org for the next step. -- Emile van Sebille emile at fenx.com --------- From pecora at anvil.nrl.navy.mil Wed Jul 10 10:18:05 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 10 Jul 2002 10:18:05 -0400 Subject: Why self? References: Message-ID: <100720021018055446%pecora@anvil.nrl.navy.mil> In article , Delaney, Timothy wrote: > Why are you assigning None to the local variable "name", and then not using > it? > > That's the basic problem here - there is no way of knowing if "name" is > supposed to be a local variable which will be used only in __init__, or > whether you want to create an instance name. Sigh. Yes, it should be (in current Python) self.name=None My point was then name can be used later in the object's methods without the self. Sigh #2. It was only a quick example. I always initialize object variables, usually with data that makes their use clear or their use later not lead to problems. Maybe something like, self.name="Default name" I'm not advocating this as the end-all of "solutions", but just a quick example that an alternative may be possible. -- Lou Pecora - My views are my own. From dreed at capital.edu Tue Jul 23 18:43:08 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 23 Jul 2002 18:43:08 -0400 Subject: list to string In-Reply-To: <20020723174006.B3170@eecs.tufts.edu> (message from Michael Gilfix on Tue, 23 Jul 2002 17:40:06 -0400) References: <20020723174006.B3170@eecs.tufts.edu> Message-ID: <200207232243.g6NMh8G04597@localhost.localdomain> Wouldn't all_text = file.read() do what you want instead of reading the lines and then joining them? Dave > From: Michael Gilfix > > It sounds like you want to do something like this: > > list = [ 'this', ' ', 'is', ' a', ' test' ] > string = ''.join (list) > > Or if you want a space and you just have a list > of strings: > > string = ' '.join (list) > > The character in the source string is used to join the elements in > the list of the join() call. So in the context of what you're written > here, you could do: > > file = open ('foo.txt', 'r') > lines = file.readlines () > all_text = ''.join (lines) > > -- Mike > > On Tue, Jul 23 @ 13:08, David LeBlanc wrote: > > I have this code: > > > > fn = file('foo.txt') > > > > txt = fn.readlines() > > > > str = ?something?(txt) # or txt.?something?()... > > > > What's the something? This is probably so obvious, i'm going to feel dumb, > > but I havn't been able to find anything in any doc I've looked at. > > > > David LeBlanc > > Seattle, WA USA From gcordova at hebmex.com Mon Jul 8 12:18:47 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 8 Jul 2002 11:18:47 -0500 Subject: Python 2.1 == Jython 2.1 != Python 2.2? Message-ID: > > > > > > > If so, is there an ETA on Jython 2.2? > > > > > > What is an ETA? > > > > > > Regards, > > > Martin > > > > > > > ETA == "Environmental Turnover Announcement" > > > > Typo prolly. > > > > ;-) > > > > -gus > > I think he wants Estimated Time of Arrival -- i.e. when can he > get his hands on Jython 2.2 > > Laura > argh... When is a wink not a wink such that an included wink does not a wink's function complete, which is to make others understand that it's a joke? -gus From b.maryniuk at forbis.lt Fri Jul 26 03:42:37 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Fri, 26 Jul 2002 09:42:37 +0200 Subject: how to count lines in a file ? In-Reply-To: References: Message-ID: <200207260942.37328.b.maryniuk@forbis.lt> On Thursday 25 July 2002 16:09, Alex Martelli wrote: > If you do forget it, understanding what's garbage, what not, gets tricky:-). Ah, sure I forget this "perlish stuff", like $_ -- just `coz never use it. ;-) Thanx. -- Sincerely yours, Bogdan M. Maryniuck I've run DOOM more in the last few days than I have the last few months. I just love debugging ;-) (Linus Torvalds) From anton.wilson at camotion.com Tue Jul 30 17:49:22 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 30 Jul 2002 17:49:22 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207302148.RAA28339@test-area.com> > > [and certainly not by assuming the Python developers are too lazy or stupid > to have thought of this before and demanding some kind of action.] It would seem that python developers like to assume other people are calling them stupid and lazy and take hints as offensive or demanding action. I've never seen so much hostility to a bug in my life. Anton > > -no-after-you-ly y'rs, > > Jonathan From jb at cascade-sys.com Tue Jul 9 02:56:51 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 08 Jul 2002 23:56:51 -0700 Subject: COCOMO - appropriate for languages like Python? References: <15655.16377.250899.348691@localhost.localdomain> Message-ID: <3D2A8933.455EC8B0@cascade-sys.com> Skip Montanaro wrote: > It's been many years since I've considered software cost estimation models > like COCOMO. Is COCOMO appropriate to apply to high-level languages like > Python? IMHO, Yes. > I believe COCOMO assumes each fully debugged source line of code > (SLOC) in any language and for any purpose costs roughly the same amount to > produce. Not true. COCOMO is an elaborate model that relates quite a number of factors pertaining to software development. E.g., one of the general results is that cost per LOC will be higher on a larger project than on a smaller one and that LOC will be lower with smarter staff than with less clever members. The COCOMO model includes quite a few knobs and dials for understanding how your shop is operating and, when calibrated to your way of doing things, COCOMO provides for predicting the costs of future projects. > The cost savings for languages like Python would come because you > have to write so many fewer lines of code to implement the desired > functionality. Yes, in applications where this is true. IIRC, COCOMO has a "knob" for how high or low level the programming language in use happens to be. > Are there other (more modern?) cost estimation models which don't assume > cost-wise that a SLOC is a SLOC is a SLOC? COCOMO does NOT make the assumption about SLOC cost that you seem to believe. For COCOMO to work AT ALL it needs to be calibrated with historical data about your own shop (e.g., historical average cost/LOC). Without the historical data then the model will be unable to predict anything meaningful about your performance. I'm sure there are other, much simpler methods that work OK. Actually, COCOMO is somewhat Baroque, in that it originally attempted to take into account all sorts of major and minor factors affecting in software development. After applying COCOMO to A Lot of projects, Bohem discovered that a small number of factors made most of the difference: The biggest productivity factor was quality of people. There is like a 1000:1 range of productivity between the top and bottom performers in large organizations. This generally swamps everything else, including choice of language, or personnel costs (the 1000x guy does not cost 1000x as much as the bottom performer). The second biggest factor is overall size of the project. That is, all other things equal, the cost per LOC is NOT constant, but it is higher on a large project and smaller on a small project. Furthermore, it appears to grow exponentially on overall project size, swamping all other factors on very large projects. I forget how the others factors ranked but IIRC, choice of language (high or low) was fairly low in the overall ranking. >From a management standpoint, your strategy should be to always strive to hire the very best people and to break projects into moderate sized, easily handled chunks. >From a schedule estimation standpoint, LOC (however you choose to count them) appears to be a pretty good estimator to use for a fixed staff and fixed project sizes. How the prediction varies as you change staff or project sizes is something you'll have to measure or guess at yourself. At least COCOMO research gives you some idea how the curves are shaped. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From 102030405 at gmx.net Sat Jul 13 07:58:44 2002 From: 102030405 at gmx.net (Ralf Claus) Date: Sat, 13 Jul 2002 13:58:44 +0200 Subject: login with python (2) Message-ID: Hello, the login website of my router needs the following html code to login :

I need a way to login to my router using a python script (automatic login). I can't find a way to implement this code in a script. I need help, or a site with an example.......:-(( thx Ralf PS: Thomas, your way is to hard for me, i am a newbie.....*first class newbie :) From zopestoller at thomas-guettler.de Mon Jul 29 03:11:37 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Mon, 29 Jul 2002 09:11:37 +0200 Subject: Leo.py: Some Thoughts Message-ID: <3D44EAA9.7010607@thomas-guettler.de> Since nobody answered in the leo forum I try it here: I just installed leo.py (hierachical editor). Here are some notes while trying it for the first time: +I didn't find a possibility to change the current text field without the mouse. ctrl-u moves the text field. Can you change the focus without mouse? +Link in FAQ "What's the best way to learn to use Leo?" is broken +How do you export? The "Save as" method only lets you save as foo.leo I am interested in HTML output. +Can you store pictures or tables (HTML-Tables)? +Difference between "Save to" und "Save as"? +No email adress in the about box. Feedback welcome? +If you open it by double-clicking (win32) the path is wrong, the LeoDocs.leo can't be found. A Glossary discribing the following words would be nice: +Noweb? +CWeb? + at file +tangle? +outline? +Remove Sentinels? +Target Language? +Promote +Demote +Compare Window Exceptions: +Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "leoPrefs.py", line 366, in onCancel self.set_ivars(c) File "leoPrefs.py", line 285, in set_ivars self.target_language = self.lang_var.get() File "C:\Python22\lib\lib-tk\Tkinter.py", line 234, in get return getint(self._tk.globalgetvar(self._name)) ValueError: invalid literal for int(): None Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "leoFrame.py", line 2485, in OnLeoDocumentation es("LeoDocs.leo not found") File "leoGlobals.py", line 131, in es log.put(s) File "leoFrame.py", line 829, in put self.log.insert("end",s) File "C:\Python22\lib\lib-tk\Tkinter.py", line 2703, in insert self.tk.call((self._w, 'insert', index, chars) + args) TclError: invalid command name ".23422392.23421568.23940456.23816376.23269248.log" Platform: Python2.2 on Windows2000, Leo 3.1 BTW, it works with cygwin's python, too From maxm at mxm.dk Fri Jul 19 18:02:02 2002 From: maxm at mxm.dk (Max M) Date: Sat, 20 Jul 2002 00:02:02 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: <3D388C5A.4070309@mxm.dk> Rhymes wrote: > When Python 2.3 will be released? > > I've read the "what's new" and i'm waiting generators and true > division :-) Hmm ... sounds like you look for a reason to postpone a project. ;-) regards Max M From mwh at python.net Wed Jul 10 08:13:37 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 10 Jul 2002 12:13:37 GMT Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> Message-ID: Wolfgang Draxinger writes: > For my current 3D engine project I decided to use Python as a > important part of the whole design. And it works well. OK. > However, now I want to make python an integal part of the engine, not > just a external lib. And I not want to statically link it with the > engine. To me these sentences contradict each other. So I must be missing something... > My goal is, to discard all modules and builtin functions that I > don't need, e.g. sys. It's intended to control the 3D engine, not to > write complex scripts. For the modules, just don't build them. You really don't want to try getting rid of sys, btw. For getting rid of builtin functions, why bother? > Can anybody give me some advice for that. Yes: don't. > Embedding Python and writing extension modules is no problem at all, > just "cleaning" the python sources. My base is Python 2.2.1 Cheers, M. PS: I saw that you x-posted this to python-dev. Please don't do that. -- 93. When someone says "I want a programming language in which I need only say what I wish done," give him a lollipop. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From achim.domma at syynx.de Wed Jul 31 14:07:44 2002 From: achim.domma at syynx.de (Achim Domma) Date: Wed, 31 Jul 2002 20:07:44 +0200 Subject: win32: execute a file just like a double-click References: Message-ID: os.starfile(...) From scrutinizer at gmx.at Wed Jul 24 14:38:38 2002 From: scrutinizer at gmx.at (Francesco S.) Date: Wed, 24 Jul 2002 18:38:38 GMT Subject: Which gui for slow (133 Mhz) pc References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> Message-ID: <3d42f3dc.5866543@news.utanet.at> On 22 Jul 2002 18:35:20, (Dave Brueck) wrote: > (Francesco S.) wrote in message news:<3d3b9eaa.7275472 at news.utanet.at>... >> Hello, >> >> What gui can you recommend for my slow pc (win95). >> >> I was impressed by the Wxpython demo. >> But for developing, the startup speed for a simple hello world app >> with about 10 sec is not acceptable for me. > Hello Dave, thanks for your reply. >Another option is to just do "normal" Win32 GUI programming using the >win32 (Mark Hammond's) Python extensions. Actually, you have 2 >options: you can write Python code that looks nearly equivalent to MFC >GUI code, or you can write Python code that looks nearly equivalent to >C Win32 GUI code. Either way you'll have very fast load times and your >program itself will be quite small (no huge libraries to ship with >it). > That's an alternative. Do I have to compile anything? (I know, stupid question, but I'm an absolute beginner in python, beside, I have a little experience in C/C++ and windows. >The downside of course is that you have to do more of the work >yourself, but I've used this approach in a few programs and it worked >well for me. The extensions come with a few examples to get you >started, and if you have experience writing the equivalent C/C++ code >then development actually goes quite fast. > >Anyway, it's something to consider.. >-Dave Following another thread, Qt seems to be also a very interesting alternative, I don't know now, if I should spend some time to examine the pyqt libraries, but this is another story, I think ... best regards, -- Francesco From bokr at oz.net Thu Jul 18 14:31:53 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2002 18:31:53 GMT Subject: Serial Port Returning Garbage. Why? References: <%gVY8.204$fK3.80978@newsfeed.slurp.net> <786Z8.804$fK3.325642@newsfeed.slurp.net> Message-ID: On Tue, 16 Jul 2002 22:15:48 -0600, bowman wrote: >max wrote: >> >> No, I'm not. It's just Transmit, Receive, and Ground. Our device >> doesn't use any of the other signals, and the implementation doesn't >> use QON/QOFF. Would it make a significant difference if I do? > >It might, if the slave end is a relatively slow device. For instance, the >older SBC UARTs or microcontroller internal UARTs might not be able to keep >up with the transmission, particularly if they have to do something with >each byte as it is received. Usually the receiver will use a DTR signal to Perhaps Max could test the speed theory by slowing down the program output, e.g. by putting time.sleep(0.25) between each character output to simulate something closer to typing speed. If it's not convenient to do that where the characters originate, perhaps it's possible to intercept the output stream and slow things down there. E.g., this uses a simple class to slow down stdout to 4 char/sec: >>> class SlowStream: ... from time import sleep ... def __init__(self, out): self.out = out ... def write(self, s): ... for c in s: ... self.sleep(.25) # simulate typing ... self.out.write(c) ... >>> import sys >>> ss = SlowStream(sys.stdout) >>> sys.stdout = ss >>> print '54321 !' 54321 ! That was slow enough that you can see it, if you try this. Don't forget to restore the old stdout (or whatever stream) >>> sys.stdout = ss.out Oops, I see from a previous post that you are using os.write for output. In that case maybe try just replacing that with, e.g., >>> class SlowOsWrite: ... from time import sleep ... def __init__(self, osw): self.osw = osw ... def __call__(self, fd, s): ... for c in s: ... self.sleep(.25) # ought to be plenty for test ... self.osw(fd, c) ... We'll test with a file instead of the serial port, and hope it works for you ;-) >>> import os >>> fd = os.open('test.txt',os.O_CREAT|os.O_WRONLY) Create the slow writer, which incidentally saves the old os.write function internally >>> sw = SlowOsWrite(os.write) Replace os.write so your other software doesn't see any difference (hopefully) >>> os.write = sw Try it >>> os.write(fd,'write this slowly') That did take a while, at 4 char/sec. Now close it. >>> os.close(fd) We'll have a look using ordinary python file i/o >>> f=file('test.txt','rb') >>> f.read() 'write this slowly' Looks ok. >>> f.close() Look at slow writer and os.write FTHOI >>> sw.osw >>> os.write <__main__.SlowOsWrite instance at 0x007D2040> Restore os.write >>> os.write=sw.osw Note that delays are terrible substitutes for handshakes. I hope you don't have to use anything like the above as a final solution, because most likely it will not be final. But it should help verify that lack of handshake is the problem. >indicate it is busy, and the sender won't start the next byte until the >receiver is ready. I'm assuming by 3 wires, you mean RX, TX and GND, so >even if the hardware handshake is being attempted, it won't be seen across >the cable. > >It is hard to say without knowing your setup. It is possible when you test >with HyperTerminal, you are typing the command in, so it really is sent >very slowly, but in the working system the master sends the command string >much faster and they are getting out of sync. > Hopefully the above will help diagnose this. >Or, it could just be that HyperTerm is setting the start/stop bits, parity, >or something a little differently. I don't think it is the baud rate, since >that usually results in all garbage characters. > Maybe the OP can query the settings while hyperterminal is connected? Regards, Bengt Richter From Jonas at localhost.localdomain Tue Jul 2 12:06:57 2002 From: Jonas at localhost.localdomain (Jonas Geiregat) Date: Tue, 02 Jul 2002 18:06:57 +0200 Subject: Who is the user?? References: Message-ID: On Wed, 03 Jul 2002 17:54:21 +0200, Kristian Sons wrote: > Hi, > > is there a possibility to find out, wich user startet the > python-script?? > > Thanks a lot, > Kristian what you mean ? who invented python ?? From mwh at python.net Tue Jul 30 11:11:07 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 15:11:07 GMT Subject: Finding count of currently open file descriptors. References: <3D469D2F.6010003@truis.com> <3D46A287.9040405@oneofus.org> Message-ID: Tim McNerney writes: > Martin v. L?wis wrote: > > In a Python debug build, you can find out all file objects, but there > > may be file descriptors not controlled by Python file objects (e.g. if > > opened by os.open). > > This is more what I'm looking for -- some generic method which is > within Python itself. How would I go about doing this within the debug > build? In 2.2: sys.getobjects(0, file) The first arg is a limit on how many objects to return, 0 being no limit. The second arg is the type of object to return. In 2.1 I guess it's something like sys.getobjects(0, types.FileType) Cheers, M. -- ... Windows proponents tell you that it will solve things that your Unix system people keep telling you are hard. The Unix people are right: they are hard, and Windows does not solve them, ... -- Tim Bradshaw, comp.lang.lisp From shagshag13 at yahoo.fr Mon Jul 22 10:41:07 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 22 Jul 2002 16:41:07 +0200 Subject: how to delete or change... References: Message-ID: > There are some unknown's here that would be helpful to know. You say > it's a text file but then talk about opening in binary. Is it ASCII? yes, it's an ascii file (i try to open it in binary to do bytes operations instead of lines operations) > How large all the files? Is it feasible for you to work in memory? No, i can't (huge file between 1,5 and 2,5 go) > Also, you say when you tried the binary seek you got an I/O error. > Was there anything informative about that error that you can post? >>> f2 = file('d:/test.txt', 'rwb') >>> f2.seek(-5, 2) >>> f2.read(5) 'TUR\n' >>> f2.seek(-5, 2) >>> f2.write('new') Traceback (most recent call last): File "", line 1, in ? f2.write('new') IOError: (0, 'Error') Maybe i miss something ? thanks in advance, s13. From mfranklin1 at gatwick.westerngeco.slb.com Fri Jul 12 12:59:05 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 12 Jul 2002 16:59:05 +0000 Subject: newbie question: getting rid of space in string :( In-Reply-To: References: Message-ID: <200207121602.g6CG2p727893@helios.gatwick.geco-prakla.slb.com> On Friday 12 Jul 2002 5:52 am, Joseph Youssef wrote: > Hello, I'm new to python and I'm writing a very small script which takes > each letter of a string and adds text to it (I know this is not a good > explanation but you'll understand below :) ) > > anyway, this is my current code: > > def textColor(string, color1, color2): > color = color1 > for a in string: > print "<" +color+ ">" +a+ "", Joseph, The comma at the end of the print statment adds a space to the 'string' you are printing. There are several ways to avoid this, perhaps building the string up then printing it in one go at the end.. like so: def textColor(string, color1, color2): wholeString="" color = color1 for a in string: wholeString=wholeString+"<" +color+ ">" +a+ "" if color == color1: color = color2 else: color = color1 print wholeString as a matter of taste I would use this:- wholeString=wholeString+"<%s>%s" %(color, a, color) but as I say this is a matter of taste! Regards Martin > so when I run let's say textColor("testing","black","red") > it returns: > t e s > t i n > g > > now this works just fine exept that space in between each block of text, I > can't get it to stick together, now I know this is a very easy question but > I need some quick help > > thanks From rajarshi at presidency.com Thu Jul 18 15:50:02 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Thu, 18 Jul 2002 15:50:02 -0400 Subject: smtplib and passwd's References: Message-ID: On Thu, 18 Jul 2002 11:34:25 -0400, Gerhard H?ring wrote: > * Rajarshi Guha [2002-07-18 11:04 -0400]: >> Hi, >> I'm using smtplib to let my script send some mail through my smtp >> server. However I need a logon and passwd for my smtp server - how does >> smtplib handle such servers? Where can I specify my username and >> password? > > import smtplib > > srv = smtplib.SMTP("mail.myprovider.com") srv.debuglevel = 25 > srv.login("myname", "mypassword") > # ... > > You need at least Python 2.2 for this login method to be available. OTOH > backporting SMTP AUTH to earlier Python versions would certainly be > possible. If there are problems, report back to me and I can send you an > improved version (bugfixes, support for old auth advertising, and > additional LOGIN auth method) that will (most likely) end up in Python > 2.3. > Thanks, I moved upto 2.2 :) From spam at ob_scure.dk Mon Jul 8 17:43:38 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Mon, 08 Jul 2002 23:43:38 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <7xwus7n5q4.fsf@ruckus.brouhaha.com> <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> Message-ID: <3D2A078A.7040502@ob_scure.dk> Cameron Laird wrote: > Me, too. While I know quite well how difficult > it is to describe any program that's worth wri- > ting, what we've heard of this one puzzles me. > I'll summarize by saying simply that I'm with > Paul: I *strongly* suspect that database opera- > tions swamp arithmetic operations in elapsed > time, and that attention to the former will be > most rewarding. I have, on purpose, not described the workings of this program in very great detail, since my original post was more about the general idea of using Python for this kind of job. Having easy access to distributed computations is merely a bonus and, if nothing else, a buzz-word to mention to managment *hint*. Furthermore, the ability to scale the application simply gives a good feeling, even if it is *never* needed. > You've mentioned once already that you might do > more with your SQL. I can imagine that much the > greatest returns in performance will come from > writing more of your algorithms in SQL. That's > likely to be a more scalable and satisfying ap- > proach than the multi-processing complexities at > which you've hinted. Satisfying, perhaps, but could you elaborate on scalable? I simply fail to see how it is that distributed computing is so bad? Everybody seems to think that once you make something distributed, every other optimization posibility simply disapear? I never said distributed computing was a priority or even would be a part of the first version. I *is* a design goal however, that should we one day, after all other optimizations in the world, using SQL, need more speed, we can do so by adding machines/CPUs (be it DB servers or application servers). -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From mf at mrinfo.de Thu Jul 25 08:25:06 2002 From: mf at mrinfo.de (Marko Faldix) Date: Thu, 25 Jul 2002 14:25:06 +0200 Subject: Anybody using 4suite for xslt processing? References: <5b4785ee.0207221346.4311877a@posting.google.com> Message-ID: [snip] > Now there is one problem left. Every output is enhanced with > > > ::: Using minidom > > > What's going wrong here? If I want to go in production state, such message > may not appear and isn't it a sort of warning? I found message sys.stderr.write( "::: Using minidom\n") in Ft.Xml.Domlette.py and set # before it. Now everything okay. Thanks for suggestions and help. -- Marko Faldix M+R Infosysteme Hubert-Wienen-Str. 24 52070 Aachen Tel.: 0241-93878-16 Fax.:0241-875095 E-Mail: marko.faldix at mplusr.de From tim.one at comcast.net Sat Jul 13 03:26:05 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 13 Jul 2002 03:26:05 -0400 Subject: Python Embedded Instances In-Reply-To: Message-ID: [Andrew MacIntyre] > I don't believe the Python core in its current form supports separate > interpreter instances in the one application (something I understand Tcl > can support). It does, but only at the C level (you can't create a new interpreter from pure Python code). See the docs for Py_NewInterpreter() in the "Initialization, Finalization, and Threads" chapter of the Python/C API manual. > You may be able to deal with this, if each "instance" is totally distinct, > by using Python threads - the master Python thread starts a thread for > each document. This probably has risks though (globals, preserved state > in some library modules, etc). Those are the kinds of risks Py_NewInterpreter() tries to save you from. See the docs for more. We almost never hear about bugs in this subsystem, which I expect means it's rarely used. From tg5027 at citlink.net Wed Jul 24 16:47:02 2002 From: tg5027 at citlink.net (terry) Date: Wed, 24 Jul 2002 16:47:02 -0400 Subject: Numeric data question In-Reply-To: References: Message-ID: Thanks!!!! >> There's not much point in quoting anything, I'm merely >> writing to suggest the original poster checkout Tim Peters' >> FixedPoint class. I use that for shoving money data into >> PostgreSQL and it works just fine. I don't have a link to it, >> but that's what google's for, right? >> >> Cheers, >> >> // mark >> >> - -- terry From martin at v.loewis.de Mon Jul 29 19:20:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 01:20:05 +0200 Subject: UnicodeError... References: <3D459AE0.5030509@pp.inet.fi> Message-ID: Teemu Luojola writes: > This > problem is dealt in Python FAQ in chapter 4.102. and the following > solution is given: > > > # Set the string encoding used by the Unicode implementation. > > # The default is 'ascii' > > encoding = "ascii" # <= CHANGE THIS if you wish [...] > The problem is, that sys doesn't include setdefaultencoding(). I don't believe you. Did you try to modify this very location in site.py? At that point, sys.setdefaultencoding is still present. > Tell me, please, how to get that Unicode build. I'm pretty sure you have a Unicode build. > When running Python in command line mode, there is no UnicodeError and > print '???' returns the expected result: '???'. Why there is such a > difference? IDLE is written with Tkinter, which returns Unicode strings to the interpreter; the interpreter then needs to convert them into source code (which means byte strings). The command line interpreter reads from the console window, and already gets byte strings - hence no need to convert them. Regards, Martin From dfan at dfan.org Sat Jul 20 08:58:25 2002 From: dfan at dfan.org (Dan Schmidt) Date: 20 Jul 2002 08:58:25 -0400 Subject: text adventure game module for Python References: Message-ID: "Michael Bauers" writes: | Having always been interested in languages for doing text | adventures, I thought Python was the perfect match. You might want to look at PAWS, a text adventure system implemented in Python. Comparisions of 12 different systems can be found at . Text adventures are alive and well, with dozens being released every year. Check out the rec.arts.int-fiction and rec.games.int-fiction newsgroups. Dan -- http://www.dfan.org From cce at clarkevans.com Thu Jul 4 14:40:04 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Thu, 4 Jul 2002 14:40:04 -0400 Subject: Thanks ... and how to express them. In-Reply-To: <3d2479ba$0$24410$afc38c87@news.easynet.co.uk>; from chris.lyon@spritenote.co.uk on Thu, Jul 04, 2002 at 05:36:09PM +0100 References: <3d2479ba$0$24410$afc38c87@news.easynet.co.uk> Message-ID: <20020704144004.A41918@doublegemini.com> On Thu, Jul 04, 2002 at 05:36:09PM +0100, chris lyon wrote: | Just a question of etiquete. I have recieved beneficial help | form individuals do I thank on the list or not? Helping others is the best repayment one could give. Clark From mwh at python.net Wed Jul 24 09:53:02 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 24 Jul 2002 13:53:02 GMT Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> Message-ID: "Keith S." writes: > Alex Martelli wrote: > > > QLineEdit handles (and returns) a single line, right? Therefore, how > > can you use it to input a multi-line command? > > True, although you can do this in the Python interactive > shell, so I presume there *is* a way of doing it. One way of finding out how is to look at the source. I seem to recall that this is a bit hairy, so another way is to look at the standard code.py or codeop.py library modules. Either call them from C or do the same work in C. > > Why not use a multiline editing widget instead? > > Because I'd really like it to work just like the interactive > shell if possible... But you WANT multiline editing if you can get it... have you looked at PyCrust? Oh hang on, that's wx, not Qt, isnt' it? Ne'er mind. Cheers, M. -- CLiki pages can be edited by anybody at any time. Imagine the most fearsomely comprehensive legal disclaimer you have ever seen, and double it -- http://ww.telent.net/cliki/index From claird at starbase.neosoft.com Fri Jul 12 12:09:35 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 12 Jul 2002 11:09:35 -0500 Subject: automating command line program References: Message-ID: <53ECD90BC83218DE.C6B2FF546410C2DC.C31C4455CB99EF00@lp.airnews.net> In article , Mark McEahern wrote: >I'm fairly new to python and I've been trying to automate the usage >of a command line prompt program and I'm able to successfully run the >application from command line but once the program has launched, I'm unable >to enter anymore commands into the program. I've basically just tried using >os.system, os.popen, and print statements. Is there other python commands >that will allow me to do this? I've looked around the web and I've found a >module, Expect, that may be able to help me but I'm unable to find a windows >version of this module for python. Any help is appreciated, thank you. >Victor > >Could you please be more specific? What is it you're trying to do? What >specifically have you tried? What specifically isn't working? . . . Myself, I thought he made it clear enough. He's made some progress with os.popen; now he needs to be told about os.popen2 (and possibly os.popen3--my guess is that's unlikely, though). Victor, look those up in whatever documentation you're using. I suspect you'll find they give you everything you're after. Are there any warnings about popen2 under Windows Victor should hear? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From peter at engcorp.com Mon Jul 8 21:07:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 21:07:21 -0400 Subject: Help with Popen in 2.2 References: Message-ID: <3D2A3749.2BBA7545@engcorp.com> Lowel Stern wrote: > > fp = os.popen('prog "stern:STWA" 1234') > > the above works fine. The quotes must be as shown they may not be > changed. The problem is I need to be able to change programatically > the section "stren:STWA" and the 1234 section I have not figured a way > to do the substitution yet any ideas. Do you know about the % operator? >>> 'prog "%s" %s' % ('stern:STWA', 1234) 'prog "stern:STWA" 1234' >>> userpass = 'phansen:secret' >>> port = 567 >>> 'prog "%s" %s' % (userpass, port) 'prog "phansen:secret" 567' Does that help any? -Peter From sasoft at gmx.de Tue Jul 30 08:53:03 2002 From: sasoft at gmx.de (Stefan Antoni) Date: Tue, 30 Jul 2002 12:53:03 +0000 Subject: re question (perhaps a stupid misunderstanding of regex-logic) Message-ID: <20020730125303.GA2149@blackscarab> i am currently reading Jeffrey E. F. Friedl's book about regex'es, and i must admit that i play more with the re-module then reading further on ;) thats why i ask the following question: i made the following regex: m = re.compile("[^M]*") i think, it would be read as: "find everything except the occurences of the char 'M' " . i wrote the following code: all = string.letters + string.digits + string.hexdigits + \ string.whitespace M = re.compile("[^M]*") M.findall(all) ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL', '', \ 'NOPQRSTUVWXYZ01234567890123456789abcdefABCDEF\t\n\x0b\x0c\r ', ''] this gives me a list with an empty item at [1] of the list. the documentation says: "findall: Find all occurrences of a pattern in a string." since the ^M is a negated char (german "negiert", i don't know if negated is right), the regex-object shouldn't give me an list-item for this match, or should it? what am i missing? thx in advance, -- Stefan Antoni -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 240 bytes Desc: not available URL: From max at alcyone.com Mon Jul 29 21:05:41 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 29 Jul 2002 18:05:41 -0700 Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 References: Message-ID: <3D45E665.3C34CDF@alcyone.com> Steve Drake wrote: > >>> xmlText=""" > > > Text > """ Looks like a typo to me. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From shagshag13 at yahoo.fr Wed Jul 24 13:33:12 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 24 Jul 2002 19:33:12 +0200 Subject: xml processing : too slow... References: Message-ID: "Alex Martelli" a ?crit dans le message de news: M6A%8.132311$vm5.4357332 at news2.tin.it... > So you need EACH separate line to be a well-formed XML document > in its own right, or else include no closing-tag? I'm confused. In fact, i'm wondering if i'm not using wrong tool (with minidom)... What i need here and which took a while with dom is to * check well formedness * process each line which are like this: 1 2 3 -> to have: ['', '', '1', '2', '', '', '3', '', ''] s13. From pyth at devel.trillke.net Thu Jul 25 04:23:21 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 25 Jul 2002 10:23:21 +0200 Subject: A better self In-Reply-To: ; from j_r_ashley@MAKGifts.com on Thu, Jul 25, 2002 at 05:44:36AM +0000 References: Message-ID: <20020725102321.J10625@prim.han.de> James Ashley wrote: > In article , Bengt Richter wrote: > > On Wed, 24 Jul 2002 08:34:33 GMT, Alex Martelli wrote: > >>should coding in lower levels be considered (on the other > >>hand, protectionist legislation shouldn't be considered even then, > >>but that's another issue:-). > >> > > What are you protecting with that "shouldn't"? ;-) > > Perhaps that was a "generally, any sane person won't, but sometimes > bueracracies insist upon insanity" kind of generalization? > > > > ISTM everyone believes in protectionism, only differing in their > > ideas of what to protect and how to do it ;-) > > ROFL...nicely said. I've thought up a few responses to this, and I'm > curious about your answer to them all, but they all seem to whirl around > politics rather than software development, and, therefore, are even more > off-topic than I'm willing to get on this sort of forum. Don't bother. This thread is already ridicously long and anyone still reading it has probably gotten to a very open mental self.state self.regards() From is at gras.de Mon Jul 15 08:25:49 2002 From: is at gras.de (Ingo Stöcker) Date: Mon, 15 Jul 2002 14:25:49 +0200 Subject: objects in a list ... Message-ID: Hey. I am a newbee @ python. For a little application-project I have a questions to you: I want to create many Objects of a class designed by my own and these objects should be stored/append in/on a list. Is this possible and how can I realize it? Thanx & Sorry for my bas englisch :-) Regards Ingo From whisper at oz.net Fri Jul 26 18:18:23 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Jul 2002 15:18:23 -0700 Subject: calendar lameness! In-Reply-To: <1027715640.10236.200.camel@vaio2> Message-ID: For less constrained calendrical calculations, I found this: http://www.funaba.org/en/calendar.html with a python binding no less! I also discovered that "calendar" "calendar software" and "calendar software library" will get you little of practical use, but the elegant term "calendrical calculations" does well :-) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Andreas Kostyrka > Sent: Friday, July 26, 2002 13:51 > To: Terry Hancock > Cc: python-list at python.org > Subject: Re: calendar lameness! > > > Am Mon, 2002-07-22 um 15.35 schrieb Terry Hancock: > > "calendar" is pretty neat -- except it has pretty > > annoying arbitrary limits on the date: > > > > 1900-1/1 to 2038-1/18 > Well, this is not that arbitrary. Considering the fact that the > "calendar" wasn't standardized completly the beginning of the 20th > century. So anything that goes that far back would have to specify the > country (or even the substate in the country) to be precise. And that > doesn't even take into account that the French Revolution tried to do > away with the 7-days week, ... > > > I can see that this is adequate for a business > > planner, but for historical or astronomical uses, > > it's really inadequate. (e.g. "What day of the > > week was the US Declaration of Independence signed > > on?" I'm sure I could look that up, but gee it > > would've been nice to just type: > > > > calendar.weekday(1776, 7, 4) > calendar.weekday(1776,7,4,"USA") > > > Actually, it looks like maybe it's "mktime" that > > is the limiter here (?). How hard would it be to > > replace that call with something smarter? It seems > > like Python longs would make it unnecessary to > > have such arbitrary limits. > Well, it's not that much a limit of calculating power, it's more that > the subject of calendars is difficult. By using the underlying C library > implementation the Python implementers don't have to think about these > political and religious considerations. ;) > > Andreas > > > -- > http://mail.python.org/mailman/listinfo/python-list From skip at pobox.com Fri Jul 19 10:02:57 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Jul 2002 09:02:57 -0500 Subject: i++ in Python? In-Reply-To: <5606b639.0207181855.48496f5a@posting.google.com> References: <5606b639.0207181429.2c6d2569@posting.google.com> <3D37429C.53BC0FDB@engcorp.com> <5606b639.0207181855.48496f5a@posting.google.com> Message-ID: <15672.7185.44940.51660@localhost.localdomain> otis> I don't like the fact that if 'j' is some kind of a global counter otis> variable, and I'm dealing with multiple threads, it is then, I otis> believe, possible for 2 or more threads to execute i = j at the otis> same time (i.e. before 'j' had the chance to increase). That's what locks are for. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From mwh at python.net Mon Jul 29 06:42:37 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Jul 2002 10:42:37 GMT Subject: xrange questioin References: <3d43234e$1@duster.adelaide.on.net> Message-ID: "Fredrik Lundh" writes: > Gerald Squelart wrote: > > > Ok, let me rephrase Chris' question for a simpler case: > > What is better: for x in range(n) or for x in xrange(n)? > > (with n is relatively small, like 10 or 100) > > for in range() is usually a few percent faster, but if you do some- > thing inside the loop, you'll hardly notice the difference. Is this still true in the iterators age? I guess I should go look... Cheers, M. -- nonono, while we're making wild conjectures about the behavior of completely irrelevant tasks, we must not also make serious mistakes, or the data might suddenly become statistically valid. -- Erik Naggum, comp.lang.lisp From cliechti at gmx.net Wed Jul 24 08:47:10 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 14:47:10 +0200 Subject: Function wrapper a la Perl's Hook::WrapSub? References: <3D3E9F34.90FB8B3F@cs.uu.nl> Message-ID: "Gerard A.W. Vreeswijk" wrote in news:3D3E9F34.90FB8B3F at cs.uu.nl: > Hi there, > > I very much would like to have a Hook::WrapSub (Perl) module for > Python. What does it do? Well, read is so simple that is not in a module : >>> class Wrap: ... def __init__(self, callable, before=None, after=None): ... self.before = before ... self.after = after ... self.callable = callable ... def __call__(self, *args, **kwargs): ... if self.before is not None: ... self.before(args, kwargs) ... result = self.callable(*args, **kwargs) ... if self.after is not None: ... self.after(args, kwargs, result) ... return result ... >>> def log(a, k): ... print "called with args:", a, k ... >>> def result(a,k,r): ... print "result:", r ... >>> def f(x): ... return x+1 ... >>> w = Wrap(f, log, result) >>> w(27) called with args: (27,) {} result: 28 28 >>> chris -- Chris From huaiyu at gauss.almadan.ibm.com Thu Jul 18 14:36:52 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 18 Jul 2002 18:36:52 +0000 (UTC) Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: Clark C . Evans wrote: >On Tue, Jul 16, 2002 at 10:14:51PM +0000, Huaiyu Zhu wrote: > >| There are facilities for conversion among the data structures: set, seq, >| dict, seqdict, with various specifications. I do not see how yaml indicates >| the types of structures. > >YAML does this with the bang (!) you can see this in the preview >for type family (http://yaml.org/spec/#preview-family) and also >in the transfer method section (http://yaml.org/spec/#syntax-trans) It appears that the bang is used to indicate any types. I found it better to separate structural types (seq, dict, ...) from terminal types (str, int, date and time, ...). The former is finite in number and predefined (at any moment in time, at least), and necessary for all the navigation tools that traverse the data structure. The latter is numerous, application dependent, and should be considered as blackboxes by the generic tools. I'd suggest grouping all the structural types together in one section and describe their semantical relations. Also group all the terminal types together in one section and indicate that they are only first examples for endless possibilities. All in all I find YAML quite impressive. Congrats on an excellent job in documenting and promoting it, unlike me, who let things fizzle and rot. Huaiyu From rnd at onego.ru Tue Jul 30 04:15:29 2002 From: rnd at onego.ru (Roman Suzi) Date: Tue, 30 Jul 2002 12:15:29 +0400 (MSD) Subject: Unicode classes of characters in Pythons' re's like in Perl? Message-ID: Hello! Reading XML Schema docs I found that there are some useful extensions to regular expressions like an ability to specify class of characters. For example, [\p{Lu}] will match any uppercase letters. Is the feature planned in Python re too? Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From fredrik at pythonware.com Wed Jul 10 05:51:14 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jul 2002 09:51:14 GMT Subject: Deriving from Exception References: <3d2bf4b6.183387921@news.skynet.be> Message-ID: "pixie888 at hotmail.com" wrote: > I have some classes which derive from Exception, however in the > __init__ function I do not call the __init__ function of Exception > itself, allthough I think I should. The reason I don't do it is > because I see that in all the tutorials about Python the tutors > themselves don't do it either. > > Can anybody tell me why? The Exception baseclass provides an __init__ method which takes all arguments and puts them in an args attribute. It also provides default __str__ and __getitem__ methods, so you can print the exception, and use the v[x] notation to access the members. In Python, the class would look something like this: class Exception: def __init__(self, *args): self.args = args def __str__(self): if not self.args: return '' elif len(self.args) == 1: return str(self.args[0]) else: return str(self.args) def __getitem__(self, i): return self.args[i] If this behaviour is fine for your exception subclass, there's no need to override anything. From b_mcerlean at yahoo.com Sat Jul 6 10:23:45 2002 From: b_mcerlean at yahoo.com (Brian McErlean) Date: 6 Jul 2002 07:23:45 -0700 Subject: Why self? References: Message-ID: "Matt Gerrans" wrote in message news:... > > In Python, I think the required "self" reference in methods is a case where > the solution is worse than the problem it solves. Since indentation is the > method of scoping in Python, this addition of five characters to each > instance variable is particularly annoying -- a one-line statement that > contains several instance variables can easily become unmanageable. > > It's a bit like that horrible blight on the programming community called > "Hungarian Notation" that needlessly polutes code with incomprehensible > variable prefixes so that you know your string is really a long pointer to a > zero terminated array of signed 8-bit characters. As if you cared, or > needed to be constantly innundated with such superfluous information. > Fortunately, the Hungarian Notation investation has for the most part been > limited to Microsoft's C and C++ APIs and thier usage, but hasn't infected > others -- and nowadays it even seems to be on the decline in Redmond (C# > examples are generally free of it). I don't entirely agree. The thing that really irritates me about hungarian notation is that you're mangling the human readable names of things to provide information that is related to the internals of the language. The name of a variable should tell me what its for, not what or where it is. Conventions like "m_" are in some ways worse - now you're abusing the names to resolve language namespace issues. On the other hand, I think that "this->" and "self." are the right way. You are using the language to say what you mean, not mangling names to get the same effect. > I never had a much of problem in C++ with distinguishing member variables > from local variables and I never liked those cheesy ("Some cheese, please, > my good man!") conventions of always using "m_" or "this->". If you keep > your methods small and clean, you don't need all this slop. > > However, since Python doesn't have declarations, some method is required to > distinguish whether an assignment in a class's method is an assignment to a > instance variable or a local variable. I prefer the solution of simply > making it illegal to have local variable names match class variable names. > Hmm... this doesn't help with the problem of globals, but there is a keyword > for that. This leads to the same problem. Its pretty common for constructors to take arguments that correspond directly with instance variables. eg. class AddressBookEntry: def __init__(self, name, address): self.name = name self.address = address Under your situation, I can't just omit self, since then there would be instance and local variables with the same name. The only thing I can do is to mangle either my instance variables or my arguments. I'm back to having to append "_arg", or "_i" to my variables. In any case, in a language like python, what you suggest may be infeasible anyway. Methods can add instance variables at will, so assignment at least would have to use self. to distinguish between using a new local variable. Brian. From aleax at aleax.it Sun Jul 7 16:32:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 20:32:27 GMT Subject: Why isn't this a bug? References: Message-ID: Russell Blau wrote: ... > Of course, if someone would like to explain why something so simple and > intuitive is a "bad idea," please enlighten me. ;-) I suspect the general idea is that having, say, print L display perfectly identical results for many different lists, such as [ '1.5' , '3' ] [ '1.5, 3' ] [ 1.5, 3 ] and so on, is considered just too prone to causing confusion. Alex From aleax at aleax.it Mon Jul 8 18:09:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 22:09:44 GMT Subject: Memory ? References: Message-ID: Shagshag13 wrote: ... > I have a data structure like this : > > key_0 -> value_0_? -> value_0_? -> ... value_0_m > key_i -> value_i_? -> value_i_? > ... > key_n -> value_n_? -> value_n_? -> value_n_? -> value_n_? > > where : > > - key are characters, You presumably mean strings -- you can't have 2,500,000 different characters (character == string of length 1, in Python). > - value are float > - n > 2,500,000 > - value "list" can have length from 1 to m = ~1,000,000 (values from key_i > could be 1 long, while key_i+1 could be 1,000,000) - i didn't knew exact > value for n (it depends on input data) - i can guess m > > by now i use a dict index for key, which give me access to a queue (list) > containing my values. that's really to slow !!! "queue"...? > with your helps, i think i should use a numeric.array for my values list, > but i even wonder if i shouldn't use a matrix (2,500,000 * 1,000,000) even Where are you going to find the 20+ terabytes to keep that mostly-empty matrix in...? Builtin module array may be suitable for your highly specialized need, and it does have the advantage of implementing an .append method on array.array objects, simplifying your code a bit. You probably need to benchmark both array.array and Numeric.array and check, but you're apparently not using Numeric's strengths here. Oh, and, be sure to use 4-byte floats (both array and Numeric support them) if that precision is enough for you -- that would halve the memory compared to the usual "double precision" (8-byte) floats. Alex From dreed at capital.edu Wed Jul 17 15:25:58 2002 From: dreed at capital.edu (Dave Reed) Date: Wed, 17 Jul 2002 15:25:58 -0400 Subject: python2 import trouble (linux - redhat) In-Reply-To: <1026930878.3325.1.camel@jwilhelm.ofsloans.com> (message from Joseph Wilhelm on 17 Jul 2002 11:34:37 -0700) References: <20020714141757.128895ce.mmellor1@yahoo.com> <3D35A628.A9ADF9B6@noaa.gov> <1026930878.3325.1.camel@jwilhelm.ofsloans.com> Message-ID: <200207171925.g6HJPwH29747@localhost.localdomain> > From: Joseph Wilhelm > > > #!/usr/bin/python2.2 > > (or whatever version) > > for their admin tools. > > > > The point is that the problem with redhat has not been that it uses > > 1.5.2. but that all the admin tools require 1.5.2 to by what "python" > > invokes. If they has specified the version on thei #! lines, then it > > would be no problem to install newer versions as well, and they probably > > would ahve provided packages to do so as well. > > > > If all they have done is upgrade to 2.2 or whatever, then we'll all have > > the same problem in a another year or two :-( > > > > -Chris > > Actually, if I remember right from when I was browsing the package list, > Python 2.2 was the -only- version they provided. So "In Theory", they > have completely deprecated 1.5.2. > > --Joseph Wilhelm I think Chris' point was unless they hard coded /usr/bin/python2.2, the same issue will occur when Red Hat 8.2 is out with Python2.2 but the latest version of Python is 2.4 or whatever. I haven't figured out exactly how Red Hat's configuration programs work. They all appear to be a link to /usr/bin/consolehelper so it must do something using argv[0] and call the appropriate program. I'm interested in learning how their programs ask for the root password and then run as root. In the beta (limbo) The first line of /usr/share/printconf/util/printconf_gui.py is #!/usr/bin/python so it looks to me like the same problem will occur. Dave From kurugant at denshi.ece.utk.edu Mon Jul 22 14:11:11 2002 From: kurugant at denshi.ece.utk.edu (Teja Sastry) Date: Mon, 22 Jul 2002 14:11:11 -0400 Subject: Sockets for a file Message-ID: <3D3C4ABF.4040905@denshi.ece.utk.edu> Hi, I would like to know if we can create a unix socket for a file (like we do in C or C++ with struct sockaddr_un) I want to wait on a file in python and trigger some function if the file gets some data written in it by another program. Please clarify if anybody has worked on this previously. Thank you, Yours Truly, Teja Sastry From b.maryniuk at forbis.lt Tue Jul 9 06:38:24 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 12:38:24 +0200 Subject: [OT] Corrections about Java In-Reply-To: <20020709102106.GA1792@lilith.my-fqdn.de> References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091157.18646.b.maryniuk@forbis.lt> <20020709102106.GA1792@lilith.my-fqdn.de> Message-ID: <200207091238.24900.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 12:21, Gerhard H?ring wrote: > No, endless loop in my JVM, too. Btw. Python sorts this out in that > continue inside a try-block is illegal. I know. But it's also *illegal* to try loop break, then go continue. > > > Btw. Python had a similar problem in 2.0, IIRC. > > At least Python 1.5 no. > Wow, do you drive an antique car, too? ;-) No, but Python 1.5 on our few OLD production servers, where theirs beurocracy does not allow to upgrade it. :-) -- Sincerely yours, Bogdan M. Maryniuck Fatal Error: Found [MS-Windows] System -> Repartitioning Disk for Linux... (By cbbrown at io.org, Christopher Browne) From fredrik at pythonware.com Sat Jul 27 03:48:48 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 07:48:48 GMT Subject: how to count lines in a file ? References: Message-ID: Tim Peters wrote: > That isn't "a change", though. These three have always been true, and still > are: > > 1. CPython uses refcounting. > > 2. Jython doesn't. > > 3. Python's Language Reference manual doesn't define when unreachable > objects are collected, and explicitly warns that an implementation > may even choose never to collect unreachable objects; it "strongly > recommends" to invoke close()-like methods rather than just hope. > > None of those are likely to change, either . on the other hand, I see no reason why the Jython implementation shouldn't make a "best attempt" to flush file buffers when the inter- preter exits in a controlled fashion. cpython guarantees this (thanks to stdio), so why cannot jython try a little harder? how many lines of code can it take? twenty? From shagshag13 at yahoo.fr Tue Jul 23 12:54:45 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 23 Jul 2002 18:54:45 +0200 Subject: how to count lines in a file ? References: Message-ID: "Chris Liechti" a ?crit dans le message de news: Xns9254BFA8ABAABcliechtigmxnet at 62.2.16.82... > "Shagshag13" wrote in > news:ahk020$tl4ue$1 at ID-146704.news.dfncis.de: > > > i need to count lines in a file (that i *can't* keep in memory, so > > can't use readlines()) > > but you can use xreadlines, or a bit nicer in Py2.2 where "file" is an > iterator. i use file because i read this in documentation : open(filename[, mode[, bufsize]]) An alias for the file() function above. does xreadlines will speed my function ? thanks, s13. From chris.lyon at spritenote.co.uk Sat Jul 6 13:34:41 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Sat, 6 Jul 2002 18:34:41 +0100 Subject: are win32com definitions from adovbs.inc accessible to Python or do I have to transcode them? Message-ID: <3d272a2b$0$4298$afc38c87@news.easynet.co.uk> I'm using Python 2.1.2.12 with ADO and am wondering if anyone has a way of encoding the defined constants in adovbs.inc or do I have to look them up myself (error prone) or do I encode the package myself (noble but the deadline approaches) ? Sorry if this seems a bit cheeky, if theirs a more appropriate mailing list for these question please point me at it. Chris Lyon From ifls at rz.tu-clausthal.de Wed Jul 31 03:36:32 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 31 Jul 2002 07:36:32 GMT Subject: alternatives to getopt? References: Message-ID: Francisco Borges wrote: : I've just started using getopt and I'm not very fond of it. Is there a : better alternative to it? How about Optik? http://optik.sourceforge.net/ Lutz From pixie888 at hotmail.com Tue Jul 16 04:12:08 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Tue, 16 Jul 2002 08:12:08 GMT Subject: Webware 0.7/Singleton pattern References: Message-ID: <3d33d51a.410514562@news.skynet.be> Read the following links for a singletondiscussion in Python http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 http://www.aleax.it/Python/5ep.html Henk On 16 Jul 2002 00:45:41 -0700, mbub at meta-level.de (Michael Bub) wrote: >Hi folks, > >I am currenty working on my diploma thesis. I chose to use Webware and >Python to build my WebApp. > >During the development it turned out that some classes should become >singletons. >I implemented all my singleton classes with the following code: > >class myClass: > > __instance=None > > def __init__(self): > # init stuff > pass > > def get_instance(): > if myClass.__instance is None: > myClass.__instance=myClass() > return myClass.__instance > get_instance=staticmethod(get_instance) > >This generally seems to work just fine when using it. However, in my >WebApp built with Webware 0.7 (using Python 2.2 on a FreeBSD4.4 >system), the second or third time the get_instance method is called, >the one instance that was created by the singleton seems to be >forgotten about (or rather, it seems as if the file that holds the >class definition was imported and used for the very first time) and >another one is created. This, of course, sucks. I do not know where >the first one goes, its __del__ does not get called during that >process, but it is replaced by the second instance created by the >singleton. after that has happened, everything is back to normal and >the singleton classes behave as expected and do not create any new >objects. > >does anyone know how to get "safe" singleton classes to get rid of >that problem? > >-- >Michael From jb at hotmail.com Wed Jul 24 12:45:07 2002 From: jb at hotmail.com (JB) Date: Wed, 24 Jul 2002 18:45:07 +0200 Subject: GUI toolkits References: <85adoh5mj5.fsf@axis.localdomain> Message-ID: <3d3ed7bd_7@news.newsgroups.com> Jolly Roger wrote: > I think Windows software using Qt ("non-commercial") can > be distributed under BSD or LGPL (or similar) license, but > not under the plain unmodified GPL. If GPL is a must, it's > possible to add a clause to the GPL which, I think, > exempts the recipient of the software from having to > redistribute Qt source code with the application. > Something like that anyway. The only problem being, that Trolltech's commitment to that non-commercial version is not clear. -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From bokr at oz.net Thu Jul 18 15:40:13 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Jul 2002 19:40:13 GMT Subject: raw_input References: <3D36C5F1.9C966A8F@millfilm.co.uk> Message-ID: On Thu, 18 Jul 2002 14:43:13 +0100, Eric Texier wrote: >It's there anything better than raw_input to query a string >input from the user in a console window. What improvement do you have in mind? Regards, Bengt Richter From claird at starbase.neosoft.com Sun Jul 7 16:29:25 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 7 Jul 2002 15:29:25 -0500 Subject: how to disable maximize button? References: Message-ID: In article , David LeBlanc wrote: >IIRC, Tk itself has the capability to trap the quit button on the window, >and that _should_ be the same mechanism to catch a click on any of the >window "system" buttons. (This pertains to MS-Windows.) > >In general terms, for MS-Windows, you have to set a handler to capture the >WM_SYSCOMMAND message and the wparam arg will have the type of action >(minimize, maximize, quit etc.) that's being passed. > >Tk has a means to set a handler for what it calls protocol events, but after >reading the Tk code itself, it only seems to work with WM_DELETE_WINDOW - >which curiously, isn't a standard MS-Windows event name! I tried setting an >event handler for WM_SYSCOMMAND in Tkinter, but it never fired (also, there >seems to be no way to get args passed with the event). . . . I think we're confusing each other. Or maybe the software's doing it to us both. It would make sense for the same protocol handler to manage all the little buttons. It doesn't, though. Tk originated historically under X, or, more broadly, ICCCM. According to the experts in , there simply is no cross-platform definition for much of what's requested. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jepler at unpythonic.net Wed Jul 3 10:45:00 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 3 Jul 2002 09:45:00 -0500 Subject: Thread safetyness in Python In-Reply-To: References: Message-ID: <20020703144500.GB32161@unpythonic.net> On Wed, Jul 03, 2002 at 02:12:39PM +0000, Gerhard Haering wrote: > John Goerzen wrote: > > 1. In C, a++ would be atomic because CPUs have an atomic increment > > operation, in most cases. > > What about SMP systems? Being one instruction is not enough to be atomic in SMP systems. For instance, quoting from "AMD x86-64 Architecture", Volume 1, page 90: Lock Prefix. The LOCK prefix causes certain read-modify-write instructions that access memory to occur atomically. The mechanism for doing so is implementation-dependent (for example, the mechanism may involve locking of data-cache lines that contain copies of the referenced memory operands, and/or bus signaling or packet-messaging on the bus). The prefix is intended to give the processor exclusive use of shared memory operands in a multiprocessor system. The prefix can only be used with forms of the following instructions that write a memory operand: ADC, ADD, AND, BTC, BTR, BTS, CMPXCHG, CMPXCH8B, DEC, INC, NEG, NOT, OR, SBB, XADD, XCHG, and XOR. An invalid-opcode exception occurs if LOCK is used with any other instruction. (this is largely the same for plain 'ol x86, but that's from the manual I have at hand) This means that if two processors are executing 'INC' at about the same time, the R-M-W steps could take place like CPU0 CPU1 Read 0 Read 0 Modify Modify Write 1 Write 1 Only 'LOCK INC' will ensure that the operation takes place in an atomic fashion. Of course, 'LOCK INC' is bad for performance, and a compiler won't generate it for every increment instruction. Some standard has defined "atomic_t" and "sigatomic_t" integral data types which have the desired behavior. I don't know offhand if this is ISO C, POSIX, or something else, though. Jeff From martin at v.loewis.de Wed Jul 31 02:54:25 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Jul 2002 08:54:25 +0200 Subject: Debug version crashing... References: Message-ID: tALSit de CoD writes: > 1) a small .exe loads the .dll and calls the main init() function > 2) the dll starts up some services, among them Py_Initialize () > 3) i tell python to execute: execfile("kikura.py") (kikura.py is the file > that SWIG generates for the shadow classes) > > All this works in the release version, but in the debug version i get this > error message along with an assert failure: > Fatal Python error: Interpreter not initialized (version mismatch?) Could it be that you are loading python22.dll instead of python22_d.dll? Regards, Martin From marklists at mceahern.com Fri Jul 5 10:08:13 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 5 Jul 2002 09:08:13 -0500 Subject: deleting a file In-Reply-To: <3D25A807.3070006@denshi.ece.utk.edu> Message-ID: import os os.remove(filename) // m - From altis at semi-retired.com Mon Jul 8 12:40:20 2002 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 8 Jul 2002 09:40:20 -0700 Subject: Full-screen display in Tkinter References: <21298535.0207040554.6caeed01@posting.google.com> Message-ID: Just an FYI that PythonCard http://pythoncard.sourceforge.net/ comes with a slideshow sample that displays images in a window or full screen. The version in cvs that will be in the next release can also display HTML. PythonCard uses wxPython, not tkinter, so it doesn't solve your tk needs, but wxPython/PythonCard is cross-platform. ka --- Kevin Altis altis at semi-retired.com "Svein Brekke" wrote in message news:21298535.0207040554.6caeed01 at posting.google.com... > I am building a slide show application with Tkinter, and need > to create a full-screen window, i.e. supressing title bar > and start menu etc. > > Is that supported in Tkinter? > I work on Win2000 with python 2.2, but would like my code to > be portable to other platforms. > > Any help or hints will be appreciated. > > Svein Brekke From K.Rdt at TU-Berlin.DE Mon Jul 1 09:53:15 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Mon, 01 Jul 2002 15:53:15 +0200 Subject: wxFont-question In-Reply-To: Message-ID: <87UTPZVDADBE9H7D0WSZU72NLQLI.3d205ecb@FRITZweb> Am 01.07.02 14:58:42, schrieb Vadim Zeitlin : >On Mon, 01 Jul 2002 12:29:56 +0200, Klaus Reinhardt wrote: >> I want to change the font to equal letters, > > If I understand you correctly, you need the font family of wxTELETYPE and not >wxMODERN. > > Regards, --------------------------------------------------------------------- Hi f=wxFont(22,wxTELETYPE,wxNORMAL,wxNORMAL,1) f.SetFamily(wxTELETYPE) NO change. These 'things' seem to work, cause I can test with GetFamily a.s.o. But the appearance of the font is the same (pro letters). K at Rdt --------------------------------------------------------------------- From jdhunter at nitace.bsd.uchicago.edu Fri Jul 26 11:30:05 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Fri, 26 Jul 2002 10:30:05 -0500 Subject: tarfile.py question References: <3d41619d$1_2@nopics.sjc> Message-ID: >>>>> "Adonis" == Adonis writes: Adonis> i attempted to read a tar.gz file (gadfly) and when i load Adonis> it no error is posted nor any information at that, but the Adonis> m variable is an empty list, and if i attempted to do Adonis> x.list() to get a list of files it returns None, although Adonis> it seems that it loaded the tar file properly no IOError Adonis> was generated, is there something i am missing? i have Adonis> tested this by generating a tar.gz file using the same Adonis> module and it unpacked properly. Since it works for one tar file and not another, you may want to make sure the gadfly tarfile is valid. You can get a copy of GNU tar and gzip for DOS to do this. If you transferred the tar file via command line ftp and forgot to type 'binary', it could be corrupt. John Hunter From dig.list at telkel.net Tue Jul 30 07:08:24 2002 From: dig.list at telkel.net (DIG) Date: Tue, 30 Jul 2002 06:08:24 -0500 Subject: signature for a file ? In-Reply-To: ; from "Shagshag13" on Tue, Jul 30, 2002 at 12:13:31PM References: <7xeldlh6o8.fsf@ruckus.brouhaha.com> Message-ID: <20020730060824.D4976@lifebook> Hi, Shagshag13 ! On Tue, Jul 30, 2002 at 12:13:31PM +0200, Shagshag13 wrote: > "Paul Rubin" a ?crit dans le message de news: 7xeldlh6o8.fsf at ruckus.brouhaha.com... > > > > Anyway if two files have the > > same MD5 checksum, it's basically certain that the files are > > identical. > > thanks for this, (so no need to use SHA or CRC ?) Practically -- no. > > So your basic strategy is: > > > > for each file in your system: > > c = md5 checksum of the file > > print c and the pathname leading to the file > > > > Then take the output of the above and sort it so all the identical md5's > > end up next to each other in the output. > > > > Then find all the sets of files with identical md5's and print out their > > paths so you can investigate further, get rid of one copy, etc. > > yes, i would like to do something like that ! And if you take into account the size of file, you will not have to run md5sum on EACH file. It will be sufficient to check with md5sum whether the files are identical ONLY IF their sizes are the same. Regards, -- DIG (Dmitri I GOULIAEV) From jepler at unpythonic.net Thu Jul 18 07:52:23 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 18 Jul 2002 06:52:23 -0500 Subject: Pmw Inconsistencies -- Any ideas ?? In-Reply-To: References: Message-ID: <20020718065217.A1702@unpythonic.net> On Thu, Jul 18, 2002 at 08:06:35AM +0000, Mike MacDonald wrote: > ##Error message: > ## Traceback (most recent call last): > ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 1, in ? > ## import Pmw > ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 11, in ? > ## root=Pmw.initialise() You're bound to have problems when you have two modules with the same name. Here, it looks like you're running the file "Pmw.py" which tried to import the module "Pmw". Jeff From jonathan at onegoodidea.com Thu Jul 25 11:33:00 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 25 Jul 2002 16:33:00 +0100 Subject: Speed up Python by up to 5% ? References: Message-ID: On 25/7/2002 16:14, in article CBU%8.25126$fH5.25050324 at kent.svc.tds.net, "Edward K. Ream" wrote: > Still, this might be a real savings. What do you think? Make the change, run some benchmarks, show us the results ;-) Jonathan From altis at semi-retired.com Wed Jul 17 18:31:49 2002 From: altis at semi-retired.com (Kevin Altis) Date: Wed, 17 Jul 2002 15:31:49 -0700 Subject: ANN: PythonCard 0.6.8 Message-ID: <7cmZ8.447$KY5.70441@news.uswest.net> PythonCard is a GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux. Release 0.6.8 includes over 30 sample applications and four tools to help users build applications in Python: codeEditor, findfiles, resourceEditor, and textEditor. This release supports the new wxPython 2.3.3 preview for Mac OS X. A list of changes since release 0.6.7 is at the end of this message. All the information you need about PythonCard can be found on the project web page at: http://pythoncard.sourceforge.net/ The installation instructions and walkthroughs are available on the main documentation page: http://pythoncard.sourceforge.net/documentation.html You can download the latest release at: http://sourceforge.net/project/showfiles.php?group_id=19015 For a list of some of the samples that have been built with PythonCard and screenshots of them in action go to: http://pythoncard.sourceforge.net/samples.html A description of each sample is included in the readme.txt file in each sample directory. The kind people at SourceForge host the project: http://sourceforge.net/projects/pythoncard/ If you want to get involved the main contact point is the Mailing list: http://lists.sourceforge.net/lists/listinfo/pythoncard-users PythonCard requires Python 2.1.x or later and wxPython 2.3.2.1 or later. wxPython can be downloaded at http://www.wxpython.org/ ka --- Kevin Altis altis at semi-retired.com --- changelog since release 0.6.7, 2002-06-14 Release 0.6.8 2002-07-17 added keyDown event to Tree added itemFocused, mouseContextClick and keyDown events to MultiColumnList moved flatfileDatabase.py module into framework so that it can be used by both the companies and flatfileDatabase samples added clipboard flush when background is destroyed to preserve the clipboard revised flatfileDatabase sample, added pickle support added findString to util.py added hack in the resourceEditor for Unicode string attributes when using a wxPython unicode build added Fred Pacquier's fpop sample (in cvs, not release) added companies sample added file history to findfiles, resourceEditor, and textEditor fixed close event bug in binding.py added text and html/xml style support to codeEditor added links to PythonCard documentation in the Help menus of the codeEditor, findfiles, and resourceEditor tools updated Run options dialog in codeEditor to support optional args added insertDialog.py scriptlet to codeEditor tool removed the auto-shell loading to speed startup of apps the shell can be loaded manually with self.loadShell() codeEditor and textEditor tools updated to use loadShell added appcomponents sub-package support when loading components fixed ComboBox init so text attribute is set after 'items' and 'selected' attributes are set; text will override 'selected' added Sort menu item to flatfileDatabase updated runScript in codeEditor so it changes to the directory of the script being run and then back to the current dir added "Allow any machine to connect" menu item option to the webserver sample added -d command-line option to show the debug menu without showing any of the runtime windows added HTML file support to slideshow sample changed CodeEditor component to auto-load 'python' style configuration if available changed samples launcher to use CodeEditor component for source and resource files added Tree component From huaiyu at gauss.almadan.ibm.com Wed Jul 31 22:02:13 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 1 Aug 2002 02:02:13 +0000 (UTC) Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> <3d46c6a2$1_1@hpb10302.boi.hp.com> Message-ID: John Roth wrote: > >"Huaiyu Zhu" wrote in message >news:slrnakgake.6hf.huaiyu at gauss.almadan.ibm.com... >> John Roth wrote: >> > >> >> For vertical scoping, it is not necessary to separate items with >> >commas. >> > >> >Is this valid Python in general, or is this another change to the >> >syntax? >> >> It's just what I think is necessary. I'm not sure if it fits the >> current python parser, although it appears to be so for existing >> structures like def, class, if, while. > >It certainly looks nice, but I think it's a change to the >syntax for list and dictionary constructors, which >is a different issue. Since Python currently ignores indentation inside (), [], {}, a syntax change is necessary anyway. The question is whether that change can be as simply as nesting indentation inside brackets and dropping the commas. That's similar to puting statements vertically or horizontally with semicolons. At least we now know that for simple examples the syntax readability is not a big problem. It is possible that more nesting of these two styles and continuation lines might pose bigger problems. Huaiyu From rdsteph at earthlink.net Sat Jul 6 08:30:47 2002 From: rdsteph at earthlink.net (Ron Stephens) Date: Sat, 06 Jul 2002 12:30:47 GMT Subject: first experiences with Python References: <2259b0e2.0207060253.1723a696@posting.google.com> Message-ID: <3D26AA70.8070002@earthlink.net> Wow. And welcome, Michelle! ;-)))) What a great introrduction to Python. As you might guess, most of us who read this newsgroup agree with you in that we find Python to be easy, fun, and powerful. Myself, I find the documentation available to be vey good and also very extensive. But, it can always get better! Maybe you can help by contributing some additonal docs for newcomers, especially since, judging from your post, you are quite an interesting writer? But before you do so, maybe you should check out and see just how much is already available. As a newbie myself, I have collected quite a long list of links to online tutorials, other diocumentation and articles about Python, and also book reviews on Python books (an obscene number of the book reviews written by myself), and other stuff of interest to Pythonistas. If you are interested, you can check it out at http://www.awaretek.com/plf.html From yduppen at xs4all.nl Sun Jul 28 12:03:05 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Sun, 28 Jul 2002 18:03:05 +0200 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: <3d4419e0$0$12302$e4fe514c@dreader4.news.xs4all.nl> > So I know what lambda functions are, they're syntax and how they're used. > However I'm not sure *why* one would use a lambda function. What's the > advantage that they offer over a regular function? Back in the old days, before 2.2 came out with its list comprehensions, they had their use. I am a big fan of constructs like map, filter and reduce; by using one function, they allow you to eliminate looping constructs from your code, keeping it shorter and (usually) clearer. However, if you have a list of objects: >>> class A: ... def value(self): ... return "x" >>> list_of_as = [A(), A(), A()] and you want to extract the values using map(), you needed to do: >>> map(lambda x: x.value(), list_of_as) ['x', 'x', 'x'] Luckily, list comprehensions remove that need >>> [x.value() for x in list_of_as] ['x', 'x', 'x'] Since I started to use list comprehensions, I haven't needed a single lambda. YDD -- .sigmentation fault From eric.brunel at pragmadev.com Mon Jul 1 07:19:50 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 1 Jul 2002 11:19:50 +0000 Subject: WindowsError in time.sleep !?!??!! Message-ID: Hi all, We encountered quite a strange problem in an application running on Win2k: when doing a time.sleep(0.1), we occasionally get a traceback: WindowsError: [Errno 5] Access is denied I haven't been able to systematically reproduce the problem. The strange thing is that when it occurs, there's another time.sleep(1) a few lines above, and this one always works. Does anybody have an explanation and/or a workaround for this problem? We may of course delete this statement, but it doesn't sound quite safe: we have many time.sleep in our code, and if we don't understand why this is happening, it may break another one later... Python version is 2.1 and we use multithreading, although not heavily. TIA -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From otijim at yahoo.com Mon Jul 15 15:41:34 2002 From: otijim at yahoo.com (Jake R) Date: Mon, 15 Jul 2002 19:41:34 GMT Subject: Common list in distinct objects' References: <3d331fa9.361390031@news.byu.edu> Message-ID: <3d332491.362646438@news.byu.edu> Now that I think about it some more I seem to remember reading somewhere in the tutorial that class definition is only processed once and being so means that the default list (myList=[]) in my __init__ is only created once and thus any objects created all point to the same list unless I create a new list (ie pass one in or have the __init__ function do it when its called) Does that sound right? Still....I don't think thats what way it ought to behave. On Mon, 15 Jul 2002 19:22:33 GMT, otijim at yahoo.com (Jake R) wrote: >I ran into this today. I created a class that contains a list >attribute. I then add an element to the lists of each object. So each >object should have a list with one element. > >However, the result I get is that, appearantly, both objects are >sharing the same list. > >So, instead of two lists with one element I get one list with two >elements. > >--In Addition------------------------------------------ >This only seems to occur when I use a default null list in my __init__ >method. > >If I change the object declaration lines to: > a = testList([]) > b = testList([]) > >Then two separate lists are created as expected. > >Or, if I remove the default value in the 'def __init__' and replace >the line with: > self.theList = [] > >I also get the expected two lists behavior. > >Can anyone help clarify this for me. > > >--EXAMPLE----------------------------------------- > >class TestList: > > def __init__(self, mylist=[]): > self.theList = mylist > > def printList(self): > for x in self.theList: > print x > > def addItemToList(self, item): > self.theList.append(item) > > >## Program > >a = TestList() >b = TestList() > >a.addItemToList("This is list of A") >b.addItemToList("This is list of B") > >print "Print a" >a.printList() >print >print "Printing b" >b.printList() > From whisper at oz.net Thu Jul 18 21:31:03 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 18 Jul 2002 18:31:03 -0700 Subject: HTML DOM parser? In-Reply-To: Message-ID: adding time.sleep(2) made it work - gave the browser time to _have_ a document :-) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of David LeBlanc > Sent: Thursday, July 18, 2002 18:11 > To: Paul Rubin; python-list at python.org > Subject: RE: HTML DOM parser? > > > > The exception might be legitimate, because of the 403 error. Try > > www.yahoo.com instead of www.nightsong.com. www.nightsong.com really > > does return a 403. > > -- > > > Nope - it's the call to ie.document that chokes. ie.navigation does open > www.w3.org just fine, but trying to get to the DOM isn't working. > > It looks like there's no attribute "document" for this interface... > > Dave LeBlanc > > > > -- > http://mail.python.org/mailman/listinfo/python-list From tim.one at comcast.net Fri Jul 12 23:05:03 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Jul 2002 23:05:03 -0400 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <1026460828.781.70.camel@lothlorien.colorstudy.net> Message-ID: [Ian Bicking] > Tim hasn't chimed in yet -- I bet he's letting us make our own wild > speculations, so that we may attain greater wisdom through pondering :) Me too. Recall that I merely channel Guido, and even then correctly only on good days. When I channeled "sparse is better than dense" as one of Guido's fundamental design principles, I was as mystified as anyone else. Indeed, my first thought was "what the hell is that supposed to mean?!". But, as a professional channeler, I was duty-bound to pass it on as it was revealed, neither adding nor removing jot nor tittle. In the years since, I've come to see that it has many meanings, some of which I explained yesterday. I'm learning from other thoughtful posts (such as yours) that I still have a long way to go in mining its full depth. Or in realizing its full shallowness, depending on how you view it . > Or maybe his attention is just elsewhere... but I'd like to think that > this is a Zen koan. Oh no. Koans are far more advanced, in the nature of using a stick to stir up a fire that consumes the stick in its quest to illuminate its own nature. The channeled 20 Pythonic Theses (their original name -- "The Zen of Python" was tacked on by somebody else, whom I suspect was not really a Zen master) are more about using sticks to build a strong platform, as if sticks were real and strong platforms were worthy of building. It takes a stronger channeler than me to dismiss that as illusion. The end of Pythonic Enlightenment is pleasure in achieving fine code; it's not enough to get you Nirvana, presumably because it's still full of sticks . > Unlike most of the other people in this thread, I always thought of > sparse v. dense as a syntactic/semantic issue. That's definitely part of it. The openness of Python's visual appearance, the ubiquitous use of dicts, and the carefully chosen handful of control structures were the first things I thought of. > ... > I'm probably reading more into this little statement than is there. I don't believe that's possible. Try harder . From fredrik at pythonware.com Sun Jul 21 09:01:38 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Jul 2002 13:01:38 GMT Subject: A better self References: Message-ID: Dave wrote: > 5) Use the x,y,z = self.x, self.y, self.z idiom unfortunately, that actually creates a 3-item tuple, only to tear it apart again. this is better: x = self.x; y = self.y; z = self.z From roy at panix.com Sat Jul 6 08:44:59 2002 From: roy at panix.com (Roy Smith) Date: Sat, 06 Jul 2002 08:44:59 -0400 Subject: Why self? References: Message-ID: "David LeBlanc" wrote: > Now if someone would just stand up and call eXtreme Programming the EXtreme > BS that it is! :P That's kind of like standing up and saying that perl is a stupid language. The reaction you get will be a very strong function of which newsgroup you happen to be standing in when you say it. From ianb at colorstudy.com Mon Jul 15 22:10:13 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 15 Jul 2002 21:10:13 -0500 Subject: Python's Lisp heritage In-Reply-To: <20020715222319.AB5043C1FC@cbbrowne.com> References: <1026767383.703.298.camel@lothlorien.colorstudy.net> <20020715222319.AB5043C1FC@cbbrowne.com> Message-ID: <1026785413.553.6.camel@lothlorien.colorstudy.net> On Mon, 2002-07-15 at 17:23, Christopher Browne wrote: > > This does kind of defeat lexical scoping, though it avoids use of > > globals. While function signatures don't change, it's at the > > sacrifice of object interfaces. OTOH, it seems to work okay. > > I'd contend that there's no "defeat" involved. This isn't a "battle" > with "winners" and "losers;" it's a situation of Trying to Solve > Problems. Well, I meant that it introduces many of the same problems as dynamic scoping. The biggest problem I see is that things can interact in unfortunate ways, and it's difficult to see where information comes from or where it is used. Of course, there is name collision, but ignoring that, there's still potential interaction problems. For instance, what happens when you want to do something recursively? Perhaps you don't expect some function to be called repeatedly with the same state object, but someone may later want to use it in this way. You may overwrite the information you had saved in some attribute, and you don't have the call stack to insulate you from such things (here dynamic scoping can even save you at times, though sometimes it won't help if you wanted to get to the original value, and not later values). The other problem is that it's hard to tell where information comes from or is used. Function signatures make the source of information fairly explicit -- it's either an argument or a global, where the global is usually a module (and easy to track). But when you start adding extraneous information to an object, you often come upon some mysterious attribute access that you can't find in the class definition. Ian From ny_r_marquez at yahoo.com Thu Jul 18 13:32:11 2002 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 18 Jul 2002 10:32:11 -0700 Subject: WeaselWeb References: <8a27e309.0207131624.6c73be50@posting.google.com> Message-ID: <8a27e309.0207180932.6da82cfe@posting.google.com> Just to let you know that there is now a light version of WeaselWeb. It's called WeaselWebLt (it doesn't use IE). The self installing package will fit in one floppy. It should probably be enough for most users. (I think.) However, if you are on a Windows only Intranet, or are otherwise having trouble accessing urls that you are normally able to access using Internet Explorer, you may want to try the full version of WeaselWeb. Note: I have not tested this version much, so I rely on your feedback to enhance it. I hope you enjoy it. -Ruben ny_r_marquez at yahoo.com (R.Marquez) wrote in message news:<8a27e309.0207131624.6c73be50 at posting.google.com>... > This may interest you if have a Palm Pilot, or if you are interested > in custom parsing html files. > > Those of you with Palm Pilots may be familiar with Weasel reader > (http://sourceforge.net/projects/gutenpalm/). I really like this > reader because, besides being free software, it gives the best > compression that I have seen, and it allows for bookmarks to be > generated on the fly as it converts from txt format to its ztxt (pdb) > format. > > The problem for me was that the converter did not know how to handle > html files. So I wrote a little Python program to do this and I > called it WeaselWeb. It is licensed as free software under the GPL. > If you are interested, get it from here (eventually it will be under > the main Weasel project page): > > http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/gutenpalm/gutenpalm/ > > There is a nice self installing package for Windows. However, the > Linux version will need a little help since I do not yet have a usable > Linux machine. I would like to eventually creaet a standalone version > for Linux as well. (If some one would like to help with this, please > be my guest.) > > Any way, I hope you enjoy it. > > -Ruben From rodneys at nospam.io.com Mon Jul 8 19:58:17 2002 From: rodneys at nospam.io.com (Rodney Somerstein) Date: Mon, 08 Jul 2002 23:58:17 GMT Subject: Any Python distribution solutions for Mac? Message-ID: <080720021958161862%rodneys@nospam.io.com> The subject says it all. Is there any packaging mechanism for distributing Python applications on the Macintosh? I know that there is py2exe for Windows and that I can do similar things for Unix. But what about for the Macintosh? If not, is there anything planned? If so, when will it be available? This, along with UI issues which wxPython is slowly taking care of on the Mac is one of the things that has kept me from using Python. Thanks, -Rodney (remove the nospam. from my address if replying via email) From neal at metaslash.com Sun Jul 14 22:23:23 2002 From: neal at metaslash.com (Neal Norwitz) Date: Mon, 15 Jul 2002 02:23:23 GMT Subject: Q: Why does this work??? References: Message-ID: On Sun, 14 Jul 2002 21:05:03 -0400, Jim Cerra wrote: > I'm very new to Python, and I've been examing a bit of code... I can't > figure out why the following doesn't produce an error: > > import string > > total_hits = 0 > hits_by_page = {} # maps document URL to hit count for that document > > def process_request(host, date, timezone, method, url, protocol, code, > bytes): > global total_hits > total_hits = total_hits + 1 > > if hits_by_page.has_key(url): > hits_by_page[url] = hits_by_page[url] + 1 > else: > hits_by_page[url] = 1 > > In the function, process_request(), why isn't the variable, > hits_by_page, declared as a global var? I tried putting in that code (" > global hits_by_page") and there is no effect. The script still > works. > > My question is Why??? You need to declare total_hits global because you rebind (assign, hint the equals sign). But hits_by_page is not assigned to. The dictionary is changed, but not rebound. If you wanted to set hits_by_page to a new dictionary, you would need to declare it global. The rule is that if you do an assignment, you must declare the variable global. If you are only referencing the variable, it does not need to be declared global. See faq #4.36 - http://www.python.org/cgi-bin/faqw.py?req=all#4.36 Neal From aleax at aleax.it Sat Jul 27 16:25:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 20:25:18 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: Carl Banks wrote: ... >>> def sort_the_right_way (f, a): ... > Come on! Wrapping up a sort in a function is an "ambitious > framework"? I'm talking about writing a single function because a > certain sort appears a dozen or so times in the code. I'm sure you're > aware of the advantages of putting oft-repeated code into one place. If the SAME sort appears repeatedly, it surely needs to be a function. But you do have to get your parameters right when "same" is not exactly "same". And if it gets to...: ... >>> sort_the_right_way (lambda x:x[1], a) ...the lambda suggests imperfect factorization. If this "same" sort does occur often, IS it the case that this is the ONLY place where it needs to be by the 1-th item? Or, by AN item? Statistically, it IS possible that the sort is both frequent enough to deserve factoring out AND yet so varied and diverse in the criteria to use that a general function is the only effective way to express them AND that this one in particular is a freak case never to reoccur, so that naming the sortfield-selector function (while not a problem) MIGHT be fractionally suboptimal. The combination of each of these unlikely factors, all together, multiplies down to a VERY small chance. And naming the sort selector function is such a TINY "cost" to pay (come on, now, HOW horrible is it to have to name even such a function as the above one?), even in the extremely unlikely case that it IS a cost at all (rather than, as far more likely, a benefit), that *lambda is not pulling its own weight in the language*. It cannot, hobbled as it is: it's a wart, deadweight, better forgotten. >> Somebody ambitious enough to encapsulate DSU should surely proceed ... > So now you're advocating building a framework of closures to replace No, I'm saying that IF somebody was ambitious enough to encapsulate DSU, then the same somebody should be consistent and proceed along the same route. "If the fool would persist in his folly he would become wise" (Blake). Can't you read? > hated lambdas, I would just write: > > def second(x): return x[1] If that's what you need, fine. > (Of course, I'll write the closure if the need ever comes to have the > program select the index.) > > What I'm saying is, your objection that this use of lambda only is > necessary because of over- and under-generalizatino isn't true for my > circumstances. I don't know you well enough to use my judgment about your specific, individual circumstances, but I *DO* know that I *NEVER* said, implied, inferred or let it be suspected that "this use of lambda is *NECESSARY*" (my emphasis). It obviously *ISN'T* _necessary_, as your hypothetical function "second" shows. You DO know what "necessary" means, yes? It's a MUCH stronger word than, say, "opportune". What an extremely unlikely combination of circumstances MIGHT cause (and I cannot rule out that your personal, individual circumstances might be exactly those), are cases in which lambda is *vaguely defensible* -- never necessary, but if every single one of those circumstances (and more yet, such as, no need ever to stray from the confines of what can comfortably be put in an expression) obtained, then using lambda wouldn't be totally absurd. It still would be INFERIOR (e.g., debugging would be harder as the traceback would not identify the failing extractor by name, as 'second', but only anonymously as 'lambda' -- who lives by the sword [of anonymity]...), but not absurdly so. But it's far simpler to never use lambda, than to analyze each case to ascertain whether it's absurd or merely inferior to use it in any single given case. Great saving of energy, to have one less "way to do it" when that "way" is such a loser. > Personally, I don't care about saving lines, per se. For me, lambda > helps me to avoid stopping mid-function call, scrolling many or few > lines to implement the function as a def, and returning. I.e., > lambdas save me cursor movement. In VIM, I hit ESC, uppercase-O, and I'm in insert mode on a newly inserted immediately-previous line with correct indent, ready to flow on with def and so on. I assume more powerful editors and IDEs, such as EMACS and the like, must have facilities at least as powerful. Thus, the "saving" seems utterly trivial. Alex From pde at cs.mu.oz.au Mon Jul 1 05:06:59 2002 From: pde at cs.mu.oz.au (Peter Eckersley) Date: Mon, 1 Jul 2002 19:06:59 +1000 Subject: Semi-static analysis (was Re: Partial Parsing of Python) In-Reply-To: <20020701104513.E10625@prim.han.de> References: <20020629141507.GA6507@luminance.reworld.org> <20020630094833.B20310@prim.han.de> <20020701060124.GA9937@luminance.reworld.org> <20020701104513.E10625@prim.han.de> Message-ID: <20020701090659.GA30807@luminance.reworld.org> On Mon, Jul 01, 2002 at 10:45:13AM +0200, holger krekel wrote: > Peter Eckersley wrote: > > [me] > > > Actually the REAL problem to solve first is to have Multi-Line editing. > > > Then all sorts of partial parsers *and* partial evaluation. Python is > > > just too damn dynamic to have that one easily. > > > > > > > Oh, which reminds me of something else. I also have problems with > > side-effects ("heisenberg" effects)-- it will be necessary to get rid of > > these. > > But you certainly know that this isn't generally possible? Take Yep, because in Python you can't know the return type of all functions. My proposal was to add notes to lots of functions, and handle the cases where you _do_ know the return type. > > somestrangefile.read(). > A perfect example! If is a builtin file object, it should have a read() method annotated as follows: pure == False (calling the method may cause side effects - do not eval() it in vain!) return_type == types.StringType (so we know we can complete using normal string methods) If is a user defined class, the user should be able to easily provide the above information. Even if it this hasn't been done, there should be *some* cases where we can analyse the python code to extract this information[*]. If a method is impure, and we don't know the return type, then we just give up and don't evaluate it. > for example. The next best bet (read: hack) is to fork off a process > which does the evaluation of an Subexpression. This way you'd catch > 90% of in-place modifications. Doesn't work for files. But then how > often are you doing dynamic network/file communication on the commandline? > This might change once we have multiline editing. But one after three > others :-) > > > My feeling was that this could be done using purity analysis and > > return-type annotation. Many of the important cases can be handled by > > just adding information about the builtin modules, but it might also > > be possible to do generalised python purity analysis. Has anyone tried > > this? > > Not me. I don't even now exactly what you are talking about :-) > I was asking about the analysis marked [*] above. > > Hmmm, I agree that one needs to escape readline/curses - but SDL sounds > > like overkill, since I imagine you'll have to re-implement lots of basic > > widgets on top of it. I picked GTK, and have found it generally > > suitable, despite a few quirks. > > Reflecting our EuroPython discussion, GTK or QT seems to be heavyweight. > We don't need widgets but the ability to put scalable fonts on a screen. > Having sprites and game-level performance can't hurt either :-) > It's very worth a try. I don't know enough about GTK's implementation to know if it's efficient at what it does (I was assuming it would be, but I could easily be wrong). I've certainly found lots of the widget behaviour very useful, but it might not be all that hard that hard to re-implement. -- Peter Eckersley Department of Computer Science & mailto:pde at cs.mu.oz.au IP Research Institute of Australia http://www.cs.mu.oz.au/~pde The University of Melbourne From ajs at ix.netcom.com Sat Jul 27 08:30:20 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Sat, 27 Jul 2002 08:30:20 -0400 Subject: Learning how to program... but what's the best way? Message-ID: <002201c23569$63e6bf20$0334fea9@carol> Hans writes - >Besides this, does anyone have ideas about what would >be a good starting point here? I strongly recommend trying to work with VPython - www.vpython.org. >>> import visual Visual-2001-12-15 >>> visual.sphere() And I am looking at a beautifully rendered 3d sphere. Lots on possibilities for instant gratification, and it seems to me such ready access to good quality 3d graphics is a real motivator for most kids (including some of us full grown ones). Art From skip at pobox.com Mon Jul 8 14:42:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 8 Jul 2002 13:42:08 -0500 Subject: COCOMO - appropriate for languages like Python? In-Reply-To: <7934d084.0207072141.17c249d@posting.google.com> References: <7934d084.0207072141.17c249d@posting.google.com> Message-ID: <15657.56576.965425.897470@gargle.gargle.HOWL> Andrae> Hint: Do-not use gets()!!! Thanks for the elementary C security tutorial, but it really wasn't necessary. I wanted to use gets() because it was semantically the closest to file objects' readline() method (read a line from sys.stdin in this case). Yes, I could have used fgets(s, 80, stdin) or something similar. That wasn't the point of the post. I was asking about COCOMO. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From chris.gonnerman at newcenturycomputers.net Tue Jul 9 19:27:45 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 9 Jul 2002 18:27:45 -0500 Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: <006001c227a0$41b31060$0101010a@local> I use chrony for time maintenance. If your computer has intermittent Internet access (i.e. dialup) it is hands-down the best way to do it IMHO. If this package has already been mentioned, sorry... I haven't followed this thread closely. http://chrony.sunsite.dk/ Off-topic since it's C, but I love it. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From krissepu at vip.fi Wed Jul 3 02:06:16 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Wed, 03 Jul 2002 09:06:16 +0300 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> Message-ID: <3D229458.719D4A7B@vip.fi> Please make also example of recursive decent parser, for example LL(k) -pekka- "Mike C. Fletcher" wrote: > Fredrik, it would be nice to see the list you collect (not just the > selected final entries). > > I'm actually doing something very similar for SimpleParse (pre-built > parsers for common constructs that can automatically be included in your > grammars). > > The library feature will appear in SimpleParse 2.0 (now under > development). Watch for more details in the weeks ahead or join in in > the development effort... > > So far I have: > int > hex > float > number := hex/float/int > double quoted string > single quoted string > string := (dqs/sqs) > semi_colon_comment (ini-files and the like) > hash_comment (python-style) > slashslash_comment (C++ // comments) > slashbang_comment (C /* */ non-nesting comments) > slashbang_nest_comment (as previous, but allows nesting) > > (and common character classes as well, but RE has those already) > > Common ones I'm thinking of adding: > Identifiers (e.g. Python, XML, HTML, C, filenames, URIs) > Dates (with a decent selection of formats, suitable for human data entry > processing) > Times (again, a number of formats) > Display-formatted numbers (e.g. 200,000.00 or 200 000,00 or (200,00) ; > locale specific by default, possibly offering a few common international > formats) > Common units of measurement (SI units only? or maybe Imperial as well. > Anyway, type would be something like: unit_weight or unit_distance or > unit_energy (parsers would then define expression,unit to require a unit > or expression,unit? to provide a default unit)) > Irrational numbers (under numbers, i or j forms) > Monetary values (locale-specific base, possible with a "world" version to > allow for parsing Pounds, Francs, Euros, Yen, Dollars etceteras without > needing to switch locales, support for surrounding brackets meaning > negative, those kinds of things :) ). > IP Addresses > Dotted identifiers > > Higher-level constructs under consideration: > Mathematical expressions > Lists, tuples, dicts (not sure how to make this generic without requiring > a specific name for key/value expressions) > > Possible Python-specific additions (seen in tokeniser.py for your purposes): > Calling/parameter-lists (definition and use) > Triple quoted strings (under strings) > > SGML/XML/HTML-specific, thinking of including them as > simpleparse/common/sgml.py: > Identifier > Tag > Attribute > Comment > Entity References > Processing instruction > Various DTD elements (not sure if worth the trouble) > > For most of those you could probably find RE versions in various libs of > the standard library (after all, they're common :) ). > > Enjoy, > Mike > > > > Michael Hudson wrote: > > Norman Shelley writes: > > > > > >>Fredrik Lundh wrote: > >> > >> > >>>... > >>>If I were to add a dozen (or so) patterns to the (S)RE module, > >>>what should I pick? What patterns do you find yourself using > >>>over and over again? > >> > >>All kinds of numerics, e.g. scientific (1e-6, 2e6, ...) and > engineering (1u, > >>2M and/or 2MEG, ...) notation. > >> > >>Python identifiers as previously mentioned. > > > > > > Well, *they're* already in the tokenize module. > > > > Cheers, > > M. > > > > -- > _______________________________________ > Mike C. Fletcher > http://members.rogers.com/mcfletch/ From greg at cosc.canterbury.ac.nz Tue Jul 30 20:45:32 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 31 Jul 2002 12:45:32 +1200 (NZST) Subject: Pyrex / py2exe import interaction In-Reply-To: <20020730165458.A81189@doublegemini.com> Message-ID: <200207310045.g6V0jWZc019035@kuku.cosc.canterbury.ac.nz> > Hello. I'm having difficulty with using a combination > of pyrex and py2exe; the problem occurs when the module > compiled with pyrex has an "import". I'll look into this if I can, but I don't know if there's much I can do, as I don't have easy access to a Windows machine to debug this sort of thing on. Greg Ewing, Computer Science Dept, +--------------------------------------+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | greg at cosc.canterbury.ac.nz +--------------------------------------+ From see_reply_address at something.invalid Thu Jul 4 20:55:47 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 12:55:47 +1200 Subject: is attribute access a hash-lookup by name? References: <66715c02.0207021737.b488f07@posting.google.com> Message-ID: <3D24EE93.2000308@something.invalid> Aahz wrote: > Also, with new-style > classes, you can use __slots__ to force vectorized lookups, but it's > more a memory-saving technique than a speedup. I don't think it's a speedup at all, since you still have to look up the class dict to find the descriptor which tells what the slot offset is. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 11 14:40:16 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 11 Jul 2002 20:40:16 +0200 Subject: Good SOAP lib for Python 2.2 References: <3D2D9B2C.3030606@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D2DD110.4080605@NOSPAMREMOVETHISxs4all.nl> Christopher Browne wrote: > Irmen de Jong wrote: > >>I'm using Python 2.2.1 and I'm searching a current, up-to-date >>SOAP library for Python. >>I tried ZSI but it fails because apparently it uses an old XML api. >> >>What should I try instead? > > > Something's odd there. There hasn't been any activity with ZSI since > about mid-May. > > And zolera.com (home of Rich Salz, main ZSI developer) seems dead (as > in "DNS doesn't think it exists anymore"). > > Have Zolera/Rich Salz disappeared? > > As for what's "up-to-date", your options are limited, as the latest > release _was_ ZSI, in mid-May 2002. The last release of anything else > was of SOAP.py 0.9.7, in June 2001. (The developers thereof were at a > DotCom that has gone under.) Weird stuff... for Java, SOAP seems to become the de-facto RPC-over-web aka Web Services platform, and a dozen implementations can be found. Now why is there so little SOAP activity for Python? Not that I like SOAP. I like XMLRPC better, of which there's even a module in the Python standard library. But I just have to use SOAP for this project I'm working on, and I want to prototype stuff in Python. Anyway I'll try the updated SOAP.py from the PyGoogle stuff. Thanks, irmen de jong From mal at lemburg.com Fri Jul 5 17:32:00 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Fri, 05 Jul 2002 23:32:00 +0200 Subject: Corrupt mxODBC installation? References: <0t2V8.25132$YC4.386257@news0.telusplanet.net> Message-ID: <3D261050.8050300@lemburg.com> Jose Correia wrote: > Decided to finally upgrade to Python 2.2.1 (from 1.5.2) and downloaded > latest versions of everything incl mxBase 2.0.3 and mxODBC 2.0.4 Windows > installer packages. > > Problem is the mxODBC module seems to be corrupt. The mx stuff is installed > under the \site-packages\mx\ directory. > Results on NT4 SP6 with (ActiveState) Python 2.2.1 build 222 installed: > > >>>>sys.path >>> > ['', 'D:\\Python\\lib\\site-packages\\Pythonwin', > 'D:\\Python\\lib\\site-packages\\win32', > 'D:\\Python\\lib\\site-packages\\win32\\lib', > 'D:\\Python\\lib\\site-packages', > 'D:\\Python\\DLLs', 'D:\\Python\\lib', > 'D:\\Python\\lib\\lib-tk', 'D:\\Python'] > > >>>>import mx.ODBC.Windows >>> > >>>>dbc = mx.ODBC.Windows.Connect('configdb', user='', password='', >>> > clear_auto_commit=0) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'Connect' > > >>>>mx.ODBC.Windows >>> > > >>>>mx.ODBC.Windows.__file__ >>> > 'mx\\ODBC\\Windows\\__init__.pyc' > > >>>>dir(mx.ODBC.Windows) >>> > ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] > > > > This last bit shows that there is indeed no "Connect" in the module. My > previous version (also 1.5.2) on another machine shows loads of > functions,etc when I used the dir() command on it. Could it be that Python is still picking up some not 100% uninstalled version of mxODBC on the machine ? Try running Python in verbose mode to have it print out the paths it tries for finding the modules: python -vv > Does this sound like there's a problem with the module or am I completely > missing something here? > > Been googling for prior version of the package but couldn't find any > anywhere. Versions prior to mxODBC 2.0 are no longer available on the web. The egenix-mx-commercial Windows installers are around 196kB in size, so the size you reported looks odd. -- Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From python at rcn.com Mon Jul 1 00:40:09 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 1 Jul 2002 00:40:09 -0400 Subject: Is this a __slot__ bug? References: Message-ID: "Ian McMeans" wrote > I wasn't able to find a good documentation of slots on the python website. > Do you have a link handy? I guess I'm just bad at searching, I couldn't find > a description in the first few pages of google either. Slots The __slots__ tool changes the way a class implements instance variables. Each variable listed is given pre-allocated space in an instance, as opposed to the standard method of giving each instance its own dictionary. There are two results of using __slots__. First, the instance loses its dynamic character and is protected from creating variables not specifically listed in __slots__. Second, the size of the instance becomes smaller because a dictionary is not required. Its use is indicated when an application uses a large number of instances, storage costs are high due to the number of instances, and the instances do not require dynamic attribute creation. For example, a Node class for a binary tree may achieve considerable space savings: class Node(object): __slots__ = ['value','left','right'] def __init__(self,value=0): self.value = value self.left = self.right = None def show(self): if self.left: self.left.show() print self.value if self.right: self.right.show() n = Node('root') n.left = Node('ginger') n.right = Node('sounds like') n.right.right = Node('bang') n.right.right.right = Node('bong') n.right.right.left = Node('bing') n.show() Raymond Hettinger From huaiyu at gauss.almadan.ibm.com Wed Jul 31 14:42:23 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 31 Jul 2002 18:42:23 +0000 (UTC) Subject: signature for a file ? References: Message-ID: John Hunter wrote: > >You may be interested in the dircmp, which will give you reports on >which files are in common in dirs A and B, which files are unique to >A, which are unique to B, and so on... > > http://python.org/doc/current/lib/dircmp-objects.html > >This built-in library is (naturally) much more efficient than the >script I posted because > >1) It only computes sums on identical files. No need to check sums on > files that have no other file the same size > >2) It computes the sums of identically sized files in blocks and > compares the files blockwise. No need to compute the entire sum if > the first 1000 bytes differ. > >3) It has a nice OO interface to get lists of common and unique files, > and will recurs subdirs upon request. Thank you very much! Huaiyu From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 19:51:20 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 16:51:20 -0700 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> <7xeldq1zzp.fsf@ruckus.brouhaha.com> <7xptxawajw.fsf@ruckus.brouhaha.com> Message-ID: <7xy9byyrnr.fsf@ruckus.brouhaha.com> Dale Strickland-Clark writes: > I see the process working something like this: > > 1. The client system calls a CGI script on our server and retrieves a > challenge string and thus initiates a session > 2. The client system then constructs the frame page with its response > in the url for the frame source (among other things). > 3. If authenticated, we display the requested forms (in sequence), > passing control to a pre-aranged url at the end of processing. > > This isn't a sensitive application. If someone breaks into it, all > they a rewarded with is a series of forms for fill in. We just want to > limit the scope for idle buggering about. Well, depending on what happens as a result of their filling in the forms (do you send anyone's money to an address supplied in the form?) you may not have to worry too much. I'm still not clear on why you need challenge-response anyway though. Suppose the client just puts HMAC(current date/time, secret key) into the URL along with the date/time in hex. Then use the HTTP Referer header to figure out who the client is (or put that in the URL too) and authenticate the URL. By examining the date/time you can reject old/stale URL's. From bbeck at REMOVE-THIS-TO-EMAIL-ME.austin.rr.com Wed Jul 3 02:49:46 2002 From: bbeck at REMOVE-THIS-TO-EMAIL-ME.austin.rr.com (Brandon Beck) Date: Wed, 03 Jul 2002 06:49:46 GMT Subject: Splitting Text files References: Message-ID: <3D229E1F.1040006@REMOVE-THIS-TO-EMAIL-ME.austin.rr.com> Ken Seergobin wrote: > X-No-Archive:Yes > > > I've looked around, but have been unable to locate a > good example of how to split a text file. Specifically, > I have datafiles with an identification line marked > with the name of a BMP file followed by many lines of > data. This repeats a number of times for each datafile. > Within the data lines I'm only interested in extracting the > those with a specific keyword. Ultimately, I'd like to have > a datafile for each BMP listed in the original file. > > Suggestions would be appreciated. I really couldn't make > sense of the regular expression notes I found. > > Thanks, > Ken > > I've written something to do exactly this, with the data all on one line, not spanning multiple lines. It obviously not exactly what you want but it should give you a good base to work off of if you're interested in extending it. Main directory: http://isomorphism.org/~bbeck/splitter/ Splitting algorithm: http://isomorphism.org/~bbeck/splitter/splitter.py Sample splitter: http://isomorphism.org/~bbeck/splitter/FirstNameSplitter.py Sample data (for FirstNameSplitter.py): http://isomorphism.org/~bbeck/splitter/input.txt Hope this helps, Brandon From emile at fenx.com Tue Jul 23 11:15:26 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Jul 2002 15:15:26 GMT Subject: Make me beautiful (code needs help) References: Message-ID: Mark > Ok, I have the following data: > > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] >>> A = [1,2,4,10,50] >>> ['?']+[a-b for b,a in zip(A,A[1:])] ['?', 1, 2, 6, 40] -- Emile van Sebille emile at fenx.com --------- From gerhard.haering at gmx.de Wed Jul 10 10:06:55 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 10 Jul 2002 14:06:55 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> Message-ID: In article <3D2C3CAB.BE7084F1 at tds.net>, Edward K. Ream wrote: > I would like to create a set of Tkinter callbacks that vary only in the > bindings of a single argument. For example, I would like to do: > > for val in vals: > b = Tk.Button(...,command=self.myCallback(val)) > > But this doesn't work: it executes callback, rather than returning the > callback function with the second arg bound to val. I've no idea about Tkinter at all, but this should accomplish what you need: command=lambda: self.myCallback(val) I don't know for sure, but I think this needs nested scopes. So if you're using Python 2.1, be sure to "from __future__ import nested_scopes". In Python 2.2, this is the default. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From annis at biostat.wisc.edu Fri Jul 5 11:38:35 2002 From: annis at biostat.wisc.edu (William Annis) Date: 05 Jul 2002 10:38:35 -0500 Subject: Getting Process List On *nix References: Message-ID: John Abel writes: > I am trying to write a script, capable of running on Win32, and *nix, > which looks for certain processes. However, I can't seem to find any > details of how to access of list of running processes under *nix, Well, each different flavor of Unix is going to handle this somewhat differently. In a lot of recent flavors you have /proc, in which you'll find a file system representation of processes. > without shelling out, something I'm loathe to do. In this case, shelling out for the Unix side may actually be most portable. -- William Annis - System Administrator - Biomedical Computing Group "When men are inhuman, take care not to feel towards them as they do towards other humans." Marcus Aurelius VII.65 From i.linkweiler at gmx.de Tue Jul 9 13:34:09 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Tue, 09 Jul 2002 19:34:09 +0200 Subject: Multi language software development? Message-ID: <3D2B1E91.4070102@gmx.de> Hi, do you know any tools or IDEs, which allow multi-language software development with python? (English, German ...) I do not need this for a special project, it is just a gernal question. I want.... - GUIs supporting more than one language - Replace strings in existing code (list of words) - use multiple language strings within my source code I have searched with google and at "Vaults of Parnassus" without finding something. One way is to replace all strings by variables, and put the variables in a module. Do you know other good ways to develop software for more than one language and to translate existing software? Ingo From quest at lysator.liu.se Tue Jul 9 04:17:16 2002 From: quest at lysator.liu.se (Anders Qvist) Date: Tue, 9 Jul 2002 10:17:16 +0200 Subject: Broken build system as of 2002-06-04 Message-ID: <20020709081716.GT20301@lysator.liu.se> The snake-farm has been choking on the python CVS source since 2002-06-04, like thus (on _all_ platforms): case $MAKEFLAGS in \ *-s*) CC='gcc' LDSHARED='gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ../python/dist/src/setup.py -q build;; \ *) CC='gcc' LDSHARED='gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ../python/dist/src/setup.py build;; \ esac running build running build_ext Traceback (most recent call last): File "../python/dist/src/setup.py", line 1008, in ? main() File "../python/dist/src/setup.py", line 1003, in main scripts = ['Tools/scripts/pydoc'] File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/core.py", line 140, in setup dist.run_commands() File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/dist.py", line 886, in run_commands self.run_command(cmd) File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/dist.py", line 906, in run_command cmd_obj.run() File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/command/build.py", line 107, in run self.run_command(cmd_name) File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/cmd.py", line 334, in run_command self.distribution.run_command(command) File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/dist.py", line 906, in run_command cmd_obj.run() File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/command/build_ext.py", line 244, in run customize_compiler(self.compiler) File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/sysconfig.py", line 146, in customize_compiler (cc, opt, ccshared, ldshared, so_ext) = \ File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/sysconfig.py", line 446, in get_config_vars func() File "/home/quest/tmp/snakefarm/python/dist/src/Lib/distutils/sysconfig.py", line 332, in _init_posix raise DistutilsPlatformError(my_msg) distutils.errors.DistutilsPlatformError: invalid Python installation: unable to open /usr/local/lib/python2.3/config/Makefile (No such file or directory) make: *** [sharedmods] Error 1 The problem occurs only when building the python source in a separate build dir. Eg: cd build ../pythonb/dist/src/config make all It seems to me that sysconfig.py is unaware that building may occur in a separate directory. -- Anders "Quest" Qvist "We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the Internet, we know this is not true." -- Robert Wilensky From ianb at colorstudy.com Wed Jul 31 12:35:57 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 31 Jul 2002 11:35:57 -0500 Subject: Let's Talk About Lambda Functions! In-Reply-To: <3D47B936.1AFA8DB8@cascade-sys.com> References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitete ch.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <3D475AB5.2060207@nowhere.org> <1028096804.836.1812.camel@lothlorien.colorstudy.net> <3D47B936.1AFA8DB8@cascade-sys.com> Message-ID: <1028133358.578.3668.camel@lothlorien.colorstudy.net> On Wed, 2002-07-31 at 05:17, James J. Besemer wrote: > Smalltalk's control structures have no pretension > whatsoever to be related to lambda (or anything > else I've ever seen before). Some examples: > > count timesRepeat: [ block of code ] > > [ count <= max ] > whileTrue: [ another block ] > > x < 10 > ifTrue: [ true block ] > ifFalse: [ false block ] Well, it looks a lot like lambda calculus, because True and False are two different classes, with definitions like: ---- (True) ifTrue: block block value "This evaluates the passed block" ifFalse: block "do nothing" (False) ifTrue: block "do nothing" ifFalse: block block value ---- This should remind one of true/false in lambda calculus (though obviously with a very different notation). But, at least in Squeak (and my impression is this is universal among Smalltalk environments), ifTrue:/ifFalse: don't actually get passed as method calls/messages. The compiler specifically looks for those methods, and turns them into traditional if statements in the bytecode. That is, you can't (usefully) implement ifTrue: in your own custom class. Ian From imbosol at vt.edu Fri Jul 26 19:14:01 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 26 Jul 2002 19:14:01 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: Alex Martelli wrote:> > Paul Rubin wrote: > >> "Britt A. Green" writes: >>> So I know what lambda functions are, they're syntax and how they're used. >>> However I'm not sure *why* one would use a lambda function. What's the >>> advantage that they offer over a regular function? >> >> You can use them inside other expressions, e.g. suppose you want to >> sort a bunch of strings starting with the second letter: >> >> a = ['apple', 'banana', 'pear', 'watermelon'] >> a.sort(lambda x,y: cmp(x[1],y[1])) >> >> => ['banana', 'watermelon', 'pear', 'apple'] >> >> Without lambda, you'd have to define a separate named function: > > Without lambda, you might be more tempted to do it right (a la DSU): > > aux = [ (x[1], x) for x in a ] > aux.sort() > a[:] = [ x for __, x in aux ] > > When you're sorting 4 items, it doesn't matter, but try -- not a > huge number -- just 400, say. Two things: First, this has a pitfall: if x is not sortable for some reason, then the "right" way can throw an exception due to lexical ordering of tuples. I encountered this when trying to sort classes that didn't have a __cmp__ method. It seems that a better way is to use id(x) as the second element and x as the third: (x[1], id(x), x) Second, if you're going to do it right often, you might want to wrap it up in a function like this: def sort_the_right_way (f, a): aux = [ (f(x), x) for x in a ] aux.sort() a[:] = [ x for __, x in aux ] In which case, the temptation to use lambda returns: sort_the_right_way (lambda x:x[1], a) -- CARL BANKS http://www.aerojockey.com From edream at tds.net Tue Jul 30 18:53:33 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 30 Jul 2002 22:53:33 GMT Subject: Leo 3.1 Bugs References: Message-ID: I have just released leo.py 3.2. I believe it addresses all issues raised here. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From david.levy at xrce.xerox.com Tue Jul 23 08:25:43 2002 From: david.levy at xrce.xerox.com (David Levy) Date: Tue, 23 Jul 2002 14:25:43 +0200 Subject: SMTP for SOAP in Python References: <3D3D217D.A5572039@lfpt.rwth-aachen.de> Message-ID: <3D3D4B47.C6761BF0@xrce.xerox.com> SOAP.py is the best library available for python IMHO you are right, most of the job is for type handling you can write your own Transport Class (SMTPTransport) to send and receive the soap message you pass it to your SOAPProxy and it;'s ok .... it should be ! I would also be interested in such an implementation ! plz tell us :) David Lars von Wedel wrote: > Hi folks, > > I saw a couple of libraries to support SOAP c/s in Python. > > However, all of them rely on HTTP as a transfer protocol > as far as I have seen. Are there any libs using SMTP? > > Doing my own implementation of SMTP transport, which would > be the best choice of SOAP library in terms of matureness > and extensibility? > > From SOAPpy in the pywebsvcs module it seems, that the biggest > part is the data type handling, whereas the actual data transport > is a fairly small piece of the overall code. Thus, an SMTP > extension should be easy or am I overlooking some details? > > Lars -- _____________________________________________________________ David Levy Xerox Research Centre Europe 6, ch. de Maupertuis F - 38240 Meylan Email david.levy at xrce.xerox.com http://www.xrce.xerox.com From aleax at aleax.it Fri Jul 5 13:02:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 17:02:05 GMT Subject: adding methods on the fly References: Message-ID: Renzo Tomaselli wrote: > Hi all, > after a long and unsuccessful search about extending C++ classes by > Python methods, I came up to the point where a couple of basic questions > should be answered: Just in case you're more comfortable with Italian, I want to point out that you can also post these questions in Italian on group it.comp.lang (start the subject with [Python]). Here you get many more responders, though, so a better chance. [Right now for example I'm not following it.comp.lang -- and not comp.lang.python either, as I _must_ get back to writing and editing, I'm just dipping in for old times' sake:-)]. > 1. Can we add new (Python) methods to a C object wrapper, e.g. after it > has been instantiated with a normal (C) method table ? What happens when you try to add attributes to a C-coded object depends on how that C-coded object has defined its setattro slot (or its setattr slot, but that's an older and less general way to do things). And similarly for the getattro that implicitly happens when the attribute is "gotten" prior to calling it. So, it all depends on how you code your C extension. > 2. if not: can we add a new method to an already imported Python class ? > If yes, how can we do it, assuming to start from a method statement hosted > by a string ? Given a Python class object, whether classic or new-style, setattr works just fine. Not sure what is "a method statement hosted by a string". > I understand that the latest version (2.2.1) allows for defining a class > which inherits from a C type, so that we can define some Python methods on > it, while retaining the capability of inherited C methods. Yes, as long as that C-coded type IS specifically coded as to support being inherited from. Once again, it all depends on how you code at the C level. One way to avoid depending on how the C-level code is written is to use wrapping and automatic delegation in your Python class -- that also works in 2.1 and earlier, not quite as fast as inheritance but the difference may not be dramatic. For an example, see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 (or, better, the expanded and clarified version in the printed Python Cookbook, ed. Martelli and Ascher, but that's only due out in 3 weeks, so, meanwhile, the original online version will do:-). Alex From rick_m_hightower at hotmail.com Sat Jul 13 11:45:39 2002 From: rick_m_hightower at hotmail.com (Rick Hightower) Date: 13 Jul 2002 08:45:39 -0700 Subject: New Book: Python Programming with the Java Class Libraries Message-ID: <6ec68a4c.0207130745.58d2fa07@posting.google.com> Python Programming with the Java Class Libraries >From the Back Cover Characterized by ease of use, richness of expression, and concise syntax, Python has remained a premier programming language for more than a decade, and is used by novices and professionals alike. In particular, its close relationship to Java™ makes the two languages, when used in combination, ideal for Web and distributed enterprise application development. **This tutorial begins with coverage of some of the basics of Python programming.*** Using plenty of skill-building exercises and interactive programming sessions, the book will help those new to programming develop an understanding of concepts and practical techniques. For experienced programmers, the book demonstrates Python's breadth of capabilities and shows the ways that Python interfaces with the Java APIs for professional application development. Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications covers important topics such as: Fundamental programming concepts, including statements, expressions, interpreters, and compilers Python basics, including operators, string formatting, namespaces, classes, errors, and exceptions Object-oriented programming concepts File input/output Python's intrinsic functions Formatting, parsing, and manipulating stringsInterfacing with the Java APIs and working with Java Streams Using Python and Java Swing to create GUIs Working with SQL and JDBC™ Python and Java applets In addition, the book contains instructions for downloading and installing the Python language and the JDK. Terminology, definitions, explanations, and numerous code samples make this book a useful learning experience. Whether you are a sophisticated computer user new to programming or a serious application developer, Python Programming with the Java™ Class Libraries will give you insight into the power of Python and the know-how to put it to work. If you are new to Python and Java, and want to come up to speed using Jython quickly, than this is the book for you. If you know Java and want to incorporate Jython in your work, this book works out well too. From bsder at mail.allcaps.org Tue Jul 30 21:49:50 2002 From: bsder at mail.allcaps.org (Andrew P. Lentvorski) Date: Tue, 30 Jul 2002 18:49:50 -0700 (PDT) Subject: How do you import a module with "." in its filename? Message-ID: <20020730183714.P13827-100000@mail.allcaps.org> I have several files: a.test.py b.test.py c.test.py which carry out regression tests for their respective modules (a.py, b.py, c.py). I would like to create an overall module called alltests.py. However, when I try to do: import a.test in alltests.py, Python gets all huffy since "." is its separator for module hierarchy. So, how do I import a module with "." in its filename? For both practical and political reasons, renaming a.test.py to a_test.py is not an option. -a From jacek.generowicz at cern.ch Wed Jul 10 03:33:24 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jul 2002 09:33:24 +0200 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: "Bo M. Maryniuck" writes: > On Tuesday 09 July 2002 16:59, curt finch wrote: > > ftp://ftp.jump.net/pub/journyx/other/PythonWhtPaper0_1.doc > > Right people will not download this. M$ Word DOC is *evil* format. Please do > PDF, DVI or HTML instead. I'll second that. I was about to have a look, and then saw the doc extension. I take doc extensions to mean "This document is intended for Microsoft customers only". I am not a Microsoft customer. From anton.wilson at camotion.com Tue Jul 30 17:44:08 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 30 Jul 2002 17:44:08 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207302143.RAA26002@test-area.com> On Tuesday 30 July 2002 03:39 pm, brueckd at tbye.com wrote: > On Tue, 30 Jul 2002, anton wilson wrote: > > On Tuesday 30 July 2002 04:55 am, Martin v. L?wis wrote: > > I would disagree. > > In the Python documentation it states: > > > > "In order to support multi-threaded Python programs, the > > interpreter regularly releases and reacquires the lock -- by default, > > every ten bytecode instructions " > > > > What's the purpose of releasing an reaquiring the lock if no other > > threads can run? > > Please consider that, because there's so many multithreaded Python > programs that work quite well, it's rather unlikely that the threading > implementation is outright broken. *Maybe* some improvement needs to be > made, but from your posts it sounds more like you don't understand how > things work at the C level, much less in Python. When the lock is released > at the end of its regular interval, an *attempt* is made to reacquire it > immediately, but there's no guarantee that the current thread will get it > right away (and if another thread is already blocking on an attempt to get > the lock then the other one will probably "win" most of the time anyway). > Maybe I am not being clear enough. I am concerned with a multi-threaded program that does not do any form of blocking on a Linux/Unix box. I DO expect a thread to block on the GIL every 10 byte codes. However, I have proved with my results that this does NOT happen. Any thread that is completely CPU bound will never give up the CPU for as long as 1) it can run 2) it has work to do I have proven this by even examining what happens within the interpreter with this code in ceval: oldt = tstate; /*<---- My code*/ if (PyThreadState_Swap(NULL) != tstate) Py_FatalError("ceval: tstate mix-up"); PyThread_release_lock(interpreter_lock); /* Other threads may run now */ /*sched_yield();*/ PyThread_acquire_lock(interpreter_lock, 1); if (PyThreadState_Swap(tstate) != NULL) Py_FatalError("ceval: orphan tstate"); if(tstate == oldt) /*< ------- my code*/ printf("bad things have happened\n"); The great majority of the time, my print statement will be printed, meaning the GIL was not released. but the put-it-up-for-grabs-every-10-instructions functionality > works just fine too. Consider: > > import threading, time > > COUNT = 3 > counters = [0] * COUNT > > def Worker(i): > while 1: > counters[i] += 1 > > for i in range(COUNT): > threading.Thread(target=Worker, args=(i,)).start() > > while 1: > time.sleep(1.0) > print counters > > Here's some output: > [162565, 176016, 165796] > [329009, 327856, 333183] > [497881, 496857, 498133] > [665567, 679094, 643678] > [810255, 845521, 811988] > [968056, 1008142, 974790] > > Lo and behold, each thread is getting execution time, and nearly equal > execution time at that! There are several reasons why your program seems to work. The first obvious reason is that the main thread sleeps. If you remove the sleep, you will see output that looks like this [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] ....(100+ times in all)... [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] [35499, 16419, 0] ...(100+ times in all) .... [35499, 16419, 11556] [35499, 16419, 11556] [35499, 16419, 11556] [35499, 16419, 11556] [35499, 16419, 11556] [35499, 16419, 11556] [35499, 16419, 11556] .....etc .... This proves that the GIL does not block very often, and definitely not every 10 byte codes. Think about this for a while. I made a python interpreter with a sched_yield inbetween the acquire and release calls and my results looked like this with your sleep removed: [1886, 1887, 0] [1886, 1887, 0] [1886, 1888, 0] [1886, 1889, 0] [1886, 1890, 0] [1886, 1890, 0] [1886, 1890, 0] [1886, 1891, 0] [1886, 1892, 0] [1886, 1893, 0] [1886, 1893, 0] .....etc....... Here, you will notice that there are constant changes. The GIL releasing is working as intended. This brings me to the second reason that your program seems to work. The Linux OS gives threads time-slices and when these time-slices are used up every 150 or so milliseconds, the process is forcibly removed from the CPU. I presume that the reason your program seems to work is that in the time between when a thread releases the GIL and a thread tries to reaquire the GIL, it is forcibly removed from the CPU, and the other thread can now run. This would not be a rare occurence due to the high frequency at which the lock is released. To prove this, I ran the program using sched_rr threads and changed the kernel so that round robin threads had no timeslice. In this case I saw this output once per second: [0, 0, 0] [0, 586126, 0] [0, 1194859, 0] [0, 1802596, 0] [0, 2414027, 0] Because the thread is never forced by the OS to relinquish the CPU, the thread will never ever lose the GIL. If the GIL was actually working corectly and blocking, the second thread would not retain the CPU past 10 byte codes. So, the GIL does not blcok as intended, and this probably needs to be looked into. Anton From peter at engcorp.com Mon Jul 8 19:45:35 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 19:45:35 -0400 Subject: COCOMO - appropriate for languages like Python? References: <7934d084.0207072141.17c249d@posting.google.com> Message-ID: <3D2A241F.44FD6CF8@engcorp.com> Jonathan Hogg wrote: > > On 8/7/2002 19:42, in article > mailman.1026153791.18801.python-list at python.org, "Skip Montanaro" > wrote: > > > Andrae> Hint: Do-not use gets()!!! > > > > Thanks for the elementary C security tutorial, but it really wasn't > > necessary. I wanted to use gets() because it was semantically the closest > > to file objects' readline() method (read a line from sys.stdin in this > > case). Yes, I could have used fgets(s, 80, stdin) or something similar. > > That wasn't the point of the post. I was asking about COCOMO. > > I thought the point was very valid. COCOMO is about fully-debugged lines of > code. Andrae pointed out that your comparison was false because the lines of > C code were clearly not "fully-debugged" and thus not comparable. There's no such thing as fully debugged. There is, however, "adequately debugged" (though how one gets there I'm not sure :-), and it's quite possible that Skip's one-liner with gets() was entirely suitable for the intended application. It's not *always* necessary to write highly robust code, and in that light it's quite possible the comparison is still entirely valid. -Peter From jb at hotmail.com Mon Jul 29 16:56:18 2002 From: jb at hotmail.com (JB) Date: Mon, 29 Jul 2002 22:56:18 +0200 Subject: Python design failures (was Re: Let's Talk About Lambda Functions!) References: <3d455445_9@news.newsgroups.com> <3d457011_1@news.newsgroups.com> <3d457545$1_3@hpb10302.boi.hp.com> Message-ID: <3d45aa16_11@news.newsgroups.com> Daniel Fackrell wrote: > `object` == repr(object), both of which will call > object.__repr__, if it exists. > > I think that the general consensus is that repr(object) is > much more > readable than the relatively obscure syntax `object`. > Also, as written previously, the ` is easily confused with > ' in many fonts. Maybe. But using the backticks is much shorter, much more elegant. I should not want to do without them. Readability or even legibility has never been a problem for me. (I have problem with booleans, but this is another story.) -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From fperez528 at yahoo.com Fri Jul 26 19:33:59 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 17:33:59 -0600 Subject: extract elements of n char from a list References: Message-ID: Tim Peters wrote: > To be technical right back , I wrote about "Unix-like systems", which > is a far broader world than is covered by glibc alone.??The?POSIX?/?Single > UNIX Specification says only this: Ahh, the beauty of vague standards :) Anyway, I thoroughly enjoyed your description and it was as I said a minor point, slightly worthy of mention. It wasn't really misleading at all, it's just that I was sensitive to the point because of having spent the afternoon yesterday writing 4 different clock functions as an extension module to distinguish between system and user time. The book looks very nice, btw. Good job, f. From phoebe_1 at att.net Fri Jul 5 09:52:39 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 5 Jul 2002 06:52:39 -0700 Subject: metaclass & __slots__ References: Message-ID: Alex & John, Thanks for good explanations and clarifications. This was just an exercise to hurt my brain, I guess :) But somehow I feel the addition of the "new" style classes and the "automatic" call of "__new__" and "__init__" is really confusing. The "__init__" seems redundant, since we actually have a true "constructor". I guess, what I am trying to say is, with the scarce documentation (and if you are lazy to browse through the source) it seems like you need to know the distinction on what to override (__new__ or __init__) for a class derived from a builtin. Thanks again M From cce at clarkevans.com Tue Jul 30 16:54:58 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 30 Jul 2002 16:54:58 -0400 Subject: Pyrex / py2exe import interaction Message-ID: <20020730165458.A81189@doublegemini.com> Hello. I'm having difficulty with using a combination of pyrex and py2exe; the problem occurs when the module compiled with pyrex has an "import". The program then works just fine until the calling script is packaged up with py2exe, then you get the following: Traceback (most recent call last): File "", line 1, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 267, in _import_one File "", line 163, in get_code File "imputil.pyc", line 89, in _import_hook File "imputil.pyc", line 152, in _determine_import_context AttributeError: 'module' object has no attribute 'get' Anyway, both of these programs play all sorts of tricks to get importing to work, so I figure that interaction of the two importing strategies is causing difficulty. Following is the source code for the various files that I'm using. Further, these files are packged up at http://clarkevans.com/tmp/prob.tgz ; the build was performed with ActiveState 2.2.1 on Win2K using py2exe 0.3.3 and pyrex 0.4 compiled using mingw32, gcc 2.95.3-6 Any help would be very cool. My actual setup is much more complicated than this, but I tried to make the smallest example which exhibits the behavior. Also, I've had to split "setup.py" into two distinct files since I didn't know how to make them both work together. Oh yes, both of these are *fantastic* tools. Thank you for them and your help! Clark P.S. Great tools! --------------- Makefile ------------------- test: clean dist cd dist/test; ./test.exe testmod.pyd: testmod.pyx python build.py build_ext --inplace --compiler=mingw32 dist: test.py testmod.pyd python dist.py py2exe clean: rm -f *.c *.o *.so *.cpp *.pyd *.pyc *~ *.bak core rm -rf build dist --------------- build.py ------------------- from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = 'testmod', ext_modules=[ Extension("testmod",["testmod.pyx"]), ], cmdclass = {'build_ext': build_ext} ) --------------- dist.py -------------------- from distutils.core import setup import py2exe setup( name = 'Demos', scripts = ["test.py"], ) --------------- testmod.pyx ---------------- import string def go(): for x in string.split("one,two",","): print x --------------- test.py -------------------- from testmod import go go() --------------- OUTPUT --------------------- $ make test python build.py build_ext --inplace --compiler=mingw32 running build_ext building 'testmod' extension testmod.cpp: In function `struct PyObject * __pyx_f_go(PyObject *, PyObject *, PyObject *)': testmod.cpp:73: warning: label `__pyx_L3' defined but not used testmod.cpp:59: warning: label `__pyx_L2' defined but not used creating build creating build\temp.win32-2.2 creating build\temp.win32-2.2\Release C:\msys\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\Python22\include -c testmod.cpp -o build\temp.win32-2.2\Release\testmod.o writing build\temp.win32-2.2\Release\testmod.def C:\msys\mingw\bin\gcc.exe -mno-cygwin -mdll -static -s build\temp.win32-2.2\Release\testmod.o build\temp.win32-2.2\Release\testmod.def -Lc:\Python22\libs -lpython22 -o testmod.pyd python dist.py py2exe running py2exe running build running build_scripts creating build\scripts-2.2 copying test.py -> build\scripts-2.2 running install_scripts creating build\bdist.win32 creating build\bdist.win32\winexe creating build\bdist.win32\winexe\lib creating build\bdist.win32\winexe\lib\Python22 creating build\bdist.win32\winexe\lib\Python22\Scripts copying build\scripts-2.2\test.py -> build\bdist.win32\winexe\lib\Python22\Scripts creating dist +---------------------------------------------------- | Processing script test.py with py2exe-0.3.3 +---------------------------------------------------- creating dist\test creating build\bdist.win32\winexe\collect creating build\bdist.win32\winexe\collect\test creating build\bdist.win32\winexe\collect\test\Scripts.py2exe Searching modules needed to run 'test.py' on path: ['c:\\cygwin\\home\\cce\\prob\\build\\bdist.win32\\winexe\\lib\\Python22\\Lib\\site-packages', '', 'C:\\Python22\\Lib\\site-packages\\Pythonwin', 'C:\\Python22\\Lib\\site-packages\\win32', 'C:\\Python22\\Lib\\site-packages\\win32\\lib', 'C:\\Python22\\Lib\\site-packages', 'c:\\Python22\\DLLs', 'c:\\Python22\\lib', 'c:\\Python22\\lib\\lib-tk', 'c:\\Python22'] force_imports = Resolving binary dependencies: C:\WINNT\System32\python22.dll testmod.pyd C:\Python22\Lib\site-packages\py2exe\run.exe ext_mapping = { 'testmod': ('testmod.pyd', ('.pyd', 'rb', 3)) } copying C:\Python22\Lib\site-packages\py2exe\support.py -> build\bdist.win32\winexe\collect\test\Scripts.py2exe byte-compiling c:\Python22\lib\imputil.py to imputil.pyc copying test.py -> build\bdist.win32\winexe\collect\test\Scripts.py2exe\__main__.py changing into 'build\bdist.win32\winexe\collect\test' c:\cygwin\bin\zip.exe -rq c:\cygwin\home\cce\prob\build\bdist.win32\winexe\test.zip . changing back to 'c:\cygwin\home\cce\prob' creating dist\test\test.exe copying C:\WINNT\System32\python22.dll -> dist\test copying testmod.pyd -> dist\test removing 'build\bdist.win32\winexe\collect\test' (and everything under it) Built File dist\test\test.exe removing 'build\bdist.win32\winexe' (and everything under it) warning: py2exe: could not parse version number '' No VersionInfo will be created cd dist/test; ./test.exe Traceback (most recent call last): File "", line 1, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 267, in _import_one File "", line 163, in get_code File "imputil.pyc", line 89, in _import_hook File "imputil.pyc", line 152, in _determine_import_context AttributeError: 'module' object has no attribute 'get' -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From rs at onsitetech.com Tue Jul 9 13:15:09 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 17:15:09 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: <3D2B19CE.5040409@onsitetech.com> Alex Martelli wrote: I think I realized why several people haven't gotten what I mean here: >> >>String name = (String) aVector.element(0) >> >>Python doesn't have any problems with implicitness here... A cast in Java is _not_ like a cast in C, although it looks like it. As far as I remember, a cast in C really lets the casted variable be treated like the new type. (?) In Java, no action is really taken during a cast. No String representation is generated above. It's actually a way to get around the static typing. Normally, aVector always returns Objects, and you only have access to the methods in the Object class. The cast tells the compiler that you're convinced it's a String, and thus the compiler will let you send a message listed in the String class's API. So again, I think that this does highlight the implicit nature of Python - when you grab an object out of a container, you can send whatever message you want to it. You don't have to explicitly state what class you think it is. Robb From timr at probo.com Wed Jul 31 01:31:04 2002 From: timr at probo.com (Tim Roberts) Date: Tue, 30 Jul 2002 22:31:04 -0700 Subject: code examples for rfc822 module? References: Message-ID: rotundo52 at hotmail.com (Jon J. Morin) wrote: >Does anyone know of any sites or other resources with code examples >using the rfc822 modulde? I am writing an app that sends and receives >email and I really don't understand the documentation on the >python.org site (I'm kind of a Python newbie). Any help is >appreciated. The test routine at the end of the module gives you the basic operation. There isn't too much to rfc822; you feed it a message, it returns the headers and addresses in usable fashion. You might want to look at the email module instead, if you need more (like MIME handling). What were you hoping to have it do? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From curt at journyx.com Tue Jul 9 10:59:49 2002 From: curt at journyx.com (curt finch) Date: 9 Jul 2002 07:59:49 -0700 Subject: j2ee and python and evil competitors Message-ID: <96c7f32.0207090659.b5b9a27@posting.google.com> i commissioned a response to this get written up. Some of your comments have been included... ftp link is ftp://ftp.jump.net/pub/journyx/other/PythonWhtPaper0_1.doc -- Our free and open SOAP/XML APIs enable 'snap-in' to your IT infrastructure http://journyx.com From dyoo at hkn.eecs.berkeley.edu Thu Jul 4 20:50:06 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 5 Jul 2002 00:50:06 +0000 (UTC) Subject: Math irregularity ... is this normal? References: Message-ID: Some One Else wrote: : Hello! : I just compiled and installed Python 2.2.1 on Linux-Mandrake 8.0. When I : do the following: :>>> 2/5.0 : 0.40000000000000002 : In 'Learning Python', a similar example says I should get the more logical : answer of 0.4. Did I install something wrong? I can see where this could : result in creeping math errors. Hello! The behavior of displaying floating point numbers changed slightly between Python 1.52 and Python 2.0 to reflect more of the nature of floating point: almost all floating point numbers can't be represented precisely on computers. The Python tutorial has a good section that taks more about floating point issues: http://www.python.org/doc/tut/node14.html To make this inprecision more visible to programmers, the implementers of Python 2.0 made a small change in Python's repr() string representation function: http://www.amk.ca/python/2.0/ Look around Section 10, and you should see something about this. By the way, if you call the 'str()' function on your number, Python will display the number in a way that you'd expect: ### >>> 2/5.0 0.40000000000000002 >>> str(2/5.0) '0.4' >>> print 2/5.0 0.4 ### and when you encounter the 'print' statement later on in Learning Python, you'll find that it does an implicit str() of anything you give it. Hope this helps! From pajer at iname.com Wed Jul 24 14:10:37 2002 From: pajer at iname.com (Gary Pajer) Date: Wed, 24 Jul 2002 18:10:37 GMT Subject: Python 2.2.1 Idle can't find _sre (Win98) Message-ID: Using Win98SE. Python 2.2 has been working fine. On a whim I upgraded to 2.2.1 today. Now Idle won't start. The traceback says that sre_compile.py fails at "import _sre" , No module named _sre. A search of google groups came up dry. Any idea? From marklists at mceahern.com Mon Jul 8 16:35:44 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 8 Jul 2002 15:35:44 -0500 Subject: subclassing int and accessing the value In-Reply-To: <200207082023.g68KNh904370@fourier.capital.edu> Message-ID: > Yes, I need to give this some more thought. If I actually end up using > this, it will need to interface with a database (MySQL or PostgreSQL) > so I need something that will be easy to back and forth between the > SQL representation and the Python representation. I use FixedPoint instances with PostgreSQL via pyPgSQL and that works quite well. Aahz has put up a copy of Tim Peters' FixedPoint here: http://starship.python.net/crew/aahz/FixedPoint.py Cheers, // mark - From h_j_fong at hotmail.com Sun Jul 28 22:49:42 2002 From: h_j_fong at hotmail.com (Chris) Date: Sun, 28 Jul 2002 22:49:42 -0400 Subject: wxRadioButtons logic (2 Qs) References: <1d2e2585.0207280850.95fe6a0@posting.google.com> <1n89kug8bhq0isbl7v96fh8sb2bnao91mv@4ax.com> Message-ID: Found my answer to Q2 too, based on side reading in RadioBox "wxRadioBox::SetLabel" Not surprisingly, this works for wxRadioButton as well. Sorry for boring anybody... Peace, Chris From b.maryniuk at forbis.lt Thu Jul 11 03:54:46 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 09:54:46 +0200 Subject: Python in the enterprise: Pros and cons In-Reply-To: References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: <200207110954.46390.b.maryniuk@forbis.lt> On Thursday 11 July 2002 07:09, Max Ischenko wrote: > After reading their ah...well...stupid > article about XP, I won't even bother to look at this. You are right. Better go bear and develope forward. :) -- Sincerely yours, Bogdan M. Maryniuck "I once witnessed a long-winded, month-long flamewar over the use of mice vs. trackballs...It was very silly." (By Matt Welsh) From fredrik at pythonware.com Mon Jul 22 14:14:36 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Jul 2002 18:14:36 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Does that reasoning not also apply to class instances? no. From emile at fenx.com Mon Jul 1 23:41:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Jul 2002 03:41:48 GMT Subject: python + simple graphics (lines, circles etc.) References: Message-ID: <0i9U8.385792$cQ3.25969@sccrnsc01> Andreas Daskalopoulos > What modules are avalaible for drawing simple things like lines, > circles etc.? I searched the documentation for a module but i didnt > find something. > Look into turtle: >>> from turtle import * >>> p = Pen() >>> p.color('red') >>> p.circle(25) >>> p.right(10) >>> p.color('blue') >>> p.circle(20) >>> -- Emile van Sebille emile at fenx.com --------- From schull at digitalgoods.com Sun Jul 28 01:01:42 2002 From: schull at digitalgoods.com (Jon Schull) Date: 27 Jul 2002 22:01:42 -0700 Subject: how do I create a full screen window with TkInter Message-ID: <2621b014.0207272101.7e796bc6@posting.google.com> What would I add to this snippet to ensure to have the image being displayed be all we see? (no titlebar, full size, etc.) class UI(Label): def __init__(self, master, im): if im.mode == "1": # bitmap image self.image = ImageTk.BitmapImage(im, foreground="white") Label.__init__(self, master, image=self.image, bg="black", bd=0) else: # photo image self.image = ImageTk.PhotoImage(im) Label.__init__(self, master, image=self.image, bd=0) import sys root=Tk() filename=r'c:\temp\capture5.jpg' im=Image.open(filename) UI(root,im).pack() root.mainloop() From aleax at aleax.it Thu Jul 25 07:14:07 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 11:14:07 GMT Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> <3D3FD318.7020406@mxm.dk> <3D3FD753.7050702@thomas-guettler.de> Message-ID: <34R%8.138298$vm5.4494921@news2.tin.it> Thomas Guettler wrote: ... > Yes, I can do foo=str(foo) myself before calling escape, > but this feature would hurt noone. Many Python functions expect to get arguments of specific types (or polymorphic to such types, i.e., supplying all necessary methods and operations with equal signatures). Having them accept arguments of wrong types, with silent coercion, would hurt all careful developers, by hiding bugs. Raising exceptions when objects of wrong types are mistakenly passed diagnoses such bugs earlier and enhances overall productivity. As you notice, explicit coercion is trivially simple to ask for explicitly, when that is what you want. Explicit is better than implicit. Python does not try to guess at what you may have meant. Errors should never pass silently, unless explicitly silenced. These guidelines WORK, when applied with good taste and pragmaticity. "Doing what I mean, for my tiny momentary convenience and at the cost of hiding possible errors" doesn't work -- specifically, it doesn't scale to serious software development. Python does scale. When you can make a specific case for some relaxing of argument type rules being specifically useful, please do -- that's what PEPs (Python Enhancement Proposals) are for, among other things. But in this case, I don't think you've made a good point (IMHO). Alex From marklists at mceahern.com Tue Jul 23 18:17:59 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 23 Jul 2002 17:17:59 -0500 Subject: list to string In-Reply-To: Message-ID: > What's the something? This is probably so obvious, i'm going to feel dumb, > but I havn't been able to find anything in any doc I've looked at. As the redundant answers pour in, I invite everyone to share in this promise with me: I will not start another stupid thread about whether join should be an attribute of string. Repeat three times and do four hail marys. // mark - From johnroth at ameritech.net Wed Jul 31 09:35:40 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 31 Jul 2002 09:35:40 -0400 Subject: Let's Talk About Lambda Functions! References: Message-ID: "Ian Bicking" wrote in message news:mailman.1028076887.27215.python-list at python.org... > On Tue, 2002-07-30 at 18:22, John Roth wrote: > > > A method is just a function that is bound to a class variable. So you > > > can do something like: > > > > > > class X: > > > pass > > > > > > X.func = lambda self, x: x * 2 > > > x = X() > > > x.func(10) > > > ==> 20 > > > > > > In fact, you can even do: > > > > > > class X: > > > func = lambda self, x: x * 2 > > > > Unfortunately, that won't work. The word 'self' is not > > magic - using it doesn't convert a function to a method. > > Fortunately it does work! You didn't read my first sentence. Those > (working) examples don't rely on the name "self" in the argument list. > They rely on the fact that a function is being put in a *class* > attribute (this doesn't work the same way if you put it in an instance > attribute). I'm not certain of context here, because your reply didn't associate properly with my original post, so if I wander a bit, please excuse. The issue I was addressing was putting an anonymous function (or method) in an expression, without any fancy conditions. In other words, putting it where you would normally want to - with lots of other code within a class. I wasn't addressing a corner condition. When you're writing a method in a class, and you want to create an anonymous function within the code of that method, how do you tell the compiler that you want a method instead? That is the question. It may turn out to have a trivial answer, but as I think I said in the original post, my knowledge of the details of Python at that level is insufficient. What I am certain of is that simply saying 'self' as the first parameter isn't sufficient for the compiler to mark it as a method (which is a different kind of object than a function!) What I'm not certain of is whether it matters. John Roth > > Ian > > > From cce at clarkevans.com Thu Jul 25 00:21:19 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Thu, 25 Jul 2002 00:21:19 -0400 Subject: ANN: PyYaml v0.21 Message-ID: <20020725002119.A98594@doublegemini.com> The pure Python binding for YAML has had a few improvements: - now parses timestamps (D4) - includes yaml.timestamp data type - several bug fixes http://yaml.org/python/PyYaml_25jul2002.tgz PyYaml is still a work-in-progress, so expect changes, although the specification itself is very stable and will not change much any more. This version still lacks support for "flow" styles (A5,A6) and good support for data types; but alas, these will come with time. If you have time to hack... by all means! YAML(tm) (rhymes with "camel") is a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages such as Perl and Python. YAML is optimized for data serialization, configuration settings, log files, Internet messaging and filtering. Best, Clark -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From whisper at oz.net Tue Jul 30 14:34:57 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 30 Jul 2002 11:34:57 -0700 Subject: Leo.py: Some Thoughts In-Reply-To: Message-ID: > Fredrik, while you are being so helpful, is there some way to use an > embedded window to render HTML or postscript? Anything else that might > help? > > Again, many thanks for lifting the blinders from my eyes! > > Edward Are you familiar with D. Richard Hipp's TkHTML control? Only sticking point is that it's GPL (alas, wish it where GLL). Someone on c.l.p has done/is working on a Python binding for it. This same person has also done a binding for Jeff Hobbs' TkTable (grid) control... Dave LeBlanc Seattle, WA USA From just at xs4all.nl Tue Jul 23 13:58:54 2002 From: just at xs4all.nl (Just) Date: Tue, 23 Jul 2002 19:58:54 +0200 Subject: how to count lines in a file ? References: Message-ID: In article , "Denis S. Otkidach" wrote: > On Tue, 23 Jul 2002, Shagshag13 wrote: > > S> hello, > S> > S> i need to count lines in a file (that i *can't* keep in > S> memory, so can't use readlines()) > > fp = open(filename) > it = iter(fp) > try: > while it.next(): > count += 1 > except StopIteration: > pass How is that better than count = 0 for line in open(filename): count += 1 ? Just From dale at riverhall.NOTHANKS.co.uk Wed Jul 24 13:35:37 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Wed, 24 Jul 2002 18:35:37 +0100 Subject: Simple HTML classes Message-ID: <47ptjushoni8bfqurttm86sgt8bm6tge84@4ax.com> We need a bunch of light-weight HTML classes to build web pages - especially forms. These will work with the CGI module so that the forms related classes are bi-directional. Before we start writing them them, I was wondering if anyone had done anything similar or there was a module I'd overlooked. I can't believe this hasn't been tackled before. Thanks -- Dale Strickland-Clark Riverhall Systems Ltd From mark at mceahern.com Fri Jul 12 16:05:42 2002 From: mark at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 15:05:42 -0500 Subject: switch recipe? In-Reply-To: Message-ID: > out of curiosity, what happens when n reaches the end of the > int/long/whatever that stores it? My guess is this will run forever--if you let it. Perhaps it should allow an optional sentinel? The assumption is the caller is responsible for using it wisely. > while the above code is a nice sample, the below code should not > be given to people learning the language, it uses way too many tricks. I appreciate your opinion and I mean and say this with respect: One of the joys of Python is that even supposedly advanced tricks are eminently explorable. I would rather not patronize someone and I'd rather make the mistake of offering them too much than too little. Besides, even if they can't get it, they're not the only ones reading this list now or in the future. Ultimately, I can trace this sentiment back to something very personal: That's precisely how I'd want to be treated. Wouldn't you? I mean, it's not like I vomitted some obscurified black hole of context-laden punctuation (i.e., Perl) on them. > Plus one letter variable names are a pain. I go back and forth on this one. Presumably, you don't mean for counters and the like (e.g., i, n). I tend to use one-letter variable names when locals() is very small, the function is short (e.g., 5-10 lines) and the meaning is painfully obvious. Perhaps a bad habit? E.g., s, imho, is better than text or string for a string. I'm not trying to save typing, so much. I strive for clarity of intent at the level of module, class, function names. So that I don't feel so bad using one-letter variable names. But, reasonable people disagree and I enjoy seeing alternative styles, discussing them. > switch is an interesting idea, definately needs a new name. Maybe loop and make_loop? At least then the danger of an infinite one is explicit? Thanks for the comments. Cheers, // mark - From rdiaz at cnio.es Mon Jul 22 10:22:10 2002 From: rdiaz at cnio.es (Ramon Diaz) Date: Mon, 22 Jul 2002 16:22:10 +0200 Subject: three questions about IDLE Message-ID: <200207221622.10551.rdiaz@cnio.es> Dear All, I have three questions about IDLE (under Linux; I am running Python 2.2.1, and IDLE's version is 0.8). 1. I think that Alt-W should be "copy selection"; however, what this key combination produces is the opening of the "Windows" submenu. How can I fix this? If I need to change the key mappings, I would rather not break the mapping of Alt to Meta modifier (since I want XEmacs and other programs to cotinue using Alt as Meta). [Note that the alternative "Esc-W", which is listed in "Using IDLE", by D. Harms, doesn't seem to work either, becasue that delets the selection]. 2. When editing in a window, is it possible to execute only some part of the code instead of having the complete window being executed (using Ctrl + F5)? (I am thinking about something like the C-c | of XEmacs). 3. Is there a way to run a piece of code without having to save the file where the editing is being done? I understand is only a "C-x C-s" delay, but... Thanks a lot, -- Ram?n D?az-Uriarte Unidad de Bioinform?tica Centro Nacional de Investigaciones Oncol?gicas (CNIO) Melchor Fern?ndez Almagro, 3 28029 Madrid (Spain) http://bioinfo.cnio.es From dale at riverhall.NOTHANKS.co.uk Fri Jul 26 19:25:19 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 27 Jul 2002 00:25:19 +0100 Subject: Challenge/Response authentication References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com> <7xeldq1zzp.fsf@ruckus.brouhaha.com> <7xptxawajw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >I'm not sure I understand this--where does the challenge come from? > >What stops someone from intercepting and re-using the authenticating URL? > >Maybe you want to read the HTTP spec for digest authentication and >do what it says. But use HMAC instead of simply appending a password >to the challenge. I see the process working something like this: 1. The client system calls a CGI script on our server and retrieves a challenge string and thus initiates a session 2. The client system then constructs the frame page with its response in the url for the frame source (among other things). 3. If authenticated, we display the requested forms (in sequence), passing control to a pre-aranged url at the end of processing. This isn't a sensitive application. If someone breaks into it, all they a rewarded with is a series of forms for fill in. We just want to limit the scope for idle buggering about. -- Dale Strickland-Clark Riverhall Systems Ltd From sholden at holdenweb.com Mon Jul 22 09:18:55 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 22 Jul 2002 09:18:55 -0400 Subject: Making code 2.1 compatible References: Message-ID: "Donn Cave" wrote in message news:ah1ik8$ebm$1 at nntp6.u.washington.edu... > Quoth Tim Peters : > ...(quoting me) > |> Matter of perspective. I would probably have picked 2.2 if it > |> had been left to me, just because it's current. But when I've > |> proposed it in the past I've suggested the recently out-of-current > |> release, because that makes it immediately an issue. > | > | Toward what end? They're business people, not Crusaders . > > Oh, don't be so hard on them, sure they're crusaders (though not in > the sense of the European military adventures some centuries back or > the popular music group known in better days as Jazz Crusaders.) > They aren't going to be as hasty and radical, but I bet you won't be > disappointed, they're on their way. (Now if a certain Redmond, Wa. > software company were in the host, I'd sweat it, but "business people" > here seems to be actually a pretty respectable assemblage.) > Well, as business people there's nothing to stop them keeping their (early-version-compatible) source in such a way that version upgrade is a relatively simple matter. "Relatively" means that they probably aren't expecting to do such engineering work for less popular packages, which wouldn't justify the effort. If Python were ever to sprout macroprocessing capabilities, their greatest value to me would perhaps be in allowing more flexibility when producing multi-platform mullti-version code. Of course, such a mechanism cannot be part of Python until Guido goes back in the time machine and fixes things so it was in from the start. I'm tempted to apply for PBF membership just to lower the tone (though if they'd have me, would I want to join?). marx-brother-fan-before-python-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 12:29:36 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 12:29:36 -0400 Subject: Just fyi - test of modified python core. Message-ID: <3D208370.5070106@removethisandallhyphens-o-n-e.net> This is just an FYI regarding my latest experiment to speed up python. After doing some research and finding that gcc is capable of having pointers to labels in C/C++ code, I decided to try something: I modified the python interpreter's main loop to utilize an array of label pointers whose indices were equal to the bytecode they were for. Thus, in pseudo code, I change this: switch (bytecode) case BYTECODE1: do something; break; ----------------------------- into: [label array for bytecodes] goto labelarray[bytecode]; BYTECODE1: do something; goto end_loop; ----------------------------- The results of this change were not as expected... as you can see from the pystone results below. avg results python2.2: 7142. python2.2-experimental: 7142. ------------------------------------------ Conclusion: this gcc compiler trick is useless in the main loop, since gcc is apparently either A) generating code equivilent to a label-array-goto for the main switch or B) producing code that runs at equivilent speed. I'm leaning towards A. Ah well, at least it only took a few hours to find out ;) -c From bokr at oz.net Wed Jul 17 13:01:10 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2002 17:01:10 GMT Subject: get a list printed in hexadecimal notation References: Message-ID: On Wed, 17 Jul 2002 12:07:55 +0200, Oliver Eichler wrote: >Hi > >Is it possible to print a mixed list with strings and numbers and having the >numbers printed as hexadecimal notation? > >something like: > >>>>l = ('spam',10,15,'more spam') >>>>print l >('spam',0xA,0xF,'more spam') > >or similar... > >The only way I could think of is to write my own print function. Is there an >easy way? > >>> def hexiseq(seq): ... if isinstance(seq,int): return hex(seq) ... if isinstance(seq,tuple): lb,rb = '(', ')' ... elif isinstance(seq,list): lb,rb = '[', ']' ... else: return repr(seq) ... ret = [] ... for x in seq: ret.append(hexiseq(x)) ... return lb + ', '.join(ret) + rb ... >>> hexiseq(('spam',10,15,'more spam')) "('spam', 0xa, 0xf, 'more spam')" >>> hexiseq(('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)) "('spam', 0xa, 0xf, 'more spam', ['nested', 0xffff, 'spam'], 'spam', 0xff)" >>> print hexiseq(('spam',10,15,'more spam')) ('spam', 0xa, 0xf, 'more spam') >>> print hexiseq(('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)) ('spam', 0xa, 0xf, 'more spam', ['nested', 0xffff, 'spam'], 'spam', 0xff) Regards, Bengt Richter From gerhard.haering at gmx.de Sun Jul 14 11:19:12 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 14 Jul 2002 17:19:12 +0200 Subject: Is there a Python text-editor suitable to embed in a VB app (newbie question) In-Reply-To: <1026659235.9237.0.nnrp-10.3e314eb6@news.demon.co.uk> References: <1026659235.9237.0.nnrp-10.3e314eb6@news.demon.co.uk> Message-ID: <20020714151911.GA1752@lilith.my-fqdn.de> * david evans [2002-07-14 16:07 +0100]: > I'm very new to Python (nearly 10 day experience now) but thanks to "Python > Programming on Win32" I've been able to construct a VB prototype, ODBC based > development tool with a Python "scripting" cabability. > > My script editor is really sad though. It's simply a MS text box. > > Is there a way that I can embed the Pythonwin editor (or similar, existing, > language-aware editor) into a VB project? > > Any suggestions or pointers (other than write it all in Python -- I'm not > good enough to do that) will be gratefully received. Looks like that's possible with Scintilla, which is a really great editor (I believe it's also what's currently used in PythonWin): http://www.scintilla.org/ http://www.scintilla.org/SciTry.vb Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From ld at nospam.com Tue Jul 9 16:11:57 2002 From: ld at nospam.com (Larry) Date: Tue, 09 Jul 2002 20:11:57 GMT Subject: Clean Exit from Socket/Program References: <3D2A9F81.50702@nowhere.org> Message-ID: "Bryan Olson" wrote in message > To terminate socket transmission cleanly, each side should do > sock.shutdown(1) which terminates sending, and then read until the > termination of the other's transmission, which you can detect by a > recv() that successfully returns zero bytes. Then you can close() or > destroy the socket. Contrary to popular belief, doing a shutdown(0) (of > the receive side) before a close() is unimportant. The problem here is that I cannot communicate with the other socket. In other words, when I connect, data starts to flow. And data never stops until the other side sees that I am not there anymore. So, what I need to do, is somehow signal the server socket and make him think I am not there, while still being able to process whatever is still in my buffers so I don't lose it. Then I could shut down. Larry From james.kew at btinternet.com Wed Jul 17 18:52:50 2002 From: james.kew at btinternet.com (James Kew) Date: Wed, 17 Jul 2002 23:52:50 +0100 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: "Clark C . Evans" wrote in message news:mailman.1026869066.6456.python-list at python.org... > I think the hype of XML will start to backfire as people > realize that its function isn't magical, and that their > particular solution isn't all that useable. The information > model fits documents well, but is a poor match for object > serialization, which is 90% of the use cases programmers > face. Um: 90%? What sort of use cases do you see programmers forcing XML into? Just curious: I fall into the "XML as poor-man's database/parser" camp at the moment but I'm finding that for a poor man's solution it does quite a good job with not much programmer effort to glue it together. Should I feel guilty for not learning lex/yacc? Or should I rejoice in my batteries-included (or at least, batteries-downloaded-from-SourceForge) pragmatism? I'm feeling a bit of both at the moment... James From clpy at snakefarm.org Sat Jul 20 03:05:12 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Sat, 20 Jul 2002 09:05:12 +0200 Subject: file modification esoterica References: Message-ID: <3D390BA8.8020806@snakefarm.org> Grant Griffin wrote: > Second, what is the best way to "touch" a file, that is, update its modification > time or "mtime" to the current time? How about os.utime()? cg. From sholden at holdenweb.com Thu Jul 25 10:22:35 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 25 Jul 2002 10:22:35 -0400 Subject: asyncore: limiting number of simultaneous connections? References: Message-ID: wrote in message news:mailman.1027013966.30611.python-list at python.org... > On Wed, 17 Jul 2002, Jason R.Mastaler wrote: > > > I'm building a server based on asynchat/asyncore. The > > documentation for these modules is sketchy at best, and I couldn't > > find an answer to this after browsing through the code. > > Just thought I'd mention that the development version of the docs has updated the asyncore documentation, as well as providing asynchat docs for the first time. I made these changes, and I'd appreciate feedback if you have any -- there's still time to make further changes to improve clarity. > > Is there an easy way to limit the number of simultaneous connections > > to such a server? My preliminary tests indicate that it will happily > > accept as many connections as the host system will allow, which is not > > good. I'd like to be able to specify a ceiling on this. > > You should be able to just implement your own readable method in the > listening socket, e.g. (untested and assumes your listening socket is > derived from asnychat.async_chat): > > def readable(self): > if not self.AllowedToAcceptMoreConnections(): # You implement this > return 0 > return asynchat.async_chat.readable(self) > Technically, of course, this isn't strictly going to limit the number of connections to any given maximum since it only determines under what conditions the listening socket returns readable(), and readable() is used by asyncore to determine whether the socket should be added to the set for which a read condition is accepted. Any time the socket is so listed (in the select.select() arguments) any number of simultaneous connections might occur, though this is unlikely. The problem with doing network code well is coping with the unlikely (low-probability) events that occur all the time! ;-) > For other reasons I used a different approach in one program: have the > accepting socket be on another thread, and it controlled access that way > (when it was ok it have another connection it would accept it and add it > to asyncore with: > > asynchat.async_chat.__init__(self, conn) > > Also, you can check len(asyncore.socket_map) to see how many sockets it is > currently handling. Assuming you're using the default map. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From coventry at removethisandallhyphens-o-n-e.net Tue Jul 9 23:26:26 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Tue, 09 Jul 2002 23:26:26 -0400 Subject: Why self? References: <090720021439257166%pecora@anvil.nrl.navy.mil> <7934d084.0207091739.4720aafc@posting.google.com> Message-ID: <3D2BA962.3070901@removethisandallhyphens-o-n-e.net> > 2) How do you reference variables that aren't in the specified > namespace without a second keyword! I see what you're saying: assume you enforce the same sort of namespace-lookup rules in place, extended to the 'with' keyword: a) look in the object specified by the with clause for the name b) look in the local scope c) look in the global scope This limits the effectiveness of 'with' severely. > 3) Issue 2 becomes critical when you what to deal with temporary > results that you definately want discarded along with the current > local scope. So maybe only rvalues are affected ie. > > with self: > self.y = x**2 * t/z + a * FFT(tseries) > > might be better, but then the inconsistency bites. Yes, 'the inconsistency bites', too much. why not simply set a local to reference self? a = self a.y = a.x**2 * a.t/a.z + a.a * FFT(a.tseries) This is still not as elegant (from certain points of view) as a 'with' capability, but results in much shorter, easier to read code, and is equivalent to the evolved 'with' clause utilizing 'as' to specify a true name for the new namespace... with self as a: a.y = a.x**2 * a.t/a.z + a.a * FFT(a.tseries) this 'as' statement would be required, most likely, to avoid having 'magic names' for the default namespaces, to allow access to a local or global of the same name... such as Zope's PARENT[] list of namespaces. If we're going to add magic names, maybe some like $_ and $@ should be considered? j/k ;) anyway, I did a Very simply test to ensure binding a local to self works. and it does: >>> class sue: ... a = 5 ... def test(self, g): ... t = self ... t.a = g ... def output(self): ... print self.a ... >>> pp = sue() >>> pp.test(3) >>> pp.output() 3 >>> prepared-to-be-shot, -c > > Maybe this is a good idea? More likely I'm about to learn which > critical basic flaw I've missed. > > at-least-I-will-get-to-learn-something-ly yours > > Andrae Muys > From duncan at NOSPAMrcp.co.uk Wed Jul 31 05:06:02 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 31 Jul 2002 09:06:02 +0000 (UTC) Subject: Using += in a loop References: <3d46d722.18669034@netnews.worldnet.att.net> <3d46e4d4$0$94903$e4fe514c@dreader3.news.xs4all.nl> Message-ID: Yigal Duppen wrote in news:3d46e4d4$0$94903$e4fe514c at dreader3.news.xs4all.nl: > Something like this should be faster: > > t_list = [] > s5_list = [] > for i in range(0, 5): > q = breaks[break][i] > x = mkup(cost * q, list * q) > if x[0]: > t_list.append(x[0]/q) > else: > t_list.append(0) > > if x[1]: > s5_list += [ ',"' , x[1] , '"'] > else: > s5_list.append(',"-"') > t_list += (0, 0) > s5_list.append(',"-","-"') > > # and convert both lists to the desired types > t = tuple(t_list) > s5 = "".join(s5_list) > > > No clue how much faster; that's what profile is for. A few other suggestions that might or might not help: I'm assuming the real code is inside a function, if not put it there at once (that will speed it up a lot). If mkup is simply returning two values, then use tuple unpacking to assign the results directly into two variables instead of indexing. This allows you to give the results meaningful names. If the first result of mkup is always numeric, then you can collapse the if statement down to a single append. Optimise out the references to the append method from inside the loop. Avoid using range in a for loop. 'i' isn't needed here at all. All of which together (apart from the function) give you something like: t_list, s5_list = [], [] t_append, s_append = t_list.append, s5_list.append for q in breaks[break]: numeric, stringval = mkup(cost * q, list * q) t_append(numeric and numeric/q) s_append(',"%s"' % stringval or "-") t_list += (0, 0) s_append(',"-","-"') # and convert both lists to the desired types t = tuple(t_list) s5 = "".join(s5_list) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bokr at oz.net Wed Jul 17 03:42:19 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2002 07:42:19 GMT Subject: Making code faster References: <3d3445f9_7@news.newsgroups.com> Message-ID: On Tue, 16 Jul 2002 18:20:23 +0200, JB wrote: >How can I make the following code faster? I open a (text) >file and read the lines in the file. The lines of the file >have the form > >[,] - Do you mean that literally? I.e., would "['abc','def']\n" be a valid example? - Why do you have to eval() it? That is probably timeconsuming compared to alternatives. - Were the lines created by repr(someList)? - Are all the s actually quoted character sequences, or are there numbers too? - Are there always two elements in the list? > >After the lines have been loaded, I set up a new list via >the function tmp1. > > i = -1 > print 'loading file' > def tmp1(s): > global i > i += 1 > return QSimpleViewItem(i,self.sv.lv.newColor,eval(s)) I can't tell what the enclosing context is that defines 'self', but you are repeating a lot of lookup doing self.sv.lv.newColor on every call instead if doing it once at def time. Likewise the global counter is not as fast as a local one. To look up once, you could use a default arg, e.g., # untested! def tmp1(s, color=self.sv.lv.newColor): global i i += 1 return QSimpleViewItem(i,color,eval(s)) To get the counter into a local context as well, you could try a factory function to return a tmp1 function with local lookups from a closure. # untested! def get_tmp1(color): i = -1 def tmp1(evald_s): # expect arg equivalent of eval(s) already done i += 1 return QSimpleViewItem(i,color,evald_s) return tmp1 > > try: > myfile = open(filename) > except: > pass > else: > tmp = myfile.readlines() > print 'lines loaded' > datei.close() ^^^^^-- not myfile? if you must eval the file lines (which I doubt, and which typically carries security dangers), I'd try mapping eval by itself first, like tmp = map(eval,tmp) then get the function from the factory tmp1 = get_tmp1(self.sv.lv.newColor) # gets the color once > self.sv.lv.rows = map(tmp1,tmp) > self.sv.lv.visible = range(len(self.sv.lv.rows)) > print 'lines decoded',self.sv.lv.rows[0].col[0] > >Any ideas? It is astonishing that loading the lines from >external storage takes much less time than the mapping >itself! > I suspect eval() is costing you a big part, unless QSimpleViewItem() has a complicated constructor/init function. Spec the file line format in detail, so we can eliminate eval. Regards, Bengt Richter From martin at v.loewis.de Mon Jul 22 01:28:06 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 22 Jul 2002 07:28:06 +0200 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Is there a way to do that? You can put a callable object in sys.modules. Module objects themselves are not callable. > If there's not a way to do this already, maybe it's a reasonable > addition. Maybe not. Why do you need this? Regards, Martin From ianb at colorstudy.com Tue Jul 30 20:53:38 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 30 Jul 2002 19:53:38 -0500 Subject: Let's Talk About Lambda Functions! In-Reply-To: References: <20020726024901.2725.176.Mailman@mail.python.org><3D41AC9E.6080103@onsitetec h.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: <1028076819.578.1164.camel@lothlorien.colorstudy.net> On Tue, 2002-07-30 at 18:22, John Roth wrote: > > A method is just a function that is bound to a class variable. So you > > can do something like: > > > > class X: > > pass > > > > X.func = lambda self, x: x * 2 > > x = X() > > x.func(10) > > ==> 20 > > > > In fact, you can even do: > > > > class X: > > func = lambda self, x: x * 2 > > Unfortunately, that won't work. The word 'self' is not > magic - using it doesn't convert a function to a method. Fortunately it does work! You didn't read my first sentence. Those (working) examples don't rely on the name "self" in the argument list. They rely on the fact that a function is being put in a *class* attribute (this doesn't work the same way if you put it in an instance attribute). Ian From fredrik at pythonware.com Sat Jul 13 09:10:00 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 13:10:00 GMT Subject: Input again References: Message-ID: Mark McEahern wrote: > input is a keyword; probably not a good idea to use > it as a variable name. no, it's not: it's a built-in function. it's perfectly okay to override it, if you feel like it. (as long as you don't complain on comp.lang.python when you find that you cannot use the original function in the same program...) From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 00:32:25 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 00:32:25 -0400 Subject: private References: Message-ID: <3D1FDB59.6020309@removethisandallhyphens-o-n-e.net> >>Kind of off-topic, but this got me curious. The only way I >>could think of is to assume (which I think is always true) >>that the private data members are in order from the starting >>address so based on the offset from the address of the object >>you could access each one. >> > > .. and of course #define private public, or just go in and edit the .h > file... True, but you could edit gcc to allow access to private members of a C++ class, could you not? Hrm, this issue probably isn't whether it is possible to hack around an implementation of 'private', but more about having a real 'private' type/functionality. Right now, we hack to put simulate private - why not make other hack to work around it? -c From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 18:39:45 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 15:39:45 -0700 Subject: HTML DOM parser? References: <7xwursj0a4.fsf@ruckus.brouhaha.com> <3D373D7C.2237E7A3@engcorp.com> Message-ID: <7xvg7ck6dq.fsf@ruckus.brouhaha.com> Peter Hansen writes: > How about automating IE using Python? > > from win32com.client import DispatchEx > > ie = DispatchEx('internetexplorer.application') > ie.visible = 1 > ie.navigate('http://www.nightsong.com') > dom = ie.document > > etc... > > Access to the DOM tree of the document might be too slow for your > needs, but if it's not, you definitely get a lot of bang for the buck... That's a really interesting idea and I might try it. I had been thinking in terms of a Linux solution, but automating IE might be ok for this particular application. Thanks. From sholden at holdenweb.com Sat Jul 27 00:12:30 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:12:30 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: "Alex Martelli" wrote in message news:41j09.125397$Jj7.2891527 at news1.tin.it... > Robb Shecter wrote: > > > But to really answer you - I like lambdas and think lambdas can add > > clarity because their scope directly reflects their 'scope'. (Make > > sense?) > > Sorry, not to me. Take a typical bug sometimes posted here, such as: > > for word in 'fee fie foo fum'.split(): > Button(frame, command=lambda: print word) > > The poster is typically nonplusses that all buttons print 'fum'. > I would be nonplussed if that code even *compiled*, given that "print" is a keyword and lambda takes an expression not a statement. > Lambda's scope (or 'scope') has taken another victim. > This is not to say, of course, that newbies don't try to write exactly such incorrect code, and this is probably one of the reasons why Guido continues to suggest it's a wart (albeit one we're going to have to continue to live with). > > Using a closure instead of the lambda: > > def makeprinter(word): > def printword(): print word > return printword > > for word in 'fee fie foo fum'.split(): > Button(frame, command=makeprinter(word)) > > is one of several ways to make the bug disappear (another is to > use a "lambda word=word: print word" snapshot-trick, but that > seems to fly in the face of your liking lambda's "scope"...?). > Closures' "scopes" can be said to directly reflect what they > should reflect. I can't see how you can claim this for lambda. > not-like-you-to-propagate-syntax-errors-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From karczma at info.unicaen.fr Mon Jul 8 06:18:39 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Mon, 08 Jul 2002 12:18:39 +0200 Subject: the meaning of life References: <3eeda89d.0207071133.4c07a86e@posting.google.com> Message-ID: <3D2966FF.8BD3FDD8@info.unicaen.fr> Gerhard H?ring wrote: > > Somebody whos parents couldn't think of any better name than "Thinkit": > > Take a break from python and realize the meaning of ALL conscious beings. > > Wow! You just discovered the meaning of life!!!!11. You should get a > noble prize. I just can't think of any suitable category. > > > [...] > > *PLONK* Don't plonk yet. Have you heard about Life, the programming language? (Perhaps here: http://www-white.media.mit.edu/~tpminka/PLE/life/life.html since the site http://www.isg.sfu.ca/life is dead, which I find quite appropriate; the Life must eventually die...) This is (ehm... was?) a multi-paradigmatic language: logic, functions, inheritance, etc. Well, Python is not so far from such noble (Nobel?) ambitions, although the Logic Sphere with non-instantiated variables and backtracking still remains to be implemented. Perhaps in a stackless Way of Life? Anyway, once I try to give a short unofficial seminar on it, and after a while people exploded: "My goodness! What is the meaning of all that!?" But it was obviously pointless to discuss the Meaning of Life, so we turned to more mundane affairs. Such as contributing to the pollution of newsgroups by irrelevant postings. Thank you for your attention. Jerzy Karczmarczuk Caen, France From imbosol at vt.edu Fri Jul 26 18:59:18 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 26 Jul 2002 18:59:18 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: Alex Martelli wrote: > Robb Shecter wrote: > >> But to really answer you - I like lambdas and think lambdas can add >> clarity because their scope directly reflects their 'scope'. (Make >> sense?) > > Sorry, not to me. Take a typical bug sometimes posted here, such as: > > for word in 'fee fie foo fum'.split(): > Button(frame, command=lambda: print word) > > The poster is typically nonplusses that all buttons print 'fum'. I imagine it's more likely that the poster would be nonplussed that it produced a syntax error. :) -- CARL BANKS http://www.aerojockey.com From emile at fenx.com Thu Jul 18 09:23:16 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Jul 2002 13:23:16 GMT Subject: Sorting list of objects on arbitrary attribute References: <3D36AD49.2020305@mxm.dk> Message-ID: <8jzZ8.576968$cQ3.54422@sccrnsc01> Max M > But usually when I think up something clever it is allready included in > the standard library, or somebody has a 2 liner which does the same thing. aList.sort(lambda x,y: cmp( (x.name, x.age, x.rand) , (y.name, y.age, y.rand) ) ) -- Emile van Sebille emile at fenx.com --------- From b.maryniuk at forbis.lt Thu Jul 25 04:24:42 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 25 Jul 2002 10:24:42 +0200 Subject: how to count lines in a file ? In-Reply-To: <200207251015.40671.rjones@ekit-inc.com> References: <200207251015.40671.rjones@ekit-inc.com> Message-ID: <200207251024.42996.b.maryniuk@forbis.lt> On Thursday 25 July 2002 02:15, Richard Jones wrote: > As far as the community is concerned, the file is explicitly closed because > no reference to it is retained. No, this is not documented. Then again, the > documentation makes no claims about any sort of behaviour when the object > is collected. The community has, reasonably enough I think, always assumed > (for a very long time in many public ways) that the file is closed when it > is collected! As to Jython not closing the file - well, I'd consider that a > bug... Umm... Richard, I just've played over all we talking about in not best way, but in anyway I'm little hooked and I would like to know what's _exactly_ going on: *bo at spectator:(~) python Python 2.2 (#1, Dec 23 2001, 09:30:32) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gc >>> len(gc.get_objects()) 844 >>> a = open('/etc/passwd') >>> len(gc.get_objects()) 844 >>> del a >>> len(gc.get_objects()) 844 >>> #Huh? >>> >>> a = open('/etc/passwd').readlines() >>> len(gc.get_objects()) 871 >>> #Yeppiie! >>> >>> del a >>> len(gc.get_objects()) 870 >>> a = open('/etc/passwd') >>> len(gc.get_objects()) 870 >>> a.close() >>> len(gc.get_objects()) 870 >>> a >>> del a >>> len(gc.get_objects()) 870 >>> #Huh? -- Sincerely yours, Bogdan M. Maryniuck "How should I know if it works? That's what beta testers are for. I only coded it." (Attributed to Linus Torvalds, somewhere in a posting) From cliechti at gmx.net Fri Jul 5 20:45:40 2002 From: cliechti at gmx.net (Chris Liechti) Date: 6 Jul 2002 02:45:40 +0200 Subject: Client sockets without os.fork() References: Message-ID: "Larry" wrote in news:MDqV8.426072$cQ3.29617 at sccrnsc01: > When a client connects in unix/linux, I could simply use the os.fork() > to create a nice new process to deal with the newly requested > session. > > I now have a need to do this in windows. Can anyone relay a fairly > easy way to put the newly created socket into it's own thread so that > it can go about doing it's business while the orginal daemon can sit > and listen for new connections? have a look at the threading module. that works the same way on win & linux. chris -- Chris From whisper at oz.net Fri Jul 19 19:34:37 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 19 Jul 2002 16:34:37 -0700 Subject: Mastering Regular Expressions 2nd Ed. Message-ID: Book. It's out. From O'Reilly. See http://www.oreillynet.com/pub/a/network/2002/07/15/regexp.html Claims extensive Python re coverage. In addition to the other usual suspects, also covers Java, Ruby, php and .net. Hope it's as good as the first one was/is! David LeBlanc Seattle, WA USA From nospam at nonesuch.com Wed Jul 31 16:38:37 2002 From: nospam at nonesuch.com (David Smith) Date: Wed, 31 Jul 2002 13:38:37 -0700 Subject: C++/Python version problems? Message-ID: <3D484ACD.7030503@nonesuch.com> I'm running Python 2.2.1 under Linux, and successfully interfaced my C++ procedures into Python. Then I got more aggressive with the templates, and g++2.95 wouldn't compile it. So I got g++ 3.0, and it compiles -- I used distutils/setup.py to make the shared object file. But, now when I try to import my module, I get the error message: ImportError: ./cfuncs.so: undefined symbol: __gxx_personality_v0 Does this maybe have to do with Python being compiled under an older g++, or being linked with an older library? Any suggestions as to what I should do? -- David Smith drs at labs dot agilent dot com <- hopefully doesn't trigger spambots From opengeometry at NOSPAM.yahoo.ca Sun Jul 7 18:30:55 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 7 Jul 2002 22:30:55 GMT Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> <3d28bdb0.71631360@news.dsl.pipex.com> Message-ID: Simon Foster wrote: > On 8 Jul 2002 00:07:47 +0200, Chris Liechti wrote: > >>'cause split() drops the empty part at the end: >>>>> '1\n2\n3\n'.split() >>['1', '2', '3'] >>>>> '1\n2\n3\n'.split('\n') >>['1', '2', '3', ''] >> > > > I see it, but I don't see why? What is the explanation for this? It > seems at odds with the documentation. '1\n2\n3\n'.split() works as follows: 1\n2\n3\n -> 1\n2\n3 -> 1 \n 2 \n 3 -> 1 2 3 '1\n2\n3\n'.split('\n') works as follows: 1\n2\n3\n -> 1 \n 2 \n 3 \n -> 1 2 3 '' where the last '\n' separates '3' and '' (null). -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From lellinghaus at yahoo.com Wed Jul 10 11:24:10 2002 From: lellinghaus at yahoo.com (Lance Ellinghaus) Date: Wed, 10 Jul 2002 08:24:10 -0700 (PDT) Subject: expect module and/or functionality? Or SSH wrapper module? In-Reply-To: <68709B52CA2675FB.DA66E2B49118728A.A93C4D4E1CA0B0B6@lp.airnews.net> Message-ID: <20020710152410.64977.qmail@web20910.mail.yahoo.com> See my comments below... --- Cameron Laird wrote: > In article , > Michael Hudson wrote: > >claird at starbase.neosoft.com (Cameron Laird) writes: > > > >> If not, no, you can't Expect with pure Python; there's no > >> practical way to get the pseudoterminal munging right without > >> calls into the C run-time library that Python itself can't > >> access. > > > >Huh? You have openpty, forkpty, ioctl, setsid, setpgrp, ... what > more > >do you want? > . > . > . > World peace. I'm concluding my counsel was ill-advised; > maybe people shouldn't be listening to me. As of 2.2, > (now-deprecated) pty was still the distribution module, > not openpty or forkpty. I fear that my pettiness came > across as a reflection on the great work done by Lance > Ellinghaus, Thomas Wouters, and others on these modules. > This would be an injustice. I overreacted to early re- > leases that didn't work smoothly for other-than-Linux, > and/or were not installed by default. > > I do want to emphasize the distinction between the modules > you've listed above and, for example, PySSH, which operates > at a higher level, as does Expect, also. As a programming > interface, openpty, forkpty, and so on are rather Unix- > centric. Thank you for the compliment! It is true that many Non-Linux systems do not provide the necessary functions to make it work easily. Solaris does not include openpty() and forkpty(). This makes it difficult to create a true Expect library in Python. I added this functionality to the posix module and submitted the diffs to the Python Dev group (and promptly got screamed at by someone there for posting it there) and have also now posted it to the Patches page on sourceforge. Maybe it will someday get rolled into the distribution, and until then you can grab it from there. There is a person on this list that has a Python module that works like Expect and is not reliant on Tcl. It is not PySSH (it does not work). I have been using his module for about 1 month now and it works GREAT (even with SSH passwords). He has told me he will release it to this list soon... Lance Ellinghaus ===== -- Lance Ellinghaus __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com From erict at millfilm.co.uk Thu Jul 18 13:24:20 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 18 Jul 2002 18:24:20 +0100 Subject: raw_input References: <3D36C5F1.9C966A8F@millfilm.co.uk> Message-ID: <3D36F9C4.A23D481A@millfilm.co.uk> Terry Reedy wrote: > "John Hunter" wrote in message > news:m2ofd5xdrg.fsf at mother.paradise.lost... > > >>>>> "Eric" == Eric Texier writes: > > > > Eric> It's there anything better than raw_input to query a > string > > Eric> input from the user in a console window. Thanks, Eric > > > > x = input('Enter a value: ') > > Ummm.... Since imput eval()s the input, this can be extremely > dangerous -- so dangerous that some people think input() should be > removed. There have been many prior postings on this subject. > > tjr Yes this is not what I am looking for. I was just hoping that it was a little module somewhere that will let me edit a line of command in the console, you know a bit like tcsh. I need it for a stupid raison and I don't feel having to think too much about it Thanks anyway From uncleenzo at hushmail.com Thu Jul 11 11:55:25 2002 From: uncleenzo at hushmail.com (Uncle Enzo) Date: 11 Jul 2002 08:55:25 -0700 Subject: redistributing python COM servers Message-ID: <10d944cb.0207110755.419f5d86@posting.google.com> Hello, Can anyone point me to a list of best practices for redistributing python COM servers? or a "gotchas" list? I'm especially interested in the following issue-- the registry entries required for the servers to be properly installed can be written manually by your installer, or the servers can be asked to "self-register" (and unregister on uninstall) in a custom action step. The first option is more explicit and makes installer saftey validation and verification by third parties easier without actually running the installer, while the second option seems, well, easier :) Also, does anyone know of a page or book out there that documents the *exact* registry entries for each COM local server exe? (and windows platform differences, if any?) Thanks in advance, Enzo From printers at sendme.cz Fri Jul 12 17:49:23 2002 From: printers at sendme.cz (A) Date: Fri, 12 Jul 2002 23:49:23 +0200 Subject: Where can I find a good webhosting service ? Message-ID: <3D2F6B03.15519.1B4D696@localhost> Hi, Where can I find a webhosting provider with Python installed and telnet (SSH) access at moderate price? What experience do you have and what can you recommend? Thanks Ladislav From thehaas at binary.net Thu Jul 11 21:22:17 2002 From: thehaas at binary.net (thehaas at binary.net) Date: Fri, 12 Jul 2002 01:22:17 GMT Subject: Python to XML to Python conversion References: Message-ID: Mark wrote: > Recently my employer has asked me to do some computer work though I'm > just savvy enough to write minor programs of little significance. My > job is to write a program that will be generic enough to take any form > of Python dictionary and be able to convert it to XML and back. like -- why? If he wants to save the data from one session to the next, the Pickle or cPickle module will be 100x easier. > Ladies and gentlemen I am completely at a loss, I'm not a good > programmer. If anyone one has any good, simple and complicated > examples, or tips I would be eternally greatful if you'd share them > with me. I have searched desperately through every posting I could > find on the subject, but to no avail. Please Help! The problem isn't very hard . . . no deep Python magic. I'd do the Python -> XML like this: outfile = file("out.xml") outfile.write("") for key in dict.keys(): outfile.write("<%s>%s\n" %(key, dict[key], key) ) outfile.write("") outfile.close() How's that?? Well-formed XML, without any DOM-overhead. If you didn't understand very in of the last sentence, than you better look at the Python docs (www.python.org/doc). Look for "minidom". Heck, look up XML. I'll leave the second problem to you . . . . -- mikeh From dcinege at psychosis.com Sun Jul 28 20:52:06 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Sun, 28 Jul 2002 20:52:06 -0400 Subject: TAB completion In-Reply-To: References: Message-ID: <200207282052.06532.dcinege@psychosis.com> On Sunday 28 July 2002 6:19, Stefan Heimann wrote: > Hi! > > I have a application with a builtin interactive shell. I use the > readline module for command completion and history browsing. The > following code enables filename completion: Is your work based on the cmd module? Dave -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From tdelaney at avaya.com Tue Jul 9 20:24:11 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 10 Jul 2002 10:24:11 +1000 Subject: Why self? Message-ID: > From: kosh at aesaeion.com [mailto:kosh at aesaeion.com] > On Tue, 9 Jul 2002, Mark McEahern wrote: > > > What you don't see, of course, is all the people who are > silent because > > they're quite happy with self. prefixes and consider this a > pointless > > discussion usually kept alive by people who refuse to learn > the idioms of > > Python to their best advantage. > > > > I have to agree with you on this. I find self makes the code > very clear > and much easier to maintain. Overall I am willing to use Very much so. I *always* use the this.variable form in Java to make it explicit that I'm referring to an instance variable. Two reasons for this: 1. Even though we have a convention here of member variables being prefixed with "m" (e.g. mVariable) I don't find this easy to see. An explicit this.mVariable is much easier to see. 2. "this" is a Java keyword, and gets coloured in my editor. Thus I can *very* easily pick out the member variables. Local variables are therefore also easier to pick out, as they are not syntax coloured. Exactly the same applies to Python, with the sole exception that self is required, and so I don't have to put up with co-workers who don't like putting self.name ... Tim Delaney From usenet-jul02 at puzzling.org Wed Jul 3 01:28:50 2002 From: usenet-jul02 at puzzling.org (Mary) Date: Wed, 03 Jul 2002 05:28:50 GMT Subject: ANN: SLUG Python Interest Group (Sydney Australia) Message-ID: The Python Interest Group of the Sydney Linux Users Group is having its monthly meeting: Date/Time: Monday 15th July 2002, 7pm - 9pm Location: University of Technology, Broadway campus, Sydney, room 2.04.29 (not the same room as last month). Although the PIG is part of SLUG, the scope of the group is not restricted to Python on Linux, and all Python users are welcome. -Mary. From peter at engcorp.com Thu Jul 11 23:44:12 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Jul 2002 23:44:12 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> Message-ID: <3D2E508C.DBDF9E52@engcorp.com> "Louis M. Pecora" wrote: > > In article <3D2CEDA1.4ACA69FE at engcorp.com>, Peter Hansen > wrote: > > > Actually, the Morse is much easier to write, since it doesn't > > require the Shift key (god how I hate underscores) > > Just go and design + develope your own keyboard. Since you post without smileys, I can only assume you are serious? To which my response is: you can't be serious. :-) (Hint, the original was a joke... note the partial wink. I do hate underscores, but concluding from that that my best option is to design and develop my own keyboard is just bizarre.) -Peter From mhammond at skippinet.com.au Thu Jul 25 23:54:30 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 26 Jul 2002 03:54:30 GMT Subject: PyXPCOM and SVG References: <3D3EEFE1.5090109@myrealbox.com> <3D4048B6.2060309@myrealbox.com> Message-ID: <3D40C815.7000605@skippinet.com.au> Johann H?chtl wrote: > Well XUL is of course not my primer as i can always use the wxwindows > widgets. But I thought about the ability to "remote control" mozilla > (maybe gecko and the upcoming SVG features) and therefore I need xpcom, or? There is currently no technique to remote control Mozilla. xpcom is inprocess only. There is a bug to add some kind of RPC to xpcom, but I don't think it is really being worked on. It should be possible to do what you want via embedding though. Mark. From fakeaddress at nowhere.org Sun Jul 28 02:33:47 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 28 Jul 2002 06:33:47 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: <3D439089.3010305@nowhere.org> Alex Martelli wrote: > Steve Holden wrote: Alex Martelli had written: >>>The poster is typically nonplusses that all buttons print 'fum'. >>> >> >>I would be nonplussed if that code even *compiled*, given that "print" is >>a keyword and lambda takes an expression not a statement. > > > Right - you caught my little trap. I don't regret using it, though, > because it DID catch a couple of lambda-lovers... First, who do you think you're kidding? It was your mistake not your trap. Second, this question is better answered by people who actually understand use of lambda. [...] > I think the reason why Guido suggests it's a wart is that it IS a wart. > > Sure, backwards compatibility mandates lambda stay, but I think it's > worth emphasizing that it's there ONLY for backwards compatibility, > and using def is better. The mistake was limiting lambda to expressions. --Bryan From cliechti at gmx.net Wed Jul 24 04:28:03 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 10:28:03 +0200 Subject: cmd, readline, and /path/filename completion References: Message-ID: Dave Cinege wrote in news:mailman.1027493794.5576.python-list at python.org: > Dunno much about programming readline, so maybe this is obvious. me neither > I toying with a unix shell written in python using shlex and cmd. > (For now based on the _Python 2.1 Bible_ lextocon example...) > > It's actually quite functional at this point. (Though replacing > bash with it, doesn't quite work yet... ) > > I'm trying to tweak the readline functionality, and am a bit lost. > > In Bash > cd /etc/ > Will display a list of files in /etc/ to complete against. > > In my shell, I will always see the files in the current directory. > > What must be done to mimic the bash functionaly? i think you have to search all directories in os.environ["PATH"] for executables if its the first word on the line, except when its a path, only search that dir. search the current dir if its the second or so arg/word on the line (more specific, you first have to check if the word is a valid path an list that dir it it is, otherwise list the current sir and both only if it isn't already a file). > Is it an option that > must be turned on in readline? Do I have to snag the line, and if it > is a valid path, cd to that path? (then back to PWD) you don't need to change the directory. just use os.listdir() the get a list of files. (and fileter that for executables with os.stat() in the firt case) chris -- Chris From thorstenharms at arcor.de Mon Jul 22 13:50:07 2002 From: thorstenharms at arcor.de (Thorsten Harms) Date: Mon, 22 Jul 2002 19:50:07 +0200 Subject: global variables Message-ID: <3D3C45CF.9060707@arcor.de> Hi! I 'm completely new to python. So here's my problem: How can I handle global data in my application? The application is a database application and I want to provide non-static informations, like the user id, name, etc. so that every object can access this information. Normally, I use C/C++ for coding, but these tricks don't work ;-) Maybe, you can give me some hints... Thanks in advance Thorsten Harms From marklists at mceahern.com Mon Jul 8 16:57:30 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 8 Jul 2002 15:57:30 -0500 Subject: List assignment, unexpected result In-Reply-To: Message-ID: > A friend of mine recently sent me some code and asked if I could > predict what it would do. I guessed wrong. Code as follows:- > > grid = [['.'] * 4 ] * 4 > grid [0][0] = '0' > grid [1][1] = '1' > grid [2][2] = '2' > grid [3][3] = '3' > for i in grid: print i > > The intent is clear i.e. fill the diagonal with 0,1,2,3; but the > result is somewhat different. Could anyone explain why this doesn't > work as expected - and even better, come up with an assignment for > 'grid' that would work. My only suggestion was an explicit > [['.','.','.','.'],['.','.','.','.'],etc. but it gets a bit cumbersome > for large grids. You can do multidimensional arrays by writing your own class or you can use the Numeric package: http://numpy.sf.net/ // m - From chris.gonnerman at newcenturycomputers.net Sat Jul 20 09:56:44 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sat, 20 Jul 2002 08:56:44 -0500 Subject: Using pointers References: <4210d7a2.0207200538.44a91c0f@posting.google.com> Message-ID: <005301c22ff5$49ac0b20$0101010a@local> ----- Original Message ----- From: "Joe Krahn" > Can I make a pointer to an object in Python? I know that all > objects/variables are references, but not in the same sense as in C. > How do I get multiple pointers to reference and modify one variable? Let's frame this in C terms. You want this: int *i, *j; int num; i = # j = # num = 11; printf("%d\n", *i); /* should print 11, right? */ Assuming I have this right... you can't do it in Python. Scalar types can't be handled that way. Sorry. Why don't you tell us a bit about what you are trying to accomplish, and then we can tell you the Pythonic approach. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From miracle at paradise.net.nz Wed Jul 31 18:08:16 2002 From: miracle at paradise.net.nz (Matthew Sherborne) Date: Thu, 01 Aug 2002 10:08:16 +1200 Subject: Problem - how to solve it ? References: <3D484E91.4394.15F5A3@localhost> Message-ID: <3D485FD0.7080504@paradise.net.nz> GPFs are fired when some C code crashes not python code. In the error it should give the name of a DLL or say python.exe. To find what part of your code is causing the error, do print messages, or write to a log file in the area around where the program crashes. Start in the highest level of the code, print a line before and after each sub routine is called, where the print outs stop, go to the sub routine after the last print out and put a bunch of print lines between all the sections in that and re-run. Keep narrowing it down like this. :) It may a bug in some windows DLL, so you could either fix it, or release a "Known Issues.txt" file with the program, letting them know that they must update their windows release if this happens. :) GBU Matthew Sherborne A wrote: >Hi, >I have a program that I compiled( with Installer) into exe for using >on Win32 systems. It works well on Windows Me, Windows 9x but >on some computers with Windows 2000 it causes General >Protection Error and the programs is finished. It would be nice if the >program wrote a line number or something similar that could help a >user find out which command caused that General Protection >Error. Is there any solution for that? >Thank you for help >Ladislav > > >_______________________________________________ >ActivePython mailing list >ActivePython at listserv.ActiveState.com >To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs >Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython > > > > > From tim.one at comcast.net Tue Jul 2 22:43:00 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 02 Jul 2002 22:43:00 -0400 Subject: Unicode utf-8 doesn't do back-and-forth? In-Reply-To: <3D217416.6080006@rogers.com> Message-ID: [Mike Fletcher] > ... > No clue what a surrogate is for, but I suppose there's no point > including them in a character-classes set if they're designed > specifically as unicode internal chars. In a galaxy far, far away, a bunch of geeks were sitting around bored, when one had a bright idea. "I know!" she exclaimed. "Let's invent a character encoding that covers all the world's character sets in one gulp!" "Hmm!" mused the oldest geek, who had been around long enough not to be blinded by American assumptions. "That's a lot of characters -- we might need 10, or even 11, bits!" "So let's use 16!" countered the rest. "That's way more than enough to last us forever 10 times over!" The rest is history, and "surrogates" are a hack to get the effect of 4 more bits (way more than enough to last us forever 10 times over). In pre-Unicode-speak, you'd call them "escape codes". not-to-be-confused-with-escape-code-points-ly y'rs - tim From pinard at iro.umontreal.ca Sat Jul 20 16:07:28 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 20 Jul 2002 16:07:28 -0400 Subject: Python 2.3 In-Reply-To: <3D399D25.F766A041@engcorp.com> References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <3D399D25.F766A041@engcorp.com> Message-ID: [Peter Hansen] > Just treat the "from __future__" statements as any other package and > you'll be fine. `from __future__' is a little special in that it should not be preceded by any other executable statement, except another `from __future__'. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From imbosol at vt.edu Sat Jul 27 13:52:08 2002 From: imbosol at vt.edu (Carl Banks) Date: Sat, 27 Jul 2002 13:52:08 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: Alex Martelli wrote: > Carl Banks wrote: >> Second, if you're going to do it right often, you might want to wrap >> it up in a function like this: >> >> def sort_the_right_way (f, a): >> aux = [ (f(x), x) for x in a ] >> aux.sort() >> a[:] = [ x for __, x in aux ] > > You can do that, but then you risk 'freezing' in your higher order > function a suboptimal way to proceed -- e.g., no way this function > can be told to produce stable sorts, while keeping DSU inline it's > trivial to ensure the sort is stable. > > The temptation to overgeneralize often accompanies the decision to > freeze some idiom into a higher-order function. Keeping the idiom > inline avoids temptations to overgeneralize. Thus, while it does > fly in the face of accepted wisdom, in Python sometimes it's wiser > to NOT refactor too many idioms and design patterns into ambitious > frameworks. Come on! Wrapping up a sort in a function is an "ambitious framework"? I'm talking about writing a single function because a certain sort appears a dozen or so times in the code. I'm sure you're aware of the advantages of putting oft-repeated code into one place. If you need another kind of sort for some reason, just don't use the function. [snip] > >> In which case, the temptation to use lambda returns: >> >> sort_the_right_way (lambda x:x[1], a) > > Somebody ambitious enough to encapsulate DSU should surely proceed > by encapsulating typical accessors to be used with it in closure > factories, e.g. > > sort_the_right_way(make_items_acessor((1,)), a) > > thereby avoiding lambda again. It's only when stuff gets wrapped > at once too much (by freezing some subset of DSU into a higher > order function) AND not enough (by not supplying other higher > order functions to go with it by building needed closures) that > the _temptation_ of lambda'ing around perks up. Easily avoided > by noting that even in that case one more def does it, of course. So now you're advocating building a framework of closures to replace the lambdas? This is what appears odd to me: you want me to inline sorts in the interest of not overgeneralizing, but it seems the same can be said by your use of make_items_accessor above. I have good reasons for my choice of where I generalize. I've never needed to be particular about the order of equal items; indeterminate is fine for me. One way to sort has sufficed for my whole life, thus, it makes sense for me to generalize. OTOH, I rarely have a use for generalizing x[1], so I would not bother with a closure. Even if I hated lambdas, I would just write: def second(x): return x[1] (Of course, I'll write the closure if the need ever comes to have the program select the index.) What I'm saying is, your objection that this use of lambda only is necessary because of over- and under-generalizatino isn't true for my circumstances. > It takes one more line -- saving lines is probably the core > fetish of lambda-enthusiasts, after all. I propose again the > hypothesis that such obsession may be linked to traumas in > one's childhood... Personally, I don't care about saving lines, per se. For me, lambda helps me to avoid stopping mid-function call, scrolling many or few lines to implement the function as a def, and returning. I.e., lambdas save me cursor movement. -- CARL BANKS http://www.aerojockey.com From abelo at earthlink.net Tue Jul 16 18:12:05 2002 From: abelo at earthlink.net (Carl) Date: 16 Jul 2002 15:12:05 -0700 Subject: saving modules Message-ID: <1d95285a.0207161412.5e101629@posting.google.com> I downloaded the Python22 software along with the python manual. In the manual it says to save the module fibo.py -I saved the module to c:\python22\fibo.py - In the DOS mode Directory it reads out as C:\Pyton22 -The file name reads out as fibopy~1 and the full name reads out as fibo.py.txt -The python shell does not recognize this as a module when I try to import it. -Please, what do I do now? From ckasso at sprynet.com Sat Jul 6 13:39:09 2002 From: ckasso at sprynet.com (Chris Kassopulo) Date: Sat, 06 Jul 2002 13:39:09 -0400 Subject: idiots guide to python References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: On Fri, 05 Jul 2002 19:29:48 -0400, Mike Johnson wrote: > I am starting an A-Level course in computing in september, and i will > need to learn how to use python. I have no previous experience of > programming, but could anyone point me in the direction of an "Idiots > Guide"? > > thanks. > > Mike Johnson http://www.greenteapress.com/thinkpython.html Not exactly an idiots guide. A pretty complete introductory tutorial, intelligently written. Best I've run across so far. -- Chris Kassopulo _/\_ Slackware 8.0 From syver-en+usenet at online.no Tue Jul 16 14:42:22 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 16 Jul 2002 18:42:22 GMT Subject: gettext i18n Message-ID: Are there any tutorials on this around? I read the i18n chapter in the python documentation but it doesn't say much about what to do with the files that pygettext and msgfmt generates. -- Vennlig hilsen Syver Enstad From jb at hotmail.com Mon Jul 29 12:48:44 2002 From: jb at hotmail.com (JB) Date: Mon, 29 Jul 2002 18:48:44 +0200 Subject: Python design failures (was Re: Let's Talk About Lambda Functions!) References: <3d455445_9@news.newsgroups.com> Message-ID: <3d457011_1@news.newsgroups.com> Aahz wrote: > In article <3d455445_9 at news.newsgroups.com>, JB > wrote: >>Tim Peters wrote: >>> >>> two language features are mentioned as being "failed >>> experiments" that only compatibility prevents throwing >>> away: >>> >>> `back ticks` >>> lambda >> >>(1) Why are back ticks a failure? I love them. > > If you're using backticks frequently, you're probably not > programming > Pythonically. There's already repr() to produce the same > result as backticks, and backticks have the problem that > in many fonts they're nearly indistinguishable from single > quotes. I do not understand this. I use __repr__ *and* backticks. For example class AnyClass: defr __repr__(self): ... a = AnyClass() myfile.write(`a`) I use this construction rather frequently. What is wrong with it? -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From claxtonr at beer.com Wed Jul 24 04:26:34 2002 From: claxtonr at beer.com (hejduk) Date: 24 Jul 2002 01:26:34 -0700 Subject: accessing a file's creation time Message-ID: i'm running 2.2 on linux 2.4.5 (slak 8.0.) my question is whether there is any way to access a file's creation time . os.stat provides access to constants that represent a file's last access time, last modification time, and last inode change time, but seemingly no way to get it's actual time of creation. i know the os stores this information somewhere (a simple "ls -l" demonstrates this), but i just can't seem to find a way to access it. thanks for any suggestions, From olc at ninti.com Wed Jul 3 23:35:08 2002 From: olc at ninti.com (Michael Hall) Date: Thu, 4 Jul 2002 13:05:08 +0930 (CST) Subject: Newbie cgi module question Message-ID: Thanks to Jeff for sorting out that last MySQLdb/tuple/list question (solution was spot on). B Another newbie question here ... Does Python's cgi module handle simultaneous get/post data? For example, I tried to use something like this:
I attempted to access the values above as follows: data = cgi.FieldStorage() action = data['action'].value thingtoedit = data['thingtoedit'].value When submitted to the target script (names.py), the 'action' parameter and it's value in the query string seem to be invisible to the script. If I use a hidden field like this, everything works fine:
The first example would work fine in PHP ... maybe Python is just different on this point? TIA again Michael Hall From j-jinkins at usa.net Sun Jul 21 10:28:33 2002 From: j-jinkins at usa.net (Jim Jinkins) Date: Sun, 21 Jul 2002 14:28:33 GMT Subject: Lists & two dimensions References: Message-ID: <3D3AC50D.4090405@usa.net> Pichai Asokan wrote: >I am a trainer and in a training session a participant came up with a >problem that stumped me: > >Here is the code snippet that isolates what I want: >-------------------- >board = [[-1] * 3 ]*3 >print board >board[1][2] = 'x' >print board >-------------------- >Output >----------------------- >[ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ] >[ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ] >----------------------- > >I thought >board = [[-1] * 3 ]*3 >should give me a list of 9 elements; >but ... > >What is going on? >Where can we read more to understand what is goingg on? > >P Asokan > > Cut and paste the code below. Then play with it. I learned a few things building it. Jim Jinkins # ------------------------------------------------------------------------------- # a = [[0] * 3] * 3 is equivalent to a = b * 3 # where b is [0] * 3 # which is equivalent to this code: b = [] # Create a new empty list for i in range(3): print "b = %s i = %d" % (b, i) b.append(0) print "b = %s final" % b # Uncomment these lines to make what is happening easier to see. # b[2] = -1 # print "b[2] = -1 makes b = %s" % b a = [] for i in range(3): print "a = %s i = %d" % (a, i) a.append(b) print "a = %s final" % a a[0][0] = 1 print "Executine a[0][0] = 1 makes a = %s" % a # List a contains 3 references to a list of 3 elements. # Changing that list changes what you see # through all 3 references (all three row elements.) # Now create a from 3 separate copies of b a = [] for i in range(3): print "a = %s i = %d" % (a, i) b = [] # Create a new empty list for i in range(3): print "b = %s i = %d" % (b, i) b.append(0) # Uncomment these lines to make what is happening # easier to see. # b[2] = -(i + 1) print "b = %s final" % b a.append(b) print "a = %s final" % a a[0][0] = 1 print "Executine a[0][0] = 1 makes a = %s" % a # List a contains references to 3 separate lists. # Changing any one of them does not change the # others # Now create a with a list comprehension a = [[0] * 3 for i in range(3)] a[0][0] = 1 print "Executine a[0][0] = 1 makes a = %s" % a # The list comprehension created 3 separate instances # of its outer expression, [0] * 3. # --------------------------------------------------------------------- From b.hall at irl.cri.nz Wed Jul 31 20:30:47 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Thu, 01 Aug 2002 12:30:47 +1200 Subject: A generic question: idiom for a paramterized base class? References: <918bc22f.0207311105.50a33dba@posting.google.com> Message-ID: <3D488137.B672EF76@irl.cri.nz> Thanks Donnal, Your idea seems to provide me with the following solution. I have split your code into two modules and added a class: ############### DonnalBase.py class AbstractBase(object): def __iadd__(self,other): return self.TAdd(self,other) def __add__(self,r): return AbstractBase.__iadd__(self,r) def __radd__(self,l): return AbstractBase.__iadd__(l,self) class TAdd(object): pass and ####### Donnal.py from DonnalBase import AbstractBase class MyClass1(object,AbstractBase): # One type of TAdd: class TAdd(AbstractBase): def __init__(self,l,r): print "TAdd instance 1" class TNode(object,MyClass1): def __init__(self): print "TNode instance" ####################### You see that I need 'MyClass' to act as a base for a number of classes (like TNode). This seems to work: >>> x = Donnal.TNode() TNode instance >>> y = Donnal.TNode() TNode instance >>> t = x + y TAdd instance 1 Thanks Blair Donnal Walter wrote: > ...snip... > Does this do what you want? > > ################################################## > class AbstractBase(object): > def __iadd__(self,other): > return self.TAdd(self,other) > def __add__(self,r): > return AbstractBase.__iadd__(self,r) > def __radd__(self,l): > return AbstractBase.__iadd__(l,self) > class TAdd(object): pass > > class MyClass1(AbstractBase): > > # One type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 1" > > class MyClass2(AbstractBase): > > # Another type of TAdd: > class TAdd(AbstractBase): > def __init__(self,l,r): > print "TAdd instance 2" > ################################################## > > >>> x = MyClass1() > >>> y = MyClass2() > >>> t = x + y > TAdd instance 1 > >>> u = y + x > TAdd instance 2 > > Donnal Walter > Arkansas Children's Hospital From wilk-spamout at flibuste.net Sun Jul 14 15:10:15 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Sun, 14 Jul 2002 21:10:15 +0200 Subject: web hosting with python cgi References: <20020714120559.46e0a1f2.wilk-spamout@flibuste.net> <1026671972.789324@console.ic.kharkov.ua> Message-ID: <20020714211015.213d292b.wilk-spamout@flibuste.net> Le Sun, 14 Jul 2002 21:39:42 +0300 artemio ?crivait: > Ian Bicking wrote: > > > If Python is installed, it will be available to you for CGI unless the > > host goes to efforts to keep people from using it -- which would just > > be mean (not that there aren't mean hosters). If a provider already > > has Python installed, even unadvertised, it's very unlikely to > > disappear. yes, really, i've seen that ! the reason ? security... > > > > Ian > > yes, i agree > > python is a standard package which is required by a number > of other applications, so it is very ulikely to be unsupported > on almost any unix/linux machine > > just write a script, run it from a server and you will surely know :-) > know that it's not... It's people who think that python cgi give security hole, it's people who think python 1.5 is more stable than 2.1, it's people who think php it's enough, it's people who think python is a snake... really, i don't know why ! -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From jblazi at hotmail.com Wed Jul 17 07:36:02 2002 From: jblazi at hotmail.com (JB) Date: Wed, 17 Jul 2002 13:36:02 +0200 Subject: Making code faster References: <3d3445f9_7@news.newsgroups.com> Message-ID: <3d3554d2_9@news.newsgroups.com> Armin Steinhoff wrote: > ... how man lines? How long are the lines? The lines are approximately 69 chars long. There are approximately 100000 lines. > Have you considered to use Pyrex in order to convert it > into a C module?? No, as I do not knoaw what Pyrex is. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From nas at python.ca Mon Jul 8 13:26:18 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 8 Jul 2002 10:26:18 -0700 Subject: stackless python In-Reply-To: ; from pinard@iro.umontreal.ca on Mon, Jul 08, 2002 at 11:39:49AM -0400 References: Message-ID: <20020708102618.A4681@glacier.arctrix.com> Fran?ois Pinard wrote: > [Fran?ois Pinard] > > Are these examples available for us to browse? Just a bit curious... > > Oops! I really meant the Python version of these examples, my message > did not make this clear! :-) Here's tow examples: http://aspn.activestate.com/ASPN/Mail/Message/602876 http://aspn.activestate.com/ASPN/Mail/Message/602993 They need to be updated to use generators as they are now implemented. Neil From jdhunter at nitace.bsd.uchicago.edu Wed Jul 10 13:31:50 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 10 Jul 2002 12:31:50 -0500 Subject: askopenfilename????? References: Message-ID: >>>>> "jubafre" == jubafre writes: jubafre> i don?t know how to use a filetypes option of jubafre> askopenfilename, somebody can help? jubafre> askopenfilename(filetypes=???) I don't use tkinter, but I believe the way this works is you present a list of tuples, where the first element of each tuple is a name associated with some filename glob to show only files of a certain type, eg self.picname = askopenfilename( filetypes = [ ("JPEG", "*.jpg"), ("GIF", "*.gif"), ("All", "*.*") ] ) John Hunter From h_schneider at marketmix.com Tue Jul 16 13:07:56 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Tue, 16 Jul 2002 19:07:56 +0200 Subject: SOLVED: Write \x1a to binary file References: Message-ID: Thanks a lot! I was a little bit fast with my request. Due to a bug, the end of my file was overwritten, so that the end marker \x1a was deleted. In fact, it is sufficient to open the file with mode 'b' to write all kind of binary data (on Win32, running Active Python 2.1). BUT: One strange side effect, I recogniced ... - I write \x1a to the end of a file. - I close it and reopen in text mode The result: the last byte gets cut off ... even when nothing is written to that file! All the best, Harald "Fredrik Lundh" schrieb im Newsbeitrag news:U6FY8.47572$n4.11655517 at newsc.telia.net... > Martin v. Loewis wrote: > > > > I've got a problem with writing "\x1A" to a binary file on Win32 platform. > > > I think due tue an issue wiht popen() this terminates the output stream. Is > > > there any solution for this ? > > > > I think there is some win32 module that allows you to set the default > > open mode for files to "binary". > > msvcrt.setmode(filehandle, mode) > > see http://www.python.org/doc/current/lib/msvcrt-files.html > for a bit more information. > > > > From fredrik at pythonware.com Mon Jul 1 12:12:08 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 16:12:08 GMT Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: Steve Holden wrote: > There did used to be a MoinMoin-based Wiki somewhere > under www.python.org http://www.python.org/cgi-bin/moinmoin resurrecting it (and moving it's focus to Python in general, rather than Python 2.0 ;-) sounds like a good idea. maybe we should start here: http://www.python.org/cgi-bin/moinmoin/Python and see what happens... (the current frontpage is Python20Info; I assume it's easy to change that once we have some content in there). > it certainly wasn't used when it was there well, someone recently added "TenaciousD rocks your socks off" to the front page, so it's not entirely dead. From ls2311 at netcom.com Tue Jul 9 01:03:30 2002 From: ls2311 at netcom.com (Lowel Stern) Date: Mon, 08 Jul 2002 22:03:30 -0700 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> <3D2A57B9.8EDD2BF0@engcorp.com> Message-ID: <14rkiu8fnp8chiua156k2qm9r1s2vf5trs@4ax.com> On Mon, 08 Jul 2002 23:25:45 -0400, Peter Hansen wrote: >Lowel Stern wrote: >> >> >Do you know about the % operator? >> > >> Yes I do. > >But not how to use it properly... > >> You will find that if you use the %s with the popen command you get an >> error: >> TypeError: unsupported operand type(s) for %: 'file' and 'str' > >Please post the code that generates this message. The code >_can_ be fixed. > >-Peter -------------------------------------- import os key = "%s %s" % ('"stern:STWA"',"1234") print key fp = os.popen('C:\python_scripts\prog %s') % (key) --------------------------------------- fp = os.popen('C:\python_scripts\prog %s') % (key) Traceback (most recent call last): File "", line 1, in ? fp = os.popen('C:\python_scripts\prog %s') % (key) TypeError: unsupported operand type(s) for %: 'file' and 'str' From wyojustin at hotmail.com Sat Jul 20 19:47:25 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Sat, 20 Jul 2002 23:47:25 GMT Subject: HTMLGen in Zope Message-ID: Has anyone ever used HTMLGen with Zope? What do I have to do to HTMLGen to get Zope to let me import it in a Zope Python script? Thanks, Justin From gerhard.haering at gmx.de Sat Jul 6 02:58:18 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 6 Jul 2002 08:58:18 +0200 Subject: jwz threading algorithm in Python Message-ID: <20020706065818.GA4611@lilith.my-fqdn.de> Has anybody implemented Jamie Zawinski's message threading algorithm in Python, yet and would like to share it? Here's the specification: http://www.jwz.org/doc/threading.html I'm about half-way thru with converting the Java implementation to Python (manual translation finished, in testing stage, now), but it looks like the debugging will take me quite some time still. Also, the code doesn't look very pythonic. If I could get a finished Python implementation, this would be much better :-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.7 ?C Wind: 3.0 m/s From guidance_shanghai at yahoo.com.cn Sat Jul 6 10:19:45 2002 From: guidance_shanghai at yahoo.com.cn (Leon Wang) Date: 6 Jul 2002 07:19:45 -0700 Subject: Chinese language support of Python? Message-ID: How can enable Chinese language support of Python? In IDLE, even can not save the source file if contain any >128 ASCII code charactors. I want to set the Window title in Chinese, but the bit7 is masked by Tkinter: from Tkinter import * from Tkconstants import * def filenew(): print 'filenew' def fileopen(): print 'fileopen' def fileexit(): print 'fileexit' def helpabout(): print 'helpabout' root=Tk() menu = Menu(root) root.config(menu=menu) root.title('中文') # this is Chinese filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=filenew) filemenu.add_command(label="Open...", command=fileopen) filemenu.add_separator() filemenu.add_command(label="Exit", command=fileexit) helpmenu = Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=helpabout) #frame=Frame(root) #frame.master.title('ETUS') #frame.pack() mainloop() From martin at v.loewis.de Mon Jul 29 19:15:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 01:15:45 +0200 Subject: default setting of unicode set References: <3D45000F.5040300@gmx.net> <3d454bc8$0$94895$e4fe514c@dreader3.news.xs4all.nl> <3d45bcef$0$12305$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Boudewijn Rempt writes: > That sounds very fine -- but the problem is, it's so counter-intuitive, > that every newcomer will stumble over this. I just noticed another posting > on this topic... Having to use codects.open instead of the builtin is just > as bad. People will start using plain open, waste a few days trying to find > out why it doesn't work, and then perhaps discover the codecs module. The alternative seems much worse: people will change the system default encoding because they are told to do so, without really understanding what that is. Then, they will write garbage data to files, because they won't get exceptions anymore about incorrect type conversions. This is like saying that you want to change "1"+2 not returning a type error anymore, since it is inconvient to write "1"+str(2) (or int("1")+2). Regards, Martin From tjreedy at udel.edu Mon Jul 8 18:18:08 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Jul 2002 22:18:08 GMT Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> Message-ID: "Robb Shecter" wrote in message news:3D29CE9D.4000802 at onsitetech.com... > Matt Gerrans wrote: > I completely agree, but I think the situation's even worse than you > described: A'typical' case of standard OO programming is made the most > tedious to write: References to instance variables from methods: > > self.__velocity = self.__factor1 * self.__factor2 > > etc. I find this totally unreadable (7 extra characters per referenced > instance variable). Only 2 'extra' chars are needed -- a letter and '.'. Why the extra '__'? TJR From news at 92tr.freeserve.co.uk Fri Jul 12 07:52:54 2002 From: news at 92tr.freeserve.co.uk (ddoc) Date: Fri, 12 Jul 2002 12:52:54 +0100 Subject: Transferring an excel file through HTTP References: <79b54d28.0207111451.35b583b2@posting.google.com> Message-ID: Chris wrote: > Hi everyone, > I have a question about clients (on windows) uploading Excel > spreadsheets (.xls) to a unix server. Why http? Why not use a script that uploads them by FTP, using bnary mode? If it is going from a Windows machine then provide the script with the user name and password in it, run a a menu item from the start button. I just say that anything in a particualr directory will go to the distant server, but if users insist on saving things all over the place you could have it ask which file first. -- A From peter at engcorp.com Sun Jul 21 20:19:12 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Jul 2002 20:19:12 -0400 Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3ACE59.1060004@lmco.com> <3D3AEDD6.78B39D70@engcorp.com> Message-ID: <3D3B4F80.B0D6BE07@engcorp.com> Alex Martelli wrote: > > > the name you use is local to the function, then when > > the function exits the binding is removed and the object, > > if no other names are by now bound to it, is destroyed. > > Yes, except that 'names' must be used in a very wide > sense here -- e.g., async.dispatcher instances are kept > alive by references to them in the socket_map dict, > which are "names" only in a very wide sense. I'm trying to follow Aahz' advice and avoid "reference" in favour of "binding" etc, but I guess I carried it too far! :) -new-habits-can-die-hard-too-ly yr's, Peter From sholden at holdenweb.com Sat Jul 6 14:54:14 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 6 Jul 2002 14:54:14 -0400 Subject: creating a file from python References: Message-ID: "gollem" wrote ... > I want to create a file from inside a running python script. Dear gollem: This sounds like something Python should be able to take in its stride. Python programs all around the world are doing this every day, and Python was invented precisely to give us new and more interesting ways to do the same thing. It still is ;-) > I can do that using commands and touch but it won't work if the intended > name of the file is the value of a python variable. I'm going to make an assumption here, so ignore the rest of this if I'm wrong: I presume you mean you can enter "though" commands into a Unix (or cygwin) command window, but you aren't sure how to do similar things from inside Python scripts. You may or may not know that Python's "os" module has a "system" function that lets you pretty much (though not *exactly*) "type a command". Of course, in Python there are dozens of ways you can do this. An example for the security-conscious: import os command = input("Any command you like:") result = os.system(command) In other words, if you can build it as a Python string, you can use it as a command. So, if you have some of the bits of the commands you need in Python strings already, you can use the names those strings are bound to in string-values expressions that you use (or intend to use) as arguments to os.system(). > The file is created as > the variable name instead of the variable value. If you don't mean a Python variable here, I'm lost, but I suppose you *might* mean a shell variable. Suppose you wanted to copy a file, you might use code like this: filename = "fileToCopy.txt" # "puts filename in variable" # in Python, we talk about binding names to values. # the name "filename" is now bound to "fileToCopy.txt". command = "cp "+filename+" /tmp/saved" result = os.system(command" > I think I need to use a shell (bash) variable to do it but then the question > becomes how do I create that? thnx > If you want to use the values of shell environment variables, again Python has help readily available as os.environ. This is a dictionary of your environment, and can be used to access your environment, and also to modify the environment that any sub-processes use. The value of the HOME environment variable is readily available as os.environ["HOME"] for example, so if you wanted to copy the file above into a subdirectory of your home directory you might use command = "cp "+filename+" "+os.environ["HOME"]+"/saved" rather than the hard-wired /tmp directory: the command now works for each user based on their home directory. To read and write a file from a Python program you again need the filenames. Look up the file() or open() functions to see how and maybe get a couple of examples. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From mbec at gemini.edu Tue Jul 30 05:43:33 2002 From: mbec at gemini.edu (Matthieu Bec) Date: Mon, 29 Jul 2002 23:43:33 -1000 Subject: condensed syntax? Message-ID: <3D465FC5.3DE7DEA4@gemini.edu> is there any way to condense the following: # scan subdir(s) within mydir for d in os.listdir(mydir): dd=os.path.join(mydir,d) if os.path.isdir(dd): self.subdir.append(dd) what follows doesn't work, but I'm thinking of a something like: self.subdir=[(os.path.isdir(dd=os.path.join(mydir,d))?dd:pass) for d in os.listdir(mydir) ] Thanks, Matthieu PS: please fwd. answer to this email as I am not on the newsgroup -- Matthieu Bec Gemini Observatory Tel: +1 808 9742557 670 N. A'ohoku Place Fax: +1 808 9359235 Hilo, Hawaii 96720, USA From guido at python.org Wed Jul 17 16:00:54 2002 From: guido at python.org (Guido van Rossum) Date: Wed, 17 Jul 2002 16:00:54 -0400 Subject: Going to OSCON? Give a lightning talk! Message-ID: <200207172000.g6HK0sp13487@odiug.zope.com> If you're going to the O'Reilly Open Source Convention next week, please consider giving a lightning talk. We have reserved two 45-minute slots in the Python track on Thursday afternoon for lightning talks. A lightning talk is a 5-minute tightly-focused presentation on any subject you like. You can discuss your favorite extension, rant, sing the praises of an under-appreciated developer, plug your product or company, beg for a job, or even present a Shakespearean-style play (don't laugh --- we had one of these in 2001). To submit your idea, fill out this simple web form: http://conferences.oreillynet.com/cs/os2002/create/e_sess?x-t=os2002_lt.create.form --Guido van Rossum (home page: http://www.python.org/~guido/) From shalehperry at attbi.com Mon Jul 29 20:44:55 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 29 Jul 2002 17:44:55 -0700 (PDT) Subject: Python design failures (was Re: Let's Talk About Lambda Func In-Reply-To: Message-ID: > > Best practice is, as Neil said, to *think* about a module, and hard, when > "cleaning it up". Widespread mechanical edits aren't welcome, and > especially since the last such effort (massive conversion to string methods) > introduced several bugs in the process. Better to find modules to love > long-term and keep them deeply beautiful, than to splash paint on boils at > random just to cover up the oozing pus . > lovely image there ...... is there a place which documents modules needing a steward? From dcinege at psychosis.com Mon Jul 29 09:06:24 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Mon, 29 Jul 2002 09:06:24 -0400 Subject: TAB completion In-Reply-To: References: Message-ID: <200207290906.24446.dcinege@psychosis.com> On Monday 29 July 2002 5:11, Stefan Heimann wrote: > Dave Cinege wrote:: > > On Sunday 28 July 2002 6:19, Stefan Heimann wrote: > >> Hi! > >> > >> I have a application with a builtin interactive shell. I use the > >> readline module for command completion and history browsing. The > >> following code enables filename completion: > > > > Is your work based on the cmd module? > > No it is not. I have looked at the cmd module, but its completion > function does not contain filename completion. Not true. Please see http://mail.python.org/pipermail/python-list/2002-July/thread.html#114824 http://mail.python.org/pipermail/python-list/2002-July/114824.html -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From cliechti at gmx.net Thu Jul 25 14:25:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jul 2002 20:25:11 +0200 Subject: if(debug), optimized away? References: Message-ID: marvelan at hotmail.com (M) wrote in news:c0abefc3.0207251004.22b21b3c at posting.google.com: > I would like to use something like this when running in > debug mode: > > if(debug): > if(items > 9): > print "fatal error..." > do_some_check_foo(42) > ... > > > If I set debug=0, is this code optimized away as in most > C/C++?? compilers? no. how could it, you can change the value of "debug" at runtime... > The reason for asking is that I would like to have A LOT of > debugging code and would like to avoid the performance penalty > when not runing in debug mode. you can use "assert" which cannot do all what you do in the above example, but it is optimized away when running "python -O" > Are there other, perhaps more Pythonish, ways of doing the same > thing? yes, exceptions. if something goes wrong you'll get an exception which you can handle appropriately. this is a high level language - you won't get coredumps etc. like in C/C++ so there is no need to check every bit. you can handle the exception at a higher layer and recover from there. chris -- Chris From cliechti at gmx.net Mon Jul 22 17:15:36 2002 From: cliechti at gmx.net (Chris Liechti) Date: 22 Jul 2002 23:15:36 +0200 Subject: global variables References: Message-ID: Thorsten Harms wrote in news:mailman.1027363530.26305.python-list at python.org: > Hi! > I 'm completely new to python. willkommen > So here's my problem: > How can I handle global data in my application? > The application is a database application and I want > to provide non-static informations, like the user id, name, > etc. so that every object can access this information. > Normally, I use C/C++ for coding, but these tricks don't > work ;-) > Maybe, you can give me some hints... if you need to access this data from different modules, put the data in a module that you import in each other. (modules are singletons in python) --file: myglobals.py -- names = id = None --file: someothermod.py import myglobals myglobals.name = "Chris" ... etc. chris -- Chris From donnal at donnal.net Fri Jul 26 16:39:26 2002 From: donnal at donnal.net (Donnal Walter) Date: 26 Jul 2002 13:39:26 -0700 Subject: type names versus types module Message-ID: <918bc22f.0207261239.37a56073@posting.google.com> I read in Guido's keynote address (slide 15 of 23) that we are now supposed to be using built-in type names instead of the types module. What is the preferred alternative syntax in Python 2.2 for the following snippet? ... if type(content) is types.ListType: print 'content is a list' else: print 'content is not a list' Thanks, Donnal From pyth at devel.trillke.net Wed Jul 31 14:13:42 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 31 Jul 2002 20:13:42 +0200 Subject: Use python without install it. In-Reply-To: ; from bergeston@yahoo.fr on Wed, Jul 31, 2002 at 05:58:15PM +0200 References: Message-ID: <20020731201342.N10625@prim.han.de> Bertrand Geston wrote: > Does somebody know if it is possible to use python on a computer under Linux > on that it's not allowed to install it for security reasons (server in > production) ? > The purpose is to have some shell scripts written in Python to make some > maintenance tasks. Those scripts are launched manually. > > Run it from a CD rom ? How ? > Special user ? is it really secure ? > Other idea ? I *guess* this is more a political than a technical issue. Manually launching maintenance scripts doesn't look like a big problem so far. but that completly depends on your circumstances. Could you be a bit more specific of which kind of security do you want? holger From markus.kaukonen at iki.fi Wed Jul 31 04:22:09 2002 From: markus.kaukonen at iki.fi (Markus O Kaukonen) Date: Wed, 31 Jul 2002 11:22:09 +0300 Subject: external binary reading standard in Message-ID: <3D479E31.4E46CFD5@iki.fi> Dear all, How to execute a external (binary) program reading from standard input in a python code ? For example : /home/mok/my_prog.bin < my_input.txt My system is Linux and the binary is written originally in fortran 90 (if that should matter). I tried os.popen('/home/mok/my_prog.bin < my_input.txt ') with no success Best Wishes, Markus Kaukonen, Finnland From gtalvola at nameconnector.com Wed Jul 17 09:25:46 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Wed, 17 Jul 2002 09:25:46 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty Message-ID: <61957B071FF421419E567A28A45C7FE514A5C7@MAILBOX.nameconnector.com> Tim Peters wrote: > [Geoffrey Talvola] > > ... > > I understand what you're saying. Would it make a > > difference if I told > > you that for this application, it's OK if the "get_nowait_reliable" > > operation blocks for "a little while"? In other words, I > > don't mind if > > it blocks while 17 other threads manipulate the queue. What I care > > about is that once the queue is no longer being manipulated in other > > threads, I either get an Empty exception or an object out > > of the queue. > > For my purposes if the queue was empty at any point during > > the operation > > then raising the Empty exception is OK. > > > > My requirements are a bit fuzzier than the strict no-blocking > > requirement of Queue.get_nowait() so maybe it's possible to > > implement > > this. > > > > In case you're wondering, this is in Webware's WebKit > > application server > > where there is a pool of N threads, and a queue of (non-thread-safe) > > servlet instances acting as a cache. We only want to create servlet > > instances when all existing instances are in-use. When a > > given thread > > needs a servlet, it basically does: > > > > try: > > instance = cache.get_nowait() > > except Queue.Empty: > > instance = new_instance() > > # use the instance... > > cache.put(instance) > > > > The problem is that every once in a while get_nowait() returns Empty > > when the queue isn't actually empty, so the size of the cache grows > > slowly and unboundedly over time. > > How do you know that the unbounded growth is *due* to that > get_nowait() > returns Empty at odd times? If service requests follow the > usual sorts of > lumpy distributions, the code you showed above simply will create an > unbounded number of instances over time, since it caters to peak > simultaneous usage as if resources were unbounded. Fiddling the Queue > implementation isn't going to cure that, if so. I left out some of the other details of Webware's app server. Suffice it to say that there are N threads that can potentially be executing the code above, so you'd expect that the cache will never contain more than N items. > > > But I'd prefer for the cache to contain at most N instances > where N is > > the number of threads. > > In that case, why not use a bounded Queue (the Queue > constructor has an > argument for this purpose) of maximum size N, and use > blocking get? That > gives up the illusion that resources are unbounded, but the > heart of your > complaint is that writing code as if resources were unbounded leads to > unbounded resource usage . If your threads are > returning instances > correctly to the queue, then the block will never wait long > -- unless it's > really the case that N instances aren't actually enough to service the > threads. But I don't want or need blocking -- the resource throttling is handled elsewhere in the app server. And I don't want to have to create all N instances on startup -- I'd rather allocate create instances only as needed, but re-use instances once they have been created. Reduces startup time, memory consumption, etc. - Geoff From edream at tds.net Mon Jul 1 09:33:03 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 01 Jul 2002 13:33:03 GMT Subject: Getting the XP clipboard in tkinter References: <3D1F1A81.95602DE0@tds.net> Message-ID: <3D205A0D.8D7FB741@tds.net> Matthias Huening wrote: > > The > > following two statements also take exceptions: > > > > s = app().root.selection_get("clipboard") > > s = app().root.selection_get(".") > Did you try this: > root.selection_get(selection="CLIPBOARD") > > Worked for me... Yes! selection="CLIPBOARD" works. selection="clipboard" does not. Somehow I was blind to case. Thanks very much for your help. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 11 05:21:18 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 11 Jul 2002 09:21:18 +0000 Subject: Pmw.Counter and Pmw.ScrolledCanvas questions In-Reply-To: <18692175.0207102141.1d5279c1@posting.google.com> References: <18692175.0207102141.1d5279c1@posting.google.com> Message-ID: <200207110825.g6B8P4728314@helios.gatwick.geco-prakla.slb.com> On Thursday 11 Jul 2002 5:41 am, John McMonagle wrote: > My first question is to do with Pmw.Counter. I am creating a > Pmw.Counter like so (see below code sample): > > > Because the label spans two text lines, the entryfield is also > expanded to this height. > > Is it possible to set the height of the entry field so as to only > appear as a single line ? Another way to say it is can the frame > component height and position be changed within the hull component ? > > > My second question is to do with Pmw.ScrolledCanvas. In my > application, I have a zoom drag feature. The user can drag an area in > the canvas window using button-3-press-motion-release to define an > area to zoom. I am able to do the zooming ok but how do you set where > the horizontal and vertical scrollbars are postioned. I wish the user > to see at the top left of the scrolled canvas window the point at > which they started the drag. I guess it's just for convenience sake > so the user does not have to scroll through to their desired point > after the zoom. John, I couldn't find a way round the Counter problem you may have to create you own multi-line labeled entry widget. As for the ScrolledCanvas are you using the .scale() canvas method. If so the call looks somthing like mycanvas.scale("ALL", xorigin, yorigin, xscale, yscale) and setting xorigin and yorigin to the top left points from you 'zoom box' should do what you want, to get those I would bbox the rectangle I guess you are drawing when they do the button-3-press-move-release dance. Oh and don;t forget to call resizescrollregion() after zooming. This is an example that seems to work (for me!) import Pmw from Tkinter import * class ZoomCanvas(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.canvas=Pmw.ScrolledCanvas(self) self.canvas.pack(fill='both', expand='yes') ## canvas bindings self.canvas.component('canvas').bind('<1>', self.button1down) self.canvas.component('canvas').bind('', self.button1motion) self.canvas.component('canvas').bind('', self.button1released) ## now create some junk on the canvas to zoom! self.canvas.create_oval(10, 10, 40, 80) self.canvas.create_oval(15, 20, 40, 40) self.canvas.create_oval(15, 30, 50, 40) self.canvas.create_oval(15, 40, 40, 60) def button1down(self, event): ## print 'Button 1 Down' self.startx=self.canvas.canvasx(event.x) self.starty=self.canvas.canvasy(event.x) def button1released(self, event): ## print 'Button 1 Released' x1, y1, x2, y2 = self.canvas.bbox("rectangle") self.canvas.delete("rectangle") ## should work out correct scale factors just using 2 for now! self.canvas.scale("all", x1, y1, 2, 2) self.canvas.resizescrollregion() def button1motion(self, event): ## print 'Button 1 Move' x=self.canvas.canvasx(event.x) y=self.canvas.canvasy(event.y) if x!=self.startx and y != self.starty: self.canvas.delete("rectangle") self.canvas.create_rectangle(self.startx, self.starty, x, y, tags='rectangle') root=Tk() zc=ZoomVanvas(root) zc.pack(fill='both', expand='yes') root.mainloop() Regards Martin From pyth at devel.trillke.net Wed Jul 24 12:14:30 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 24 Jul 2002 18:14:30 +0200 Subject: How to get the method/function which called a function? In-Reply-To: <1027524712.2754.10.camel@taz.rv.dlevel.net>; from alessandro.iob@dlevel.com on Wed, Jul 24, 2002 at 05:31:51PM +0200 References: <1027524712.2754.10.camel@taz.rv.dlevel.net> Message-ID: <20020724181430.H10625@prim.han.de> Alessandro Iob wrote: > def log(msg): > caller = GET_CALLER() > print repr(caller), msg > > class A: > def t(self): > log('a message') > > a = A() > a.t() # prints "> > a message" > > How can I implement the "GET_CALLER()" function in "log()" ? You can't. Basically you can get to the namespaces of your callers, though. import inspect pframe = inspect.currentframe(2) # caller's caller frame local2self = pframe.f_locals['self'] But you can't get to the name of the A.t method (i.e. 't') this way. The execution frame only knows about the *code* object beeing executed and not the orginal name ('t') which bound to that code object. It does know about the line number, though. You could try to use the line-numbers in the execution frames to get to the source code ('inspect.getsource') and try to extract names. I don't recommend going this way as it is very hard to get it to work reliably. And it has little chance to work across language boundaries (e.g with C-coded extensions). regards, holger From dkt at registriesltd.com.au Tue Jul 9 20:07:49 2002 From: dkt at registriesltd.com.au (David K. Trudgett) Date: Wed, 10 Jul 2002 10:07:49 +1000 Subject: openprojects python room is ruled by dangerous people In-Reply-To: ; from whisper@oz.net on Tue, Jul 09, 2002 at 04:48:18PM -0700 References: Message-ID: <20020710100749.C10550@regdp-02.intint.registriesltd.com.au> On Tuesday 2002-07-09 at 16:48:18 -0700, David LeBlanc wrote: > > History of the 20th Century: WW1, WW2, WW3? > > No, WWW -- Could we be going in the right direction? > > Wow, I missed WW3! It was scheduled for the 20th century, but got delayed. Couldn't find enough patriots. Now they've legislated for them. :-) David Trudgett From maxm at mxm.dk Thu Jul 18 10:25:40 2002 From: maxm at mxm.dk (Max M) Date: Thu, 18 Jul 2002 16:25:40 +0200 Subject: Sorting list of objects on arbitrary attribute References: <3D36AD49.2020305@mxm.dk> <8jzZ8.576968$cQ3.54422@sccrnsc01> Message-ID: <3D36CFE4.9040609@mxm.dk> Emile van Sebille wrote: >>the standard library, or somebody has a 2 liner which does the same > thing. > > aList.sort(lambda x,y: cmp( (x.name, x.age, x.rand) , (y.name, y.age, > y.rand) ) ) You are too clever for your own good ... regards Max M From jdavis at empires.org Mon Jul 1 17:16:21 2002 From: jdavis at empires.org (Jeff Davis) Date: Mon, 01 Jul 2002 21:16:21 GMT Subject: reloading modules References: <1FVT8.56956$xy.18941573@twister.socal.rr.com> Message-ID: Thanks very much, it seems to work exactly like I needed! I have one question though: you say in the message: "The purpose is to speed up the development process, not to update long running programs on the fly." Could you explain a little further? I was planning to use the module for web development in mod_python (where I don't want to worry about restarting the server just for a minor change). Will it work for that kind of thing? Regards, Jeff From cce at clarkevans.com Thu Jul 4 17:34:45 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Thu, 4 Jul 2002 17:34:45 -0400 Subject: Calling stdlib functions from pyrex Message-ID: <20020704173445.A44106@doublegemini.com> Hello. This pyrex stuff looks like a great tool. I tried to convert the module that I just posted recently, but I ran into a bit of difficulty... here is my error message: pyrexc tztool.pyx Unpickling lexicon... Done (0.11 seconds) gcc -c -fPIC -I/usr/local/include/python2.2/ tztool.c tztool.c:21: redefinition of `struct tm' tztool.c:35: conflicting types for `setenv' /usr/include/stdlib.h:123: previous declaration of `setenv' tztool.c:36: conflicting types for `unsetenv' /usr/include/stdlib.h:184: previous declaration of `unsetenv' tztool.c:38: conflicting types for `time' /usr/include/time.h:132: previous declaration of `time' tztool.c:39: conflicting types for `localtime_r' /usr/include/time.h:142: previous declaration of `localtime_r' *** Error code 1 Any help would be great. I have a ton of stuff that I'd like to convert over... Best, Clark -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software ----- BEGIN tztool.pyx ctypedef long time_t cdef extern struct tm: int tm_sec int tm_min int tm_hour int tm_mday int tm_mon int tm_year int tm_wday int tm_yday int tm_isdst long tm_gmtoff char *tm_zone cdef extern void setenv(char *key, char *val, int override) cdef extern void unsetenv(char *key) cdef extern void tzset() cdef extern int time(time_t *junk) cdef extern tm * localtime_r(time_t *now, tm *fill) def offset(zone): cdef time_t now cdef tm a setenv("TZ",zone,1) tzset() now = time(0) localtime_r(&now, &a) unsetenv("TZ") tpl = (a.tm_zone,a.tm_gmtoff/60) tzset() return tpl ----- BEGIN Makefile all: pyrexc tztool.pyx gcc -c -fPIC -I/usr/local/include/python2.2/ tztool.c gcc -shared tztool.c -o tztool.so python test.py ----- BEGIN tztool.c.old #include #include #include #include #include PyObject * offset(PyObject *self,PyObject *args) { time_t now; struct tm a; PyObject *pyobj; if(1 != PyTuple_Size(args)) { PyErr_BadArgument(); return NULL; } pyobj = PyTuple_GetItem(args,0); if(!pyobj) return NULL; if(!PyString_Check(pyobj)) { PyErr_BadArgument(); return NULL; } (void) setenv("TZ",PyString_AsString(pyobj),1); tzset(); now = time( NULL ); (void)localtime_r( &now, &a ); pyobj = Py_BuildValue("(sl)",a.tm_zone,a.tm_gmtoff/60); return pyobj; } PyMethodDef methods[] = {{"offset",offset,METH_VARARGS},{NULL, NULL}}; void inittztool(void) { (void) Py_InitModule("tztool", methods); } From skip at pobox.com Tue Jul 9 20:08:51 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Jul 2002 19:08:51 -0500 Subject: File size error in os.stat with large files. In-Reply-To: References: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: <15659.31507.545528.916376@gargle.gargle.HOWL> >> If it returns '0', LFS is not enabled. if it returns '0L', LFS is >> enabled. Fran?ois> Clever. Yet it seems that, in the long run, Python evoluation Fran?ois> plan is to abolish user-visible distinction between usual Fran?ois> integers and long integers. So I wonder if, despite the trick Fran?ois> above might work for some while, it is really safe relying on Fran?ois> it for programs meant to live a looong life :-). It seems to me that exposing interpreter build options via the sys module would be a Good Thing. You can mess around with distutils.sysconfig.get_config_var("CPPFLAGS"), but that is a bit fragile (the format can change over time or across compilers, making it difficult to write robust code that sniffs out the useful bits). Then again, maybe that's by design. Still, I think it ought to be easy to discover at runtime if large file support, threading, or other optional capabilities were compiled into the interpreter. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From tim.one at comcast.net Mon Jul 22 22:55:07 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 22 Jul 2002 22:55:07 -0400 Subject: Dict^H^H^H^HSomething in binary pickle causes exception In-Reply-To: <3D3CB772.8050703@something.invalid> Message-ID: [Greg Ewing] > Sorry, it looks like I jumped to a completely unwarranted > conclusion by assuming that dictionaries were responsible. That's OK -- only Jim Fulton reads binary pickles for fun . > There is *something* in my pickle that the unpickler > doesn't like, however. It's a pickled Plex Lexicon, > and it's rather big (too big to post here, anyway). > I'll do some more investigation and try to narrow > it down. I seem to be dimly aware of several claimed pickle oddities backing up; haven't had time to dig into them yet, and don't think anyone else has either. FWIW, note that pickles basically consist of instructions to a "virtual pickle machine", and the implementation is recursive. As a result, pickles of very deeply nested structures can blow up. > Anyway, what I mainly wanted to find out is whether > the binary format *should* be able to handle everything > that the non-binary format can. I take it the answer > to that is "yes"? That's the intent, yes. I don't know of any exceptions or bugs in this area, but you can deduce from an earlier statement that I don't read binary pickles for fun. From kill_spammers at kill_spammers.org Sat Jul 20 01:43:59 2002 From: kill_spammers at kill_spammers.org (Jim Aikin) Date: Sat, 20 Jul 2002 05:43:59 GMT Subject: text adventure game module for Python References: Message-ID: <3D38F8BA.6090601@kill_spammers.org> Michael Bauers wrote: > Having always been interested in languages for doing text adventures, > I thought Python was the perfect match. Obviously they are > mostly a thing of the past. Not true, actually. On rec.arts.int-fiction you'll find lively discussions of well-maintained languages like TADS and Inform, in which one can write text adventures. (There are Python partisans in that group, BTW.) Dozens of new freeware games are released every year, and some of them are very good indeed. --Jim Aikin *************************************** "Those instances of it which lack the quality referred to as 'swing' are meaningless." --Duke Ellington *************************************** From andreas at kostyrka.priv.at Sat Jul 27 04:08:47 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 27 Jul 2002 10:08:47 +0200 Subject: how to count lines in a file ? In-Reply-To: References: Message-ID: <1027753151.8774.214.camel@vaio2> Am Die, 2002-07-23 um 19.06 schrieb Chris Liechti: > xreadlines does read lines on demand, instead of loading the entire file. > (like range and xrange). and yes "file is open" i think it was introduced > because of the "for line in file(...)" idiom, it sound better so than with > open... Well, AFAIK file was introduced because all the other types have got "type constructors", and while open is such a constructor in function, it's got the wrong name for files. Andreas From aleax at aleax.it Tue Jul 9 03:05:03 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 07:05:03 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: Robb Shecter wrote: > Brian Quinlan wrote: >>... Actually, private instance >> variables are uncommon in general. > > Sounds like a difference in design philosophies. In my code, private > everything is the norm, with a very thin/small public API. Wise artisans learn a tool's strengths and use those strengths rather than fighting against the tool. Your "design philosophy", *actively* _hiding_ information, may be OK with other languages (one could do a lot of debate about that -- see later for a start), but it's definitely not the most productive way to use Python (or several other tools with similar underlying philosophies). What I see as the fallacy of "information hiding" as an active purview (having pursued it diligently for lo those many years) is that it reflects and responds to an assumed underlying "pecking order" which, upon reflection, is not a best fit for most projects. To wit: the designers of libraries and frameworks do an excellent job defining exactly what functionality the client-code programmers need; those client-code programmers, on the other hand, are rater clueless blokes who'll trample all over the carefully designed library / framework architecture unless strictly held in check for their own good. Just doesn't work that way -- not in organizations that aren't already dysfunctional, not in projects that are decently managed. I'm not very interested in choosing tools and design philosophies to enhance the thin chances of projects using rigid "waterfall" methodologies, _without_ decent levels of code-inspection, in some dysfunctional organization where "application programmers" are thought of as an unruly, lower-caste breed unable to follow a few sensible principles without the equivalent of electric cattle prods to motivate them. I recommend Highsmith's new survey of "Agile Software Development Ecosystems" for a background on what I have in mind as the applicable ranges of usable methodologies -- then, one may reflect on how such social structures should best be reflected in tools and design. The boundaries of any subsystem should be clean, with emphasis on simplicity and clarity of working code rather than architectural elaboration. Architectural sophistication should enter when it is strongly demanded by _reality_, rather than as an anticipatory move on the part of a presumed-to-be-all-seeing "Designer" (with a mandatory uppercase D). Design is in good part the task of unearthing the simplicity that too often lies buried and hidden under elaborate, complicated layers -- over-generalization and over-specialization being both able to hide that simplicity. Too many libraries and frameworks meant to be _reusable_ are barely even _usable_ -- and language tools that allow a designer to _enforce_ (rather than _suggest_) usage rigidity don't help at all. public/private is one such tool, and there are others -- such as methods that are not overridable (Java's "final") or not virtual (C++), _data_ that is not overridable (Python is exceptionally good at letting you override data as well as code -- it makes the Template Method design pattern into an even stronger powerhouse than in other OO languages, as it now mixes so naturally with data-driven, interpretive-like structures!), hard-coded names and types. C++'s templates do away with much of that, in favour of verbal specifications of "what is this thing supposed to do" and even the O()-performance constraints on "this thing" -- C++'s standard library (and the still-under-development STL which inspired it) is a great monument to the power of generic programming. Python (apart from wrapping it all in much more elegant syntax) takes this to new height (at a performance cost, of course) by doing it at runtime and thus even more flexibly. I guess it can be argued that in order to _learn_ to ride a bicycle it's best to have training wheel and just one gear ratio. Although, I've seen, in some of the regions where bicycles are most widespread (Bologna is on the outskirts of one such largish region), kids learning to ride on real, full fledged bicycles rather than "kid stuff" ones, and being none the worse for that. I wonder if Amsterdam (which is surely another major region of intense bicycle use, and Python's birthplace) has a similar philosophy, and whether this may have influenced Python itself (Guido has surely used _locks_ on bicycles as a metaphor to explain Python's _advisory_ concept of "private" -- but that's a slightly different issue). Be that as it may, production-level coding, like effective cycling, benefits from flexibility (many gear ratios, for example, so you can choose the best one at each time) and simplicity (the everyday miracle of a bicycle's inherent dynamic equilibrium) rather than from training wheels (supposed to stop you from losing your balance). >> Python forces you to be explicit. That way we will know what you are >> doing, right or wrong. > > Mmmm - I dunno; I think this same argument could be used in the Java > world for some of the things the language forces you to do, like > explicit casting and declarations: > > String name = (String) aVector.element(0) > > Python doesn't have any problems with implicitness here... If you want to force a _string_ representation of aVector's first element to be bound to variable name, you'll code: name = str(aVector[0]) which is roughly on a par with the Java construct -- you use the indexing operator [] rather than calling an '.element' method, and function call syntax str(...) rather than cast syntax, but that's all pretty much syntax sugar. Python doesn't force you to lose flexibility by specifying types when you'r rather keep polymorphism -- that's a totally different issue. You CAN force types (e.g. by calling str), you don't HAVE to (you can just get a reference, if that is what you want). The use of implicit scoping in Java (and similar languages) is not polymorphic. Therefore, no flexibility is lost by making the scope clearer, the way Python does. Simplicity and clarity gain, without flexibility loss -- an obvious, large win. The way some people are going ballistic about using self.whatever (rather than typical C++'s m_whatever, &c) can be seen as either tragic or ridiculous -- I'll choose the latter viewpoint, most particularly given the temporal coincidence with yet another round of the recurring saga of the joiner.join haters... a good indication that the time draws near for me to drop out of c.l.py again -- I can't really afford the time even for serious, useful, constructive discourse here, when I should be writing and editing and coding, much less for yet another round of such so-often fought flamewars. It's not as if there's any actual risk of beautiful Python being destroyed by such ridiculous ideas becoming real, after all -- it's survived hundreds such tempests-in-teapots, it will survive a couple more. Alex From john.abel at pa.press.net Mon Jul 8 04:44:48 2002 From: john.abel at pa.press.net (John Abel) Date: 08 Jul 2002 09:44:48 +0100 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <000401c22443$8f20dea0$bd5d4540@Dell2> References: <000401c22443$8f20dea0$bd5d4540@Dell2> Message-ID: <1026117888.10684.43.camel@lestat.howden.press.net> OK, I apologise in advance for appearing dense. I've added the code that was supplied by Brian, and the server script appears to run OK. However, the client script displays the following error: Traceback (most recent call last): File "MDClient.py", line 6, in ? print ServerConn.ReturnFiles ("/text/today") File "/usr/local/lib/python2.2/xmlrpclib.py", line 821, in __call__ return self.__send(self.__name, args) File "/usr/local/lib/python2.2/xmlrpclib.py", line 975, in __request verbose=self.__verbose File "/usr/local/lib/python2.2/xmlrpclib.py", line 853, in request return self.parse_response(h.getfile()) File "/usr/local/lib/python2.2/xmlrpclib.py", line 896, in parse_response return u.close() File "/usr/local/lib/python2.2/xmlrpclib.py", line 571, in close raise apply(Fault, (), self._stack[0]) xmlrpclib.Fault: The client script contains the following code: import xmlrpclib if __name__== "__main__": ServerConn = xmlrpclib.Server ("http://localhost:8000") try: print ServerConn.ReturnFiles ("/text/today") except ServerConn.UnknownIP, ErrMsg: print "Connect Failed", ErrMsg The server script: import sys, os, SimpleXMLRPCServer, string class AuthenticatingSimpleXMLRPCRequestHandler (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): def _dispatch(self,method,params): self.UnknownIP = "UnknownIP" if not (self.client_address == "144.178.234.189" or self.client_address == "localhost" ): raise self.UnknownIP, "Client IP Is Not Authorised" else: SimpleXMLRPCServer.SimpleXMLRPCRequestHandler._dispatch(self,method,params) def ReturnFiles(FileRequest): RetrFile = open(FileRequest,"r") FileContents = None for FileLine in RetrFile: if FileContents == None: FileContents = FileLine else: FileContents = FileContents + FileLine return FileContents if __name__== "__main__": XMLRPCServer = SimpleXMLRPCServer.SimpleXMLRPCServer ( ("localhost",8000), AuthenticatingSimpleXMLRPCRequestHandler ) XMLRPCServer.register_function(ReturnFiles) XMLRPCServer.serve_forever() I apologise it I'm doing something really obvious, but I can't seem to find any documentation, or examples that are similar to what I am trying to do. Thank you John On Fri, 2002-07-05 at 17:46, Brian Quinlan wrote: John Abel wrote: > I've set up an server, and client, which works OK, but now I want to > secure the server. Is there a way I can query the IP of the connecting > client? I've looked through the documentation, and can see that > SimpleXMLRPCRequestHandler is based on BaseHTTPServer, which has > client_address, but I can't seem to get access that variable. > > Any pointers would be much appreciated. You could base your security on IP address or you could have the client send a cookie with each RPC call. Using your IP address technique, you can subclass SimpleXMLRPCRequestHandler and write your own do_POST or _dispatch method. Your implementation can be very simple; just check client_address and call the base class implementation if it is correct. You must also register your SimpleXMLRPCRequestHandler subclass with the SimpleXMLRPCServer. Here is an untested example: class AuthenticatingSimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): def _dispatch(self, method, params): if self.client_address not in list_of_valid_addresses: raise Exception, "your IP address is not authorized" else: SimpleXMLRPCRequestHandler._dispatch(self, method, params) server = SimpleXMLRPCServer( some_address, AuthenticatingSimpleXMLRPCRequestHandler ) server.server_forever() Cheers, Brian From whisper at oz.net Wed Jul 10 18:53:33 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 15:53:33 -0700 Subject: Python in the enterprise: Pros and cons In-Reply-To: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: The article suggested the following cons and here are my counter arguments: * Smaller pool of Python developers compared to other languages, such as Java -- Easier learning curve compared to other languages such as Java, C, C++, Perl, Tcl and Ruby; especially so for people coming from any of those languages. Python is just plain easy to learn. * Lack of true multiprocessor support -- Heh. That's not really true either. Python is no better and no worse then any other application program wrt to multiprocessor usage. What the author probably was referring to here is Python's lack of multi-processor multi-threading - i.e. true parallel computation. Know many non-specialized languages that can or do exploit multi-processor multi-threading? There are even OS dependencies: Win32 OS's (NT, 2k, XP) will not spread applications across processors unless your program causes it to explicitly (this is at least true on retail 2 processor maximum systems). Linux OTOH, does so. * Absence of a commercial support point, even for an Open Source project (though this situation is changing) -- I think you haven't noticed the forest for all the trees. While there is no dominant well known Python Services Provider (maybe we could buy Anderson Consulting cheap ;-)), there are quite a number of smaller companies and individuals offering Python support and consulting. Digital Creations, Python Labs, Pythonware and Orbtech come to mind and there are many others. * Software performance (though benchmarks repeatedly demonstrate Python is comparable to Java in most applications) -- "Python is comparable to Java" is probably a con - Python far surpasses Java in the shortness of time spent going from "hmmm ..." to "run ...". If you're comparing clock cycles, then you're saying an open source development project has done what a multi-billion dollar company with 100's of developers has done (that's a bit unfair - Python probably has more developers (including "battery" developers) on it then does Java). Python can and most likely will get faster and even more popular, but I'm not sure the same can be said for Java. * Lack of prepackaged solutions -- Take a look at the Python foundry on SourceForge. Browse the comp.lang.python.announce archives. Spend an afternoon in the Vaults of Parnassas, Python's defacto standard repository/catalog for contributed software. Search for "python applications" on Google or Yahoo. Try "python " for whatever type of application you're looking for and see what comes up. Lack of channels for promoting Python applications doesn't mean they don't exist. * Python's obscurity in development shops -- We don't WANT to take over the COBOL shops ;o)! I suspect most Linux and Windows programmers have heard of Python and it would not surprise me to know that a lot of them where using it internally where it's below the radar of the people who poll language use (Dataquest, Gartner Group?). IBM, HP and Intel use Python! * Database access layer limitations -- Ok, I agree that maybe this could be better "out of the box", but there are good ODBC wrappers for Python from 3rd parties. ODBC is one of the few specs that Microsoft got right enough for it to find it's way to the Linux world. * Documentation gaps -- This was recently discussed on comp.lang.python. There are at least 27 books dealing with Python or Python in specific applications. The "in the box" documentation is ackward to use but reasonably comprehesive (tutorial aside - the best basic introduction is the book "Learning Python" by Mark Lutz). There are at least 2 full books for Python online: DiveIntoPython and "How To Think Like A Computer Scientist" (using Python), and many other online resources available through Python.org. * Absence of GUI and teamwork tools -- There two commercial tools for wysiwyg tkinter development, one of which is PythonWorks from Pythonware. Do CVS and Subversion count as teamwork tools? They do solve the source management part. MoinMoin Wiki software will solve the team interaction part of the equation, and there are chat packages out there, including a Jabber client for instant messaging on all the popular IM networks. It's a product opportunity for someone to integrate all the tools into a cohesive whole, but all the parts seem to be there... ----------- The one thing that has come to mind from writing this as a con for Python is the lack of channels for widespread dissemination of information about commercial software applications, support and consulting. Python does need better publicizing in the marketplace. Python.org provides such a focus for information about the language, but provides little beyond a jobs board for the marketplace. It would be nice to see a registry of products and services that use or support Python. My conclusion is that Python is entirely ready for the enterprise - and it's already there! David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of builder > Sent: Wednesday, July 10, 2002 14:03 > To: python-list at python.org > Subject: Python in the enterprise: Pros and cons > > > Python has many fans in the open source community, but is it ready for > the enterprise? Here are the advantages and disadvantages of using > Python in the corporate environment. > http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm > -- > http://mail.python.org/mailman/listinfo/python-list From aleax at aleax.it Wed Jul 24 08:08:48 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 12:08:48 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: James Kew wrote: > "Alex Martelli" wrote in message > news:JCv%8.110249$Jj7.2629802 at news1.tin.it... >> >> When your __init__ (or any other method) *just* >> delegates to the superclass, and nothing else, >> simply remove that method's definition from >> your class -- inherit it rather than going to >> the trouble of overriding just to delegate, >> which buys you nothing. > > I was wondering about this recently: I can see that leaving it out is more > efficient, but leaving it in does make the class slightly easier to use: Clutter, boilerplate, and duplicated code don't make programs any easier to use, IMHO. It's not mostly an issue of the extra time of an extra function call -- it's about clarity, spareness, elegance, and usefulness. Oh, and ease of maintenance, too:-). > a) clients of the class don't have to wander up the class hierarchy to > discover what the __init__ parameters are, and Of course not, print Theclass.__init__.__doc__ will suffice -- but it works just as well when __init__ is inherited, of course. > b) writers of subclasses of the class which add their own __init__ don't > have to wander up the class hierarchy to discover which superclass to call > __init__ on and what parameters to pass. You don't need to know what superclass exposes __init__: you can always call it on your immediate superclass, directly or via the super built-in. For parameters, see above. > I suspect the proper Pythonic answer to both is "document, don't code"? I'd say both document AND code. But not DUPLICATE code -- code whose only purpose in life is complicating everybody's life by duplicating exactly some feature of some OTHER code, such as a given __init__'s signature -- clutter source files with such boilerplate, and ensure problems when something is updated and its must-be-exact copy isn't. Say my client code uses some class A from library X. There's another helpful library Y which wraps X and in particular supplies a class B that inherits from A and adds a few bells (no whistles yet, but they're working on it). Now, a new release of X comes out, the only change I care about being that A's __init__ has grown a new optional keyword parameter named encoding with a default value of 'iso-8859-1'. Cool, I can use that, as I need the Euro symbol and thus encoding='iso-8859-15' instead. Oops! B's __init__ doesn't yet known about the new encoding parameter, thus I have to curse and hack around the limitation (having to edit library source is SUCH a deuced, wrecked thing). Bad enough if that __init__ had a REASON for existing. When I find out it's there for *NO* bloody reason whatsoever, *JUST* to make my life miserable by failing to recognize 'encoding', THAT is when I'll truly *SCREAM*. Don't do that. PLEASE. In fact: when you wrap a library class, please CONSIDER accepting arbitrary keyword parameters and passing them up to the superclass's method that you're overriding-and-delegating-to. Just in case this sort of thing happens tomorrow. Pretty please. So much for the overriding method serving as "documentation" for the signature of the superclass method, of course. I won't miss that. ALex From skip at pobox.com Tue Jul 30 11:36:20 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Jul 2002 10:36:20 -0500 Subject: Guide to the python interp. source? In-Reply-To: <3D45224C.8050208@tismer.com> References: <1027848147.20536.125.camel@vaio2> <15684.23324.498143.792539@localhost.localdomain> <3D45224C.8050208@tismer.com> Message-ID: <15686.45684.135240.855617@localhost.localdomain> Chris> Just a remark: All the icons appear to be broken, for example: href="/pyvmwiki/HelpContents"> src="/pyvmwiki/img/moin-help.gif" Yes, thanks. I had muffed the moin_config.py file. Should be okay now. Skip From see_reply_address at something.invalid Tue Jul 16 21:16:40 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 17 Jul 2002 13:16:40 +1200 Subject: ANN: Pyrex 0.3.4 Message-ID: Pyrex 0.3.4 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Bug fixes: - Runtime crash when using * or ** args in a method of an extension type fixed. - Compiler crash when using default argument values in a method of a Python class. Enhancements: - Type slots filled with functions from outside the extension module are now initialised dynamically, which should eliminate at least some of the "initialiser is not constant" problems experienced on Windows. - On Windows, __declspec(dllexport) is now used for the module init func declaration (or should be -- I haven't tested this). What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pecora at anvil.nrl.navy.mil Tue Jul 23 12:11:00 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 23 Jul 2002 12:11:00 -0400 Subject: Overhead for local assignments (was: A better self) References: Message-ID: <230720021211008411%pecora@anvil.nrl.navy.mil> I did some tests as suggested in the "Better self" thread on the timing overhead of assigning to local variables and then using them in a formula. The issue in that thread was readability which can be gained several ways. The code and results below compares those ways. I present the explanation for the four tests, first, then show the results (a bit surprising...to me, at least), and then at the end I give the code. I am not claiming this is the best way to do these tests. It is typical of coding I have done. Feel free to criticize or better, suggest other tests, or even better, do other tests and post them. -- Lou Pecora EXPLANATION OF TESTS ===================================== # Tests overhead for "assigning" object variables # (e.g. self.t, self.x, self.y, self.z) to # local variables or function arguments so as to use simpler names # in a formula without the "self." prefix. Such assignements # will cause "overhead". This module's aim is to compare the # overhead involved in each approach. # The approaches are: # (1) Assign in tuple, thus: t,x,y,z=self.t,self.x,self.y,self.z, # then use t,x,y, and z in the formula # (2) Assign in line, thus: t=self.t # x=self.x # y=self.y # z=self.z, then use t,x,y, and z # in the formula # (3) Assign to class function arguments, thus: # self.fcntst(self.t,self.x,self.y,self.z), # where the class function contains the formula # (4) Assign to class function arguments using local # variable f assigned to the class function, thus: # f(self.t,self.x,self.y,self.z), where f=self.fcntst # # Note, an attempt is made to _exclude_ the loop overhead by # timing an empty xrange loop, first, and subtracting that # time, tx, from the tests (1) to (4) RESULTS AND COMMENTS ===================================== Note: the results (the ratios) appeared to be independent of the number of loops used (n, below) from n=1000 to n=1000000 xRange time= 0.15076 tuple assign time= 0.958203999999 line time= 0.799539 fcn1 (class call) time= 1.508272 fcn2 (local call) time= 1.256834 Ratios to the minimum time: (1): 1.24455939542 (2): 1.0 (3): 2.09241051267 (4): 1.70485481189 Method (2) is fastest as some people suggested. (1) does seem to involve some time creating and destroying a tuple as suggested. (3) is the worst, by a factor of 2! So if you have lots of class function calls, assign the function to a local variable, but even better, avoid using the function calls to just calculate a formula, if possible. CODE ===================================== # Just imports stuff commonly used import time from Numeric import * class lcltst: def __init__(self,n): self.t=1 self.x=2 self.y=3 self.z=4 self.n=n # Numb.loops # Calculate the for loop time so as to exclude it later t1=time.clock() for i in xrange(self.n): pass self.tx=time.clock()-t1 # loop time print "xRange time=",self.tx # (1) Assign variables in a tuple def linasg(self): t1=time.clock() for i in xrange(self.n): t,x,y,z=self.t,self.x,self.y,self.z # After assigning local variables normally the # formula for doing # calculations using the local variables would follow t2=time.clock() print "tuple assign time=",t2-t1 return t2-t1 # (2) Assign variables one at a time, in line def indasg(self): t1=time.clock() for i in xrange(self.n): t=self.t x=self.x y=self.y z=self.z # After assigning local variables normally the # formula for doing # calculations using the local variables would follow t2=time.clock() print "line time=",t2-t1 return t2-t1 # Dummy function def fcntst(self,t,x,y,z): # Would normally contain the formula and do calculations using # the argument variables pass # (3) Call dummy formula function def fcn1(self): t1=time.clock() for i in xrange(self.n): # Use class function call self.fcntst(self.t,self.x,self.y,self.z) t2=time.clock() print "fcn1 (class call) time=",t2-t1 return t2-t1 # (4) Call local assignment of dummy formula function def fcn2(self): t1=time.clock() # Assign class function to local variable, first f=self.fcntst for i in xrange(self.n): f(self.t,self.x,self.y,self.z) t2=time.clock() print "fcn2 (local call) time=",t2-t1 return t2-t1 #---- Run the test for n loops ---------------------------- print "--------------------------------------" n=200000 # Number of loops (tested from n=1000, to n=1000000) lt=lcltst(n) tx=lt.tx tlist=[lt.linasg()-tx] tlist=tlist+[lt.indasg()-tx] tlist=tlist+[lt.fcn1()-tx] tlist=tlist+[lt.fcn2()-tx] tmax=min(tlist) tfract=divide(tlist,tmax) print print "Ratios to the minimum time:" print "(1):",tfract[0] print "(2):",tfract[1] print "(3):",tfract[2] print "(4):",tfract[3] From cliechti at gmx.net Wed Jul 3 17:32:12 2002 From: cliechti at gmx.net (Chris Liechti) Date: 3 Jul 2002 23:32:12 +0200 Subject: win32 setcommtimeouts parameter? References: Message-ID: grante at visi.com (Grant Edwards) wrote in news:fcHU8.3751$eH2.3711448 at ruti.visi.com: > The win32 extension SetCommTimeouts accepts a tuple of five > values for the timeout parameters. > > Can anybody lend me a clue as to the order of those five > values? already found that one? http://msdn.microsoft.com/library/techart/msdn_serial.htm or just use http://pyserial.sf.net ;-) chris -- Chris From mlai at intrinsyc.com Tue Jul 16 17:37:55 2002 From: mlai at intrinsyc.com (max) Date: 16 Jul 2002 14:37:55 -0700 Subject: Serial Port Returning Garbage. Why? References: <%gVY8.204$fK3.80978@newsfeed.slurp.net> Message-ID: bowman wrote in message news:<%gVY8.204$fK3.80978 at newsfeed.slurp.net>... > max wrote: > > > > Serial Connector: 3-wire > > Are you using a hardware handshake or QON/QOFF? No, I'm not. It's just Transmit, Receive, and Ground. Our device doesn't use any of the other signals, and the implementation doesn't use QON/QOFF. Would it make a significant difference if I do? Max Maximilian Lai Embedded Software Developer Intrinsyc Software, Inc. 10th Floor, 700 West Pender Vancouver, BC V6C 1G8 p: 604-646-7970, 604-801-6461 f: 604-801-6417 e: mlai at intrinsyc.com w: www.intrinsyc.com Intrinsyc, the 'Connected Intelligent Device Company' From rich at worldsinfinite.com Tue Jul 9 15:56:01 2002 From: rich at worldsinfinite.com (Rich Harkins) Date: Tue, 9 Jul 2002 15:56:01 -0400 Subject: Why self? In-Reply-To: References: Message-ID: <200207091556.01318.rich@worldsinfinite.com> > [snip] > If you are subclassing a class that someone else has written, you don't > want to accidentally redefine an internal name. Sorry. I can accept > that you should be able to explicitly access it, but to be able to > change it by accident is (would be?) a misfeature. > > I didn't believe that this happened in Python. It does, and it seems a > significant flaw. My understanding is that if you define a variable in > a class that subclasses another class, then unless you take definite > steps to cause things to happen otherwise, you are defining a new > variable that is local to the scope of the class that you are currently > defining, and will not impact routines that you call from parental > classes. Experiment shows that this isn't what happens. > from __future__ import nested_scopes > does not fix this problem, as I assumed that it would. > > Let's be explict: > from __future__ import nested_scopes > class A: > def ma(self): > print "ma, ma" > def pa(self): > self.ma() > class B(A): > def ma(): > print "hello, world" > tst = B() > tst.pa() > > Testing this produces the message, "hello, world" > This seems to be the wrong message. The version of pa that was called > was the version defined in class A, so the routine called should have > been the routine defined in class A. > > Or, to me more accurate, for libraries to have maximal portability, I > would want the message to have generated "ma, ma", and I had been > assuming that nested_scopes would result in that being the message that > was produced. This would happen in Java/C++ too: public class X { public String ma() { return "ma, ma"; ` } public String pa() { return ma(); } }; public class Y extends X { public String ma() { return "hello, world"; } }; Calling Y().pa() would return "hello, world", just like Python. So this seems to me a problem of general polymorphism rather than Python. In Python you could at least force it by being explicit and utilizing the fact that classes are first-class objects too (C++ works similarly, but Java doesn't let me call arbitrary superclass methods for some reason): class A: def ma(self): print "ma, ma" def pa(self): A.ma(self) class B(A): def ma(self): print "hello, world" Java/C++ have the same problem with instance variables too that aren't declared private (private is spelled __ in Python) as much as Python does, other than in Java/C++ I can't change the type of the inherited instance variable. I am aware that Java/C++ deter using member variables of inherited classes directly, but this is one of the things I *like* about Python, and why I don't spend so much wasted time defining get/set methods when I can just *use* the variable in question. Anyway, that's my .02. Rich From gugabbe at hotmail.com Tue Jul 23 18:27:30 2002 From: gugabbe at hotmail.com (Mack) Date: Wed, 24 Jul 2002 00:27:30 +0200 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: In , John Hunter wrote: >>>>>> "Mack" == Mack writes: > > Just built myself new redhat 7.1 packages from source rpms (2.2.1). Works great sofar. I hope it doesn't break any tools that uses old python. I found out, however, that there were now three pythons in /usr/bin, python, python1.5 and python2. python were identical to python 1.5 so I just did a cp /usr/bin/python2 /usr/bin/python. I can always revert if somethings wrong. I started reading some tutorials on python because I've just read SAMS "Teach Yourself Perl in 21 days". Seems to be a really powerful language and looks just about what I need. I do not really like the complex syntax though so I thought that I'd look into Python as well. Ordered a book today also. I think it's best to take a really good look before I get too busy coding a lot of stuff that I'll regret later. Thanks for all the help sofar. Mack From mwh at python.net Thu Jul 18 05:59:37 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Jul 2002 09:59:37 GMT Subject: pickle performance on larger objects References: Message-ID: Sam Penrose writes: > memory usage increases by about 20%, FWIW. For my particular use case > cPickle is still several (many ?) times slower than just recreating > the object by reading in a file. Are you sure that the file doesn't have an associated .pyc? For then you're testing marshal perfomance, and that's always going to kill pickle. Just a thought. Cheers, M. -- We've had a lot of problems going from glibc 2.0 to glibc 2.1. People claim binary compatibility. Except for functions they don't like. -- Peter Van Eynde, comp.lang.lisp From andreas at kostyrka.priv.at Thu Jul 25 13:33:25 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 25 Jul 2002 19:33:25 +0200 Subject: Session ID & Security In-Reply-To: <7xadonkosg.fsf@ruckus.brouhaha.com> References: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> <3D38B779.3090602@removethisandallhyphens-o-n-e.net> <7xwurrkwes.fsf@ruckus.brouhaha.com> <3D38D519.8070501@removethisandallhyphens-o-n-e.net> <7xadonkosg.fsf@ruckus.brouhaha.com> Message-ID: <1027618252.8773.130.camel@vaio2> Am Sam, 2002-07-20 um 06.26 schrieb Paul Rubin: > Thanks, that's kind of interesting, but because of the issues you > mention and because of the file system overhead (even if it's a ram > disk), I still think shared memory is the best mechanism by far. Well, I'm not that sure. Especially if you consider that there are filesystems designed to handle many small files (reiserfs) in a db-like way. Additionally, have you benchmarked the overhead? Going for a shared memory solution isn't exactly conforming to the KISS principle. > http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html > > is a Python interface to the shm system call that does everything > required. Alternatively a semaphore operation (basically a call to an > atomic test-and-set instruction) could be added to the existing mmap > module, and you'd simply map a shared file into memory. > > For more flexibility, it might be interesting to use MPI for all this > stuff. Run your web server on a Beowulf cluster! I'd guess that MPI is even slower than a file system operation. Andreas From shagshag13 at yahoo.fr Wed Jul 31 13:42:20 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 31 Jul 2002 19:42:20 +0200 Subject: signature for a file ? References: Message-ID: "Shagshag13" a ?crit dans le message de news: ai5ned$11p711$1 at ID-146704.news.dfncis.de... > > Hello, > > i would like to have your opinion on this... > > i had at home many hdds, that could contain many time same files, in many places/directories (-> i'm really disorganized). > i would like to do some sort on theses files. to do this i'm planning to write a python script that would compute a kind of CRC32, > MD5 or SHA (i'm really not competent in that - so here i need advices and pointer to some implementations - and to know which is the > best to had a unique unambiguous signature for a file) and then use it to find "doubles" : same size + same signature = probably > same file. Looking for something else I find a script doing what i want to... See "Subject: Re: Dup detector [Conclusion]" @ http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=6r23tp%24eaa%241%40nnrp1.dejanews.com31/07/2002 (url might be cut) regards, s13. From b.maryniuk at forbis.lt Tue Jul 23 09:05:20 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 23 Jul 2002 15:05:20 +0200 Subject: ssh and Python In-Reply-To: References: Message-ID: <200207231505.20015.b.maryniuk@forbis.lt> On Tuesday 23 July 2002 13:00, Erno Kuusela wrote: > that probably means that they have disabled them because they > fear people will use passphraseless rsa keys. i suggest > you have a chat with the administrator, as hardcoding > the password is a worse solution. Yeah, I agree. Fully. But life in the computer science sometimes sucks... -- Sincerely yours, Bogdan M. Maryniuck Microsoft Corp., concerned by the growing popularity of the free 32-bit operating system for Intel systems, Linux, has employed a number of top programmers from the underground world of virus development. Bill Gates stated yesterday: "World domination, fast -- it's either us or Linus". Mr. Torvalds was unavailable for comment ... (rjm at swift.eng.ox.ac.uk (Robert Manners), in comp.os.linux.setup) From timr at probo.com Fri Jul 26 22:54:25 2002 From: timr at probo.com (Tim Roberts) Date: Fri, 26 Jul 2002 19:54:25 -0700 Subject: calendar lameness! References: Message-ID: <1o24kugq5amid8fndc6ds6q53u6rfp9j3n@4ax.com> "James J. Besemer" wrote: > >Tim Peters wrote: > >> [James J. Besemer] >> > ... >> > And don't get me started on when Easter is. >> >> That's easy! Sunday. > >Yeah, but which Sunday? That's easy, too: the first Sunday after the first full moon after the vernal equinox. Of course, that phrase is not so easily translated into a Python expression... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From erict at millfilm.co.uk Fri Jul 5 04:05:23 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Fri, 05 Jul 2002 09:05:23 +0100 Subject: __slot__ issues References: Message-ID: <3D255343.3AE18944@millfilm.co.uk> Arthur Siegel wrote: > (The following is copy of my post to tutor at python.org. > Since I believe it to involve a (minor) bug issue, I > thought I'd copy it here for possible comment) > I don't thing it is a bug and I like it like this. I use it, not only to save memory but also to force myself to declare and init all the variables instance. When I am there, editing the __slots__ I can use the time to actually set a default value in the __init__. (nasty c++ habit) > > Apologies to the folks who do not share my new found interest in slots. > > Which I am starting to think of as the quark of the Python object world. > > >>> class A(object): > __slots__=("a") > >>> class B(A): > __slots__=("b") > >>> b=B() > >>> b.__slots__ > 'b' > >>> b.a=4 > In other words "a" is somehow acting as a slot for > B instances, but is not *in* B.__slots__. > How would one then reference, introspect, whatever > as to what are in fact available slots for instances of B? > It will not be hard to have a method to build up a the concatenate slots from parent class: self.__class__.__bases__ > > And a possibly minor bug: > > >>> class A(object): > __slots__="a" > > >>> class B(object): > pass > > >>> class C(A,B): > __slots__=("b") > > >>> c=C() > >>> c.a=1 > >>> c.b=2 > >>> c.c=3 > Traceback (most recent call last): > File "", line 1, in ? > c.c=3 > SystemError: C:\Code\221\Objects\dictobject.c:511: bad argument to internal > function > > If B is a classic class and I do the same multi-inheritance I get the > expected error message: > > AttributeError: 'C' object has no attribute 'c' > > So its the error message, not the behavior that I am pointing to as probably > unintended. > > Art > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From fredrik at pythonware.com Sat Jul 27 15:15:55 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 19:15:55 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: Carl Banks wrote: > So now you're advocating building a framework of closures to replace > the lambdas? This is what appears odd to me: you want me to inline > sorts in the interest of not overgeneralizing, but it seems the same > can be said by your use of make_items_accessor above. don't feed the troll. From debl2nonospammywhammmy at bellatlantic.net Tue Jul 2 21:38:15 2002 From: debl2nonospammywhammmy at bellatlantic.net (David Lees) Date: Wed, 03 Jul 2002 01:38:15 GMT Subject: GoTo considered missing References: Message-ID: <3D225589.B2FF52AC@bellatlantic.net> There was a relatively recent extended exchange which you can find either in dejanews or by looking back on 6/19/02 for a subject line: 'GOTO w/ Python?'. It is a hot button topic for a few people, but you will find some nice discussion in the followups plus useful links such as: http://www.acm.org/classics/oct95/ (this particular one posted by Simon Brunning) David Lees Harvey Frey wrote: > > OK. I'm a spaghetti-coder from way back, new to Python. > I didn't even realize there was no "goto" till I tried to rewrite a big C > program in Python. > > Breaks and Continues are fine for single loops, but: > What is the approved Python method for getting from the bottom of a set of > nested loops to the top? > > Maybe I could rewrite the big loop with function calls, but I'd be > knee-deep in recursion. > > Harvey > ========================= > Harvey S. Frey MD PhD Esq. > hsfrey at harp.org www.harp.org > C'est Vrai. C'est Frey! > ========================= From loewis at informatik.hu-berlin.de Tue Jul 30 10:22:19 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2002 16:22:19 +0200 Subject: Finding count of currently open file descriptors. References: <3D469D2F.6010003@truis.com> Message-ID: Tim McNerney writes: > How do I go about finding out the number of file descriptors currently > open in a program? Depends on your operating system. On Linux, /proc/self/fd contains this information. In a Python debug build, you can find out all file objects, but there may be file descriptors not controlled by Python file objects (e.g. if opened by os.open). > I'm trying to track down a file descriptor leak which may or may not > be in library calls. Will I run into problems getting an accurate > count due to the possible delay between doing a close and GC? If you do a close, the file is closed immediately (i.e. when the close returns). Cyclic GC is usually irrelevant, since file objects cannot participate in a cycle - they can, however, be referred to from a cycle. Regards, Martin From gcordova at hebmex.com Wed Jul 3 15:20:12 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 3 Jul 2002 14:20:12 -0500 Subject: GoTo considered missing Message-ID: > | > | I'd like to know too. I can't really think of an example > | where I'd need a goto statement. > > Come on, guys - think outside of the block! > > Donn Cave, donn at u.washington.edu > C'mon Dave, think outside of the spaghetti. Or, structure your project a bit. You'll find that you really don't need a goto. -gustavo From wyojustin at hotmail.com Thu Jul 18 19:45:14 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Thu, 18 Jul 2002 23:45:14 GMT Subject: web-hosting with psp? References: <3D34035A.F7904AE@gol.ge> Message-ID: You might want to check these guys out: http://www.oinko.net/freepython/ Justin "Giorgi Lekishvili" wrote in message news:3D34035A.F7904AE at gol.ge... > Hello! > > Is there any web-hosting provider, which already supports webware python > server pages? > > I remember a few providers supporting python cgi. > > > Thank you, > Giorgi > From aleax at aleax.it Tue Jul 9 01:49:52 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 05:49:52 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2A078A.7040502@ob_scure.dk> <06F2E275AA053281.30FCDA468DD949D2.9ED8D7E798995448@lp.airnews.net> <3D2A2586.5070302@ob_scure.dk> Message-ID: <4QuW8.46343$Jj7.1305133@news1.tin.it> Thomas Jensen wrote: ... > I'm a little scared though about using SQL too extensivly. Joe Celko's "SQL for Smarties" might be just what you need to move you to the next level of SQL usage (or, to turn you off it for life, depending:-). Alex From jeffm52 at rivernet.com.au Tue Jul 30 20:28:08 2002 From: jeffm52 at rivernet.com.au (Jeff Melvaine) Date: Wed, 31 Jul 2002 10:28:08 +1000 Subject: Newbie question: unexpected diagnostic when subclassing Message-ID: <3d472b34$1@news.rivernet.com.au> I think I must be doing something basically wrong, but ... ??? I'm running Python 2.1 on Windows 98. I create a file x.py in which I declare class x: ... The basic operations of this class work OK. I then create a file y.py in which I declare class y(x): ... When I try to create an instance of y, I get the diagnostic TypeError: base is not a class instance referenced to the definition of class y. In this context, does x really have to be a variable whose value is an instance of class x? Thanks in advance. Jeff From BethO at surfware.com Thu Jul 25 17:48:05 2002 From: BethO at surfware.com (BethO at surfware.com) Date: Thu, 25 Jul 2002 14:48:05 -0700 Subject: embedding pythonwin into an MFC application Message-ID: Hi, I have a program where alot of the processing is written in C++, but this is driven by a python script. We want the end users to be able to make their own modifications if they want to, so we'd like to embed the pythonwin application within an MFC C++ interface. I'm having some problems getting started in this regard...............I looked at the embedding pythonwin documentation that was included, but I don't have the file win32uihostglue.h on any of my machines................................I'm not sure what downloads contain this file............. When I look at the C++ documentation, it talks about embedded applications in relation to how they modify the document...........I really don't want to modify the document in this way, I just want to embed the Python application within a C++ view, so I'm really not sure about implementing the container on the C++ end, etc.......... Anyhow, any feedback in this regard is most appreciated. Thank you for your time. Sincerely, Beth E. Okun From nas at python.ca Fri Jul 26 13:58:55 2002 From: nas at python.ca (Neil Schemenauer) Date: Fri, 26 Jul 2002 10:58:55 -0700 Subject: Guide to the python interp. source? In-Reply-To: ; from tim@bladerman.com on Fri, Jul 26, 2002 at 12:36:53PM +0000 References: Message-ID: <20020726105854.A16968@glacier.arctrix.com> Tim Gahnstr?m /Bladerman wrote: > Is there a guide or a recomended way to "get to know" the source code to the > python interpreter? Not that I know of. Here are a few pointers: * Python/ceval.c:eval_frame is the heart of the virtual machine. This is were most of the work is done. Use the 'dis' module to disassemble bytecode to get an idea of how the VM works. For example: >>> def foo(): ... return 10 + 20 ... >>> import dis >>> dis.dis(foo) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 (10) 9 LOAD_CONST 2 (20) 12 BINARY_ADD 13 RETURN_VALUE 14 LOAD_CONST 0 (None) 17 RETURN_VALUE * The data structures in Include/object.h are key. You should study PyObject, PyVarObject and PyTypeObject. * Most builtin objects live in the 'Objects' directory. There is usually one file for each object. Some objects have header information in 'Include'. * The parser lives in 'Parser' and the compiler is in 'Python'. I would recommend studying the compiler written in Python (in Lib/compiler) rather than the one written in C. HTH, Neil From jmm at sublogic.com Fri Jul 12 04:59:51 2002 From: jmm at sublogic.com (James Manning) Date: Fri, 12 Jul 2002 04:59:51 -0400 Subject: broken URL in FAQ entry 4.77 Message-ID: <20020712045951.A3924@xanex.hippierage.org> http://www.python.org/doc/FAQ.html#4.77 missing a slash in a URL (currently listed as http:/www.digicool.com/releases) and it should really be href'd, although the missing slash may be why it's not linked. If there's a better place to send this, please just let me know and/or forward it along. Thanks, James -- James Manning GPG Key fingerprint = B913 2FBD 14A9 CE18 B2B7 9C8E A0BF B026 EEBB F6E4 From gmfawcett at operamail.com Wed Jul 10 14:16:34 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 10 Jul 2002 11:16:34 -0700 Subject: Pyrex and Distuils: an enhanced build_ext command References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> <3d799735.0207100216.4eb8a9cd@posting.google.com> Message-ID: <3d799735.0207101016.5e223a43@posting.google.com> "Thomas Heller" wrote in message news:... > > 1. The 'official' way to replace a standard distutils command > class is done in the following way: Derive your class, say > 'my_build_ext', from the standard distutils command: > > class my_build_ext(build_ext): > .... > > and then pass a cmdclass parameter to the setup command: > setup(... > cmdclass = {'build_ext': my_build_ext}, > ...) Ironically, Thomas, you inspired the approach that I took -- I borrowed it from py2exe. ;-) But, all things being equal, "simple and explicit" always trumps "import hack". Thanks, I'll take this into account. > 2. Looking at distutils command.build_ext source, there is already > a method which 'precompiles' source files into .c files, it's the > swig_sources() method. Sound a little hackish, but probably we could > get away with just overriding this method in the my_build_ext class. > Maybe something like the swig_sources() command should be promoted > into an 'official' hook for precompilation? When I subclassed build_ext, I just cut out the swig_sources() method, assuming it was SWIG-specific. But I see the analogy and agree that this would be a clean place to put the "pyrexc" code. Thanks, Thomas, -- Graham From donn at u.washington.edu Tue Jul 16 12:18:54 2002 From: donn at u.washington.edu (Donn Cave) Date: 16 Jul 2002 16:18:54 GMT Subject: Making code 2.1 compatible References: Message-ID: Quoth Michael Hudson : ... | Which parts confuse you? Or has Tim cleared it up? Yes, thank you, the faq reference was all it took. ( http://www.python-in-business.org/pbf_content/faq ) | [Tim, later] | > If they don't, we do -- the volunteer bugfix-release Patch | > Czars so far have taken a strong "no new features!" stance. | | Note that a selling point of the "no new features!" stance is a | reduction of the work required... every time I said "no" to a patch, | there was less fiddling with cvs to do. Sure, though the circumstances look different to me, with more resources available to add features, and more pressure to do so. But like I said, it sounds like they have thought about it - ``For the core language, this is a sensitive issue, ...'' Donn Cave, donn at u.washington.edu From gerhard.haering at gmx.de Sun Jul 28 15:25:42 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 28 Jul 2002 21:25:42 +0200 Subject: Help! Python to compare dates in diff. timezones In-Reply-To: <3D4430F4.5040005@beeb.net> References: <8f8ffe67.0207280817.6fc327b8@posting.google.com> <3D4430F4.5040005@beeb.net> Message-ID: <20020728192542.GB902@lilith.my-fqdn.de> Just adding some technical tips. * rmschne [2002-07-28 19:04 +0000]: > Sunit, > > I would recommend you do the following. > > 1. confirm the system date each site is running on the relevant machine. > 2. confirm the times in the database match what you expect from 1 > > (I say steps 1 and 2 above as I was once caught out by what I thought > were two different time-zoned machines, but in fact both were set for GMT). > > 3. along those lines, consider setting both machines to GMT or some > common time. > > 4. Ensure you keep both machines in synch with each other re time, or > at least to a common standard. You recognize that both machines could > be set for a different time zone, but you also ought to control the > drift that inevitably will occur. The natural solution is to use NTP here. > 5. In your Python script, simply have a variable which records the > time zone of each site, and then write a function that does the > arithmetic (adding or subtracting hours) to suit your needs. mxDateTime would come in useful here. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dgallion1 at yahoo.com Wed Jul 24 23:54:05 2002 From: dgallion1 at yahoo.com (Darrell) Date: Thu, 25 Jul 2002 03:54:05 GMT Subject: Python 2.2.1 Idle can't find _sre (Win98) References: Message-ID: A shot in the dark. Check you python path with something like this. Run it by double clicking it, to check file associations. import sys print sys.path raw_input("Done") Old .pyc and .pyo files have caused me problems. --Darrell Gary Pajer wrote: > Using Win98SE. > Python 2.2 has been working fine. On a whim I upgraded to 2.2.1 today. > Now Idle won't start. > The traceback says that sre_compile.py fails at "import _sre" , No module > named _sre. > > A search of google groups came up dry. > Any idea? From ergeorge at worldnet.att.net Tue Jul 30 12:36:07 2002 From: ergeorge at worldnet.att.net (eg) Date: 30 Jul 2002 09:36:07 -0700 Subject: Python equivalent to 'which'? Message-ID: <732d35a1.0207300836.3836892e@posting.google.com> Is their a python equivalent to the bash shell command 'which'? I haven't found it, and 'which' is such a common word that it may be lost in the noise in my dejanews searches :( I could grab the PATH environment variable and walk all the paths, but I'm hoping python has already done it for me! Thanks Eric From ld at nospam.com Wed Jul 24 23:34:16 2002 From: ld at nospam.com (Larry) Date: Thu, 25 Jul 2002 03:34:16 GMT Subject: UDP Multicast HELP! References: Message-ID: "Martin v. Loewis" wrote in message news:m38z40hi1o.fsf at mira.informatik.hu-berlin.de... > The problem here is that IP_ADD_MEMBERSHIP requires a struct ip_mreq, > which is typically defined as > > struct ip_mreq > { > struct in_addr imr_multiaddr; /* IP multicast address of group */ > struct in_addr imr_interface; /* local IP address of interface */ > }; > > So this is an 8-byte value. For imr_interface, you usually specify > INADDR_ANY, which is '\0\0\0\0', so you really need to use > > group = socket.inet_aton('234.5.6.7') + '\0\0\0\0' > s1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group) > > [Strictly speaking, you should use struct.pack to build the struct, > but the code above is just as portable, I assume] I truly appreciate you taking time to respond, but I really don't understand what you are trying to explain to me. Everything else in python seems so easy, and creating a tcp socket and udp socket is so easy, just a few lines of code. I am really surprised that there is no EASY way to join a group. Now, your explanation SEEMS like all I need to do is make a few adjustments, but the "struct" throws a loop at me cuz I never messed with that before. If I really do just need an "adjustment" to the above code I posted, could you repost my code with the corrections so I can see how it all comes together! Thanks, Larry From torppa at staff.megabaud.fi Sat Jul 6 18:43:21 2002 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Sat, 6 Jul 2002 22:43:21 +0000 (UTC) Subject: Given PID, make sure a process is running on Unix? References: <3D2770A8.7070900@ob_scure.dk> Message-ID: In article <3D2770A8.7070900 at ob_scure.dk>, Thomas Jensen wrote: > VanL wrote: >> Hello, >> >> I am trying to get write a python script that on Unix reads a PID from >> a file and, if that process is still running, exits. If the process is >> not running, the process would be started. >> >> I have everything written except the part that makes sure the process is >> running. I have poked through the os module, but I can only seem to >> find information about the current process or child processes, not just >> some arbitrary process. > > If your system has a 'proc' device, you could do something like this: > os.path.isdir('/proc/%d' % pid) > Most Unix flavours have a proc device AFAIK. All(?) unix flawors have kill(2) >>> import os >>> os.kill(12331,0) Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 3] No such process >>> os.kill(os.getpid(),0) >>> -- Jarkko Torppa, Elisa Internet From h.baumgartl at chello.NOSPAM.nl Wed Jul 17 07:03:04 2002 From: h.baumgartl at chello.NOSPAM.nl (Henry Baumgartl) Date: Wed, 17 Jul 2002 11:03:04 GMT Subject: string encoding - how to make it work Message-ID: Hello all, Looking through material i could find on the matter, i haven't been able to find a workable solution that will allow me to write code that will take keyboard string input from any Python supported OS, and generate identical strings anywhere else. For example: On my W2K box, command line input has no problems dealing with defined short-cuts, as in: Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> aes='d?f' In IDLE this generates the Error: UnicodeError: ASCII encoding error: ordinal not in range(128) (the standard Python command line interpreter accepts this definition and subsequent print statements without a problem) The following works on IDLE, although print generates an unprintable character: >>> aes='d\x89f' >>> aes 'd\x89f' >>> print aes d?f The next issue is that even when the input is accepted, reading the string from different applications becomes an unpredictable adventure. Is there a way, using standard string methods, to write code that will always generate the same output? Best regards, Henry From jaeggi at NOSPAMembl-heidelberg.de Wed Jul 3 09:51:24 2002 From: jaeggi at NOSPAMembl-heidelberg.de (Daniel Jaeggi) Date: Wed, 03 Jul 2002 15:51:24 +0200 Subject: baffling bug in this bit of code! References: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> <3D22FD0C.10509@mxm.dk> Message-ID: <3D23015C.7000803@NOSPAMembl-heidelberg.de> Max M wrote: > Are you shure you are not comparing apples and oranges here ??? > > erhh I mean strings and integers ... > > Ie. > > max_y = '8' > y = 42 > if (y > max_y): > etc. OK, that has sorted it - I've forced my x and y to be int's. But that still didn't explain the behaviour. repr(x) revealed that x was a string while max_x was an int but the program still managed to produce the right result. Whereas y was exactly the same but didn't come up the same. This is what confused me initially! Thanks, Dan -- "There must and shall be aspirin. If I do not have aspirin, I shall die." From aahz at pythoncraft.com Wed Jul 3 12:37:04 2002 From: aahz at pythoncraft.com (Aahz) Date: 3 Jul 2002 12:37:04 -0400 Subject: is attribute access a hash-lookup by name? References: <66715c02.0207021737.b488f07@posting.google.com> Message-ID: In article <66715c02.0207021737.b488f07 at posting.google.com>, Steven Shaw wrote: > >As I understand it, in Python, an object is an associative array or >hash. Not quite true. It's more accurate to say that an object is a chunk of memory. However, the vast majority of objects contain a dict to perform attribute lookup. >I imagine this means that every attribute access is a >hash-lookup by name. Does the implementation optimise this away >somehow? Not usually, except for some built-in objects and function local names. >Is there a way to have structs/records in Python where the members of >the struct are looked up by offset (not by name)? Tuple or list would be the obvious ones, though it's possible in 2.2 to have fancy two-way structures that can do both offset-based and name-based lookups (see os.stat for an example). Also, with new-style classes, you can use __slots__ to force vectorized lookups, but it's more a memory-saving technique than a speedup. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From matt_gerrans at hp.com Mon Jul 8 18:42:07 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Mon, 8 Jul 2002 15:42:07 -0700 Subject: private References: Message-ID: > Ok, here's a challenge for you... Write a C++ program with private data > members, then find at least two trivial ways of circumventing it. And when you've completed this exercise in C++, try it in Java. ;-) From aleax at aleax.it Fri Jul 5 13:31:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 17:31:36 GMT Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) References: <3D2487CB.9000102@gmx.de> <3D24FAC5.3050406@something.invalid> <2259b0e2.0207050852.3b603a9a@posting.google.com> Message-ID: Michele Simionato wrote: ... >> while: >> line = f.readline() >> gives line <> "": >> do_something() >> >> Some day I'll get around to PEPping this... > > Python2.2 has already > > for line in f: do_something() > > where f is a file object. ...and for those cases where the function called is not specifically f.readline(), iter can still help: while: blup = anobj.amethod() if blup == '': break do_something(blup) becomes: for blup in item(anobj.amethod, ''): do_something(blup) You can take this as an indication of things to come, maybe -- appropriate iterators or other generators do let you express just about any loop as a for. My tutorial about iterators and generators is up for download at the Europython site, www.europython.org, since I just presented it at the Europython conference. Not sure about the URL, and www.europython.org is not responding right now so I can't check -- anyway, what's up for sure is a ZIP of the .PPT (Microsoft Powerpoint file) -- Marc Andre Lemburg also kindly turned it into a .PDF file, but I don't know if that's up for download yet (but should be pretty soon anyway). Alex From fredp at mygale.org.nospam Fri Jul 5 12:24:33 2002 From: fredp at mygale.org.nospam (Fred Pacquier) Date: 5 Jul 2002 16:24:33 GMT Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: Alex Martelli said : > Now, I don't really know why people are so obsessed about > wrapping things up as "a single statement" rather than > going for speed, clarity, concision, elegance, and all > other aspects of code that can sensibly be considered > good ones. But anyway, if "wrapping up into a single > statement" is what rocks your boat, for whatever reason, > you can hardly complain that Python doesn't LET you do > it. It may be silly, but then, some of Monty Python's > routines were also silly, but still hilarious, no? Yes :-) Thanks for the heads-up, Alex ! -- YAFAP : http://www.multimania.com/fredp/ From mgilfix at eecs.tufts.edu Wed Jul 24 17:41:40 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 24 Jul 2002 17:41:40 -0400 Subject: Which gui for slow (133 Mhz) pc In-Reply-To: <3d42f3dc.5866543@news.utanet.at>; from scrutinizer@gmx.at on Wed, Jul 24, 2002 at 06:38:38PM +0000 References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> <3d42f3dc.5866543@news.utanet.at> Message-ID: <20020724174140.A3904@eecs.tufts.edu> On Wed, Jul 24 @ 18:38, Francesco S. wrote: > Following another thread, Qt seems to be also a very interesting > alternative, I don't know now, if I should spend some time to examine > the pyqt libraries, but this is another story, I think ... GUI stuff always comes down to your needs really. But pretty much all the toolkits out there can accomplish the same thing, and at roughly the same speed (which is pretty decent to being with) for most applications. What you might want to ask yourself is: how portable does my application need to be (do I want *nix and windows support, for example) and do I need threading? That's when it can get a little iffier and in that case, I've found wxPython to be best. -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From aleax at aleax.it Wed Jul 24 09:25:41 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 13:25:41 GMT Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> Message-ID: Keith S. wrote: > Alex Martelli wrote: > >> You may have forgotten to conclude the string with a >> '\n', which is typically needed from the point of view >> of Python's syntax (for "dedent"...). > > The bit that drives Python is like this (I'm using > QT for the GUI, and m_cmdview is just a pointer to > the QLineEdit widget): QLineEdit handles (and returns) a single line, right? Therefore, how can you use it to input a multi-line command? > for x in [1, 2, 3]: > > ^ > SyntaxError > : > unexpected EOF while parsing The string seems to be finished here (where no doubt there was a newline) which indeed IS a syntax error exactly for the given reason. Why not use a multiline editing widget instead? Alex From a_salnikov at yahoo.com Fri Jul 12 14:40:42 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Fri, 12 Jul 2002 11:40:42 -0700 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> Message-ID: "Louis M. Pecora" wrote in message news:110720021224320303%pecora at anvil.nrl.navy.mil... > In article <3D2CEDA1.4ACA69FE at engcorp.com>, Peter Hansen > wrote: > > > Actually, the Morse is much easier to write, since it doesn't > > require the Shift key (god how I hate underscores) > > > Just go and design + develope your own keyboard. > Why bother, look here is one: http://anekdotov.net/pic/comp2/2404morze.jpg It should have smileys on it, I bet :) Andy. From warkid at storm.ru Thu Jul 4 07:02:23 2002 From: warkid at storm.ru (Kerim Borchaev) Date: Thu, 4 Jul 2002 15:02:23 +0400 Subject: I'm an idiot In-Reply-To: References: Message-ID: <12626.020704@storm.ru> Hello David, having noticed that every solution suggested writes extra eol at the end of resulting file i'd like to present my version with tests included. ####################################### def strip_file(src, dst): f = open(dst, 'w') for line in open(src).readlines(): eol = '' if line and line[-1]=='\n': eol = '\n' f.write(line.strip()+eol) def test(src, expected): import tempfile f0 = tempfile.mktemp() f1 = tempfile.mktemp() open(f0, 'w').write(src) strip_file(f0, f1) res = open(f1).read() assert expected == res test('hello\nworld', 'hello\nworld') test('hello\nworld\n', 'hello\nworld\n') test(' hello\n world', 'hello\nworld') test(' hello \nworld', 'hello\nworld') test(' hello world ', 'hello world') ####################################### Enjoy! Kerim mailto:warkid at storm.ru Saturday, June 29, 2002, 5:00:22 AM, you wrote: D> OK, I am the first to admit it. I am an idiot. I have RTFM on this over D> and over, and I can still not figure out what I am doing wrong. D> I think the intent of the code is obvious, but just to clarify, I want to D> read every line in a file and write those lines back out to another file, D> but with leading and training space removed. I also want to have some D> elegant way to determine that I have reached the end of the file and D> break out of the loop. D> And just to explain my stupidity, my reference langauge is BASIC. I D> could have written this in BASIC in a minute, but I need to learn D> something new. Any help would be appreciated. D> David D> f=open('c:\\temp\\temp.txt', 'r') D> g=open('c:\\temp\\temp1.txt', 'w') D> while 1: D> try: D> s=f.readline D> g.write(s.split()) D> except IOError: D> break D> g.close D> f.close From jblazi at hotmail.com Mon Jul 15 04:02:33 2002 From: jblazi at hotmail.com (JB) Date: Mon, 15 Jul 2002 10:02:33 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308c96_8@news.newsgroups.com> <3d315be9_1@news.newsgroups.com> Message-ID: <3d327fcc_2@news.newsgroups.com> Bengt Richter wrote: > On Sun, 14 Jul 2002 13:17:09 +0200, JB > wrote: > >>Bengt Richter wrote: >> > [...] >>> (Is this like your data? Or how does it differ?) >> >>This is ok. The real data are much longer strings, but it >>is ok. > A further question: What generates the "id" number, and > what do you need it for besides verifying order? Do you > need it as a key to other data locally or remotely? Or is > your concern just guaranteeing > unchanged order as the selection narrows? To tell you the truth, I do not know. Yesterday I noticed, that I did not need it, but it does not matter much. At the moment I use the following solution (it shows what I am after): #------------------------------------------------------- #self.rows is a list of QSimpleViewItem class #instances. The definition of this class is at the end #of this message. The lists and # contain natural #numbers of the set #{0,1,...,N-1}, where N is the total number of elements #of self.rows. If we have an i with #0 <= i < N, then i is either in or in #. #------------------------------------------------------- # Only those rows are shown, for which the -th # coloumn contains the string def filter_out(self,c,s): print 'filter (1)' tmp = [] for v in self.visible: if string.find(self.rows[v].col[c],s) == -1: self.hidden.append(v) else: tmp.append(v) self.visible = tmp self.hidden.sort() print 'filter (2)' self.update_sb() #update scrollbars self.update_view() #---------------------------------------------------- def filter_in(self,c,s): print 'filter (1)' tmp = [] for h in self.hidden: if string.find(self.rows[h].col[c],s) != -1: self.visible.append(h) else: tmp.append(h) self.hidden = tmp self.visible.sort() print 'filter (2)' self.update_sb() self.update_view() So I use two functions. is called when the search string gets longer and filter_in when it gets shorter. Even this is pretty fast. It seems to me that the append operations are expensive here (they take much time), but I always thought that Python lists are arrays... > > If it's just order, we can probably eliminate them, and > gain speed. If you need the id's, and the rest of the > tuple is just a single string item, then we will gain > speed by combining the id into the string, perhaps as a > suffix. The gain will come from having a list of > string-only elements so that we can search for substrings > without a subscript operation on a tuple for every > element, and being able to use map or filter using builtin > functions. This may allow simpler approaches with adequate > speed. This I do not understand. > Well, maybe the question was a little too broad ;-) > My example searched first for 'B' then for 'Y' within the > results of the first search, but it did not search for > 'BY'. Oh! I do not want that. > This is an important distinction, since you will > presumably want to refine a search for, e.g., Bach by > incrementally refining based on 'B', 'Ba', 'Bac' and > 'Bach', but if you want to find his Italian Concerto, you > don't want to continue refining results by searching them > for 'BachI', 'BachIt', 'Bachita', etc. I.e., you are > finished with Bach and should presumably refine further > based on 'I', 'It', 'Ita', etc. found anywhere in the > entries you have so far. Or search for "italian" immediately. The QListView widget (if you are a bit familiar with Qt) already has an incremental search built in but it looks only for patterns the strings start with. >>Of course, only 40 or so lines can be displayed at the >>same time. It plays no r?le if I pass list or tuples of >>strings. >> > You mean no difference if you pass ('x','y','z') or > ['x','y','z']? But I was referring to tuples including the > integer id number. IOW, I wouldn't expect to pass > [(24,'x'), (25,'y'), (26,'z')] to a low level single > column dropdown list widget that I wanted to show x, y and > z. So the question is in what form your parameters need to > be passed. This again I do not understand. I have defined a class: class QSimpleViewItem: def __init__(self,id,color,tuple): self.id = id #for future use :) self.col = tuple #here are the strings self.sel = 0 #selected or not selected self.color = color #color of the line In the

tuple, I shall almost always use coloumn 2 for my searching. But I may want to use other colomns too. When update_view is called, my widget takes a list of QSimpleViewItem-s and updates the screen. > As you notice, we are now a long way from discussing just > "Moving list entries from one list to another" ;-) Yes, sorry. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From tim.one at comcast.net Wed Jul 24 21:56:03 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 24 Jul 2002 21:56:03 -0400 Subject: Python 2.2.1 Idle can't find _sre (Win98) In-Reply-To: Message-ID: [Gary Pajer] > I tried to follow the instructions in http://www.python.org/2.2.1/ What instructions ? > First I downloaded http://www.python.org/ftp/python/2.2.1/UNWISE.EXE > over my existing unwise.exe Good move. The next time you try this, uninstall Python immediately after this step (that's what unwise.exe is for). It will only delete files that it originally installed (so if you have 3rd-party extensions, etc, it will leave them alone). If it asks whether you want to do "a rollback", say no (because you're going to install a newer Python anyway). I don't know that uninstalling first will actually help, but I never try installing a new version of anything over an old version of that thing, so I don't know that it won't help either -- and it might. > Then I downloaded http://www.python.org/ftp/python/2.2.1/Python-2.2.1.exe > > Then I started the installer. It detected c:/python22 Not quite -- it always suggests that directory, even if it doesn't exist, or even if you have a previous installion in a different directory. > and offered to install there. I said ok That means it was installing in > the same directory as version 2.2 lived. Right. > It offered to make backups of existing files, I said yes, please. That's a good idea too. If you get utterly sick of Python, the uninstaller supports a "rollback" mode, which restores everything (within reason) to what it was before you installed Python. > That's all. > > Since my first post, I noticed that PythonCard applications > crashed with the same error. I found a file called _SED.PYD in the new > installation, There is no such file. Do you mean _SRE.PYD? Even that would be peculiar. That's the name Wise uses internally for the file, but it should have changed it to lowercase while installing it. > but in the backup, the filename was lowercase. I renamed the file to > _sed.pyd, and now PythonCard apps start, but IDLE still doesn't. Again, there is no such file in the distribution. You could try renaming it to _sre.pyd, but your system is in such a unique state, if I were you I'd blow away my Python22 directory and start over from scratch. Or install 2.2.1 into a different folder. From jbarilla at princeton.edu Mon Jul 15 22:25:46 2002 From: jbarilla at princeton.edu (Joseph Barillari) Date: Mon, 15 Jul 2002 22:25:46 -0400 Subject: Base-class method access Message-ID: Hi. Is it possible for a derived class to access overridden methods of its base class? For example: class Foo: def frob(): print "Spam" class Bar(Foo): def frob(): print "Eggs" # In C#, the syntax to call Foo's frob() would be # base.frob() >> a = Bar() >> a.frob() Eggs Spam Is there a means of doing this in Python? Thanks in advance. --Joe -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 265 bytes Desc: not available URL: From BPettersen at NAREX.com Mon Jul 1 00:57:16 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Sun, 30 Jun 2002 22:57:16 -0600 Subject: private Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192F1AA02@admin56.narex.com> > From: - c o v e n t r y - > > >>Kind of off-topic, but this got me curious. The only way I > >>could think of is to assume (which I think is always true) > >>that the private data members are in order from the starting > >>address so based on the offset from the address of the object > >>you could access each one. > >> > > > > .. and of course #define private public, or just go in and > edit the .h > > file... > > True, but you could edit gcc to allow access to private > members of a C++ > class, could you not? Hrm, this issue probably isn't whether it is > possible to hack around an implementation of 'private', but > more about having a real 'private' type/functionality. Right > now, we hack to put simulate private - why not make other > hack to work around it? The OP asked about private vars/methods like C++. Above are three ways to get around private in C++ without recompiling the (possibly third party) C++ library you're #including. As you see, the private declaration in C++ is mostly informational. In Python we use _ or __ prepended to var/method names to achieve the same effect. Python does have true private vars/methods through the Bastion module, but most Pythonistas don't see the purpose. After all, if you can't trust your developers you have bigger problems. -- bjorn From achim.domma at syynx.de Thu Jul 4 15:34:07 2002 From: achim.domma at syynx.de (Achim Domma) Date: Thu, 4 Jul 2002 21:34:07 +0200 Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: "Eric Brunel" wrote in message news:ag1fj0$inr$1 at wanadoo.fr... > I don't which one of these two or Achim's one is the most efficient. I also don't know, but you can make it in one line: for count,name in dict([ (count,name) for name,count in myDict.items() ]).items(): print count,name wether this is good code or not is another question ... ;-) Achim From mwh at python.net Mon Jul 29 06:41:13 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Jul 2002 10:41:13 GMT Subject: Python Internals Doc References: Message-ID: "David LeBlanc" writes: > There was, at one time, a website describing Python's internals - > anyone know if it's still available and, if so, where it can be > found? Are you sure? I don't think I've ever seen such a thing. Cheers, M. -- nonono, while we're making wild conjectures about the behavior of completely irrelevant tasks, we must not also make serious mistakes, or the data might suddenly become statistically valid. -- Erik Naggum, comp.lang.lisp From phr-n2002b at NOSPAMnightsong.com Sat Jul 13 08:24:40 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 13 Jul 2002 05:24:40 -0700 Subject: login with python (2) References: Message-ID: <7x65zjvmrb.fsf@ruckus.brouhaha.com> "Ralf Claus" <102030405 at gmx.net> writes: > Hello, the login website of my router needs the following html code to login > : > >
>

> > something like this could work (untested): import urllib LOGIN = "http://192.168.2.1:/login.htm" SITE = "go" PASSWORD = "..." data = urllib.urlencode({"site": SITE, "password": PASSWORD}) file = urllib.urlopen(LOGIN, data) print file.headers print file.read() study the headers and the page contents carefully to see what you need to do next (the site may be forwarding you somewhere, possibly using javascript; it may use cookies, etc) From matt_gerrans at hp.com Tue Jul 9 19:10:58 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Tue, 9 Jul 2002 16:10:58 -0700 Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: > >>On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote: > >>> eval! > >>Overkill. Unsafe. Ugly. Lame. > >What do you mean by unsafe? > Something like the following could happen (don't try it!) > # eval('system("rm -rf /")') Hey, that has no effect on my Windows system! Could this be because of Bill Gates' recent one-month edict that Microsoft focus on making Windows secure? ;-) (I don't think I'll test it on my Linux box, though!) Anyway, that's assuming you have no control over the input; if that is the case, you could filter it easily enough: if re.match(r'0x(\d|[a-f])*', string, re.I ): n = eval(string) else: n = 0 # Could alternatively raise a ValueError, or something like that, here. You could change this to allow for decimal input, etc., while still not inviting a nefarious chunk of code. (Someone will probably suggest a better re for this...) From duncan at NOSPAMrcp.co.uk Mon Jul 22 04:32:30 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 22 Jul 2002 08:32:30 +0000 (UTC) Subject: Nested scopes question References: Message-ID: Fernando Perez wrote in news:ah84gq$ave$1 at peabody.colorado.edu: > Thanks a lot for the references. So I guess my uglyish hack of hiding > the value inside a list is after all the solution for this problem. > Well, at least it gets the job done :) It sounds a lot as though you should be considering using a class here. Classes are designed for just this job (sharing changeable state between separate function calls). >>> class C: def bar(self): print "x=",self.x self.x += 1 def foo(self): self.x = 0 for i in range(5): self.bar() >>> foo = C().foo >>> foo() x= 0 x= 1 x= 2 x= 3 x= 4 -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tjreedy at udel.edu Fri Jul 12 11:51:19 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Jul 2002 15:51:19 GMT Subject: Converting 2 bytes string into INT References: Message-ID: "DeDa" wrote in message news:agmpj5$muevv$1 at ID-70583.news.dfncis.de... > Hi to all, I'm a newbie of Python and I already have a big problem. I read 2 > bytes from files and I like to convert them into an integer. How can I do > it? If your two bytes form a two-digit string, such as x = '12', use str(s). Otherwise, you have to tell us more. TJR From markus.vonehr at ipm.fhg.de Thu Jul 11 02:36:06 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 11 Jul 2002 08:36:06 +0200 Subject: askopenfilename????? References: Message-ID: <3D2D2756.5466C485@ipm.fhg.de> Hola Juliano, you have to use tuples, for example: one parameter: filename = askopenfilename(filetypes=[("*.jpg", "*.jpg")]) more than one parameter: filename = askopenfilename(filetypes=[(".gif, .bmp", ("*.gif", "*.bmp"))]) jubafre at zipmail.com.br schrieb: > > i don?t know how to use a filetypes option of askopenfilename, somebody > can help? > > askopenfilename(filetypes=???) > > Juliano Freitas > www.gebrasil.hpg.com.br > > ------------------------------------------ > Use o melhor sistema de busca da Internet > Radar UOL - http://www.radaruol.com.br From tim at bladerman.com Sat Jul 27 09:19:45 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sat, 27 Jul 2002 13:19:45 GMT Subject: Guide to the python interp. source? References: Message-ID: "Alex Martelli" > Tim Gahnstr?m /Bladerman wrote: > > Is there a guide or a recomended way to "get to know" the source code to > > the python interpreter? > > Assuming you're familiar with Python's C API (the online docs are good, I guess maybe I must start out there and write some C/python modules to get a feel of that before I start pooking around in the interpreter > and interpretation of bytecode. Those are nasty, particularly (as Thanks, that really encouraged me :-) I will have a look at the places you mentioned that I sniped out to. > of 2.2.1) the compilation. Then you can look at other more > marginal nasties such as garbage collection &c. That is probably not an isue I must look into much at all > > and I will need to monitor the state of the interperter for debugging > > purposes > > Instrumenting the interpreter to understand what exactly is > going on is not hard and does not require complete understanding, > indeed doing and examining such instrumentation will HELP you > further your understanding. I hope so, I actually am starting to think that I will learn a whole lot during this project, not just about Python and the Python interpreter but about CS in general and looking at other peoples code in particular. > Modification is of course another kettle of fish:-). To bad, my plan is actually to have al variables that ar curently in use in a debuggerpanel on one of the sides al the time and also have an inputbox there for the user to be able to change any variable at will. > > Python is, I think, a verry intuitive language for beginners, with some > > modifications it can be even better. Especially with a good IDE. That is > > Two mostly separate issues, I think -- the really good IDE is pretty > uncontroversial (if really good:-), the mods WILL get you flames:-). Definitley separate issues but I felt that both neede a rewrite to make a really good novice suite. It seems like a few people are interested in the project so I will post more on the changes I intend to make and why when I have come a little furter. I assume I will see some flaming but remember the good thing with doing a project of your own. You can end discussions whenever you want and you dont have to care about either flames nor advices :-) > > one of those people that can have a look at a million lines of code and se > > It's nowhere like a million lines! 264k overall including ALL the > platform-dependent goo you don't AT ALL care about. Given that > Modules and Objects are separable, modular and clear, the hard > core is just 30k lines or so in Python/*.c and Parser/*.c. Well, I dindn't actually think it would be a milion lines :-), I just meant that there is to much to be overlookable. > > Things I want to change is for example, everything should be "call by > > refferense", it shall not by case sensitive, redirect output, better > > errormesages, etc, etc. > > Better error messages would of course be a welcome contribution > to Python itself:-). Yes, I actullay think the current once are quite bad, I hope my project is aplicable on the reall interpreter so they can be incorporated in the futre. > "redirect output" is a mystery -- Python's Argh as I said in a reply to Hudson, it was written in a haste and didn't mean much. I have also written a samll errormessage example there. > insensitivity is what gets my personal applause: it's the ONE > feature of the language I truly, deeply dislike (just as I > dislike it in Unix, XML, C, ...). You're in for substantial > work with the *libraries*, I think (not the C-coded ones -- > the Python-coded ones). Maybe, maybe not, Maybe I can just convert everything internaly to uppercase? I don't know, havn't given it much thought yet. > "Call by reference" I gotta see. Just for fun, do it like > good old Fortran used to: > > def inc(x): > x = x + 1 > > inc(2) > print 2 > > should of course print '3'. I have thought about that and that is not what I want. In this particular case I want an integer object to be created with the value 2, that is sent to inc and changed but when we come to the next line that object will be garbage collected because none have a refference to it. Inc will work as it is supposed to do wich is good if you just want to have the sidefects of it. An other possibility would be to generate a good looking errormessage. Because it is likely a mistake. > I suggest you consider "value/copy-return" as an alternative: I will absolutely consider it. > The hard part comes in determining what you want to > happen on e.g.: > f(x, x.y, x.y.z, x.y.z.t) Cheesch! I will consider that by christmas :-) Thanks alot! Tim From m.faassen at vet.uu.nl Tue Jul 9 17:58:29 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 9 Jul 2002 21:58:29 GMT Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: Erno Kuusela wrote: > In article , m.faassen at vet.uu.nl > (Martijn Faassen) writes: > | They do kick you out a bit readily, I agree. I got somewhat annoyed > | when I got kicked out while apologizing for spamming with a misfired > | copy & paste buffer. > it seems to be a part of the life cycle of an irc channel. first > it is only a few people with an intimate atmosphere, then it starts > attracting lots of people because of the friendly atmosphere, and > in a while the intimate atmosphere gradually dissolves. then > the "old timers" leave or start policing with an iron fist... > it doesn't always go like that, but often. Anyway, I like #python, but it might be nice to cut people a bit more slack for their (perceived) stupidity; it doesn't cost anyone a lot, and besides it's more fun -- if someone is really silly or stupid, it's frequently entertaining to watch, I find. And often the person is not really stupid at all, and it just takes a while to connect to each other. (old timers are expecting certain behaviors but a newbie may have other ideas initially). I find it even more amusing to tease old timers, myself. :) You can really spark some of them off by making some heavy claims about the superiority of the C++ language, say. Of course they commonly realize I am doing this, which makes it far less frustrating for everybody than if some innocent newbie is involved. Naturally there are genuinely frustrating or annoying people as well, and those should be dealt with if cutting slack does not help. Anyway, it doesn't have to go this way; I've been involved in a MUD for about a decade, and while there have been cycles, it's been around for a while now, so it must be a reasonably nice place. But I imagine the social dynamics of MUDs are different from the dynamics on IRC, and again matters are different on Usenet. comp.lang.python seems to be scaling quite well, for instance. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From otis_usenet at yahoo.com Tue Jul 23 19:25:29 2002 From: otis_usenet at yahoo.com (OtisUsenet) Date: 23 Jul 2002 16:25:29 -0700 Subject: urllib2 won't raise exceptions References: <5606b639.0207221527.12f91366@posting.google.com> Message-ID: <5606b639.0207231525.c62ce9e@posting.google.com> Problem solved. I had to refer to those URLError and HTTPError objects as urllib2.URLError and urllib2.HTTPError. Otis otis_usenet at yahoo.com (OtisUsenet) wrote in message news:<5606b639.0207221527.12f91366 at posting.google.com>... > Hello, > > I am trying to use urllib2 to make HTTP POST requests and a) retrieve > HTTP status, and b) check for any exceptions. > > 1) I don't see a way to get the status code back from urllib nor > urllib2 (and I read that this will be impossible to get from them and > that httplib should be used instead). > > 2) I read that if something fails, URLError or HTTPError will be > raised. So I have the code to catch them and print someting. > However, nothing ever gets printed, even if I request pages that give > '500 Server Error', like in the case below. > > Am I doing something wrong? > Thanks. > (pardon my indentation, I pasted this a few times...) > > from urllib2 import * > > def sendRequest(self): > > try: > # NB: this URL gives "500 Server Error" > urlObject = \ > urllib2.urlopen('http://www.clr.utoronto.ca/cgi-bin/doc/show/doc=Cross.Rodney') > response = urlObject.read() > urlObject.close() > return response > except URLError, msg: > print "URLError: ", msg; > except HTTPError, msg: > print "HTTPError: ", msg; > except Exception, msg: > print "EXCEPTION" > except Error, e: > print "ERROR" From tim at vegeta.ath.cx Fri Jul 5 05:51:27 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: 5 Jul 2002 02:51:27 -0700 Subject: Why self? References: Message-ID: Jesper Olsen graced us by uttering: > Why is it necessary to use a "self" argument to class methods in python? > > To me it seems a bit like doing object oriented programming in C... > > Why not make it implicit like "this" in C++? > > I do not find it usefull that I can give it my own name. > > So, is it just legacy or is there a reason for this convention? The following link contains an answer to your question. http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.007.htp HTH Tim Hammerquist -- Life *is* pain, Highness. Anyone who says differently is selling something. -- Westley, "The Princess Bride" From marklists at mceahern.com Tue Jul 9 12:24:26 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 9 Jul 2002 11:24:26 -0500 Subject: Splitting a string every 'n' In-Reply-To: Message-ID: > > But the performance of this is hopeless for very long strings! > > Presumable because there's too much list reallocation? Can't Python > > just optimise this by shuffling the start of the list forward? Using generators here compares favorably with a smart while loop. They have the advantage of separating the iteration from the processing, so you can actually reuse gen_substring since it allows you to iterate over the n-length substrings: #! /usr/bin/env python from __future__ import generators from time import clock def gen_substring(s, n): i = 0 end = len(s) while i <= end: j = i + n yield s[i:j] i = j def do_gen(s, n): for sub in gen_substring(s, n): sub.upper() def do_while_simple(s, n): while s: sub = s[:n] s = s[n:] sub.upper() def do_while_smarter(s, n): i = 0 end = len(s) while i <= end: j = i + n sub = s[i:j] i = j sub.upper() def time_it(f, *args, **kwargs): start = clock() f(*args, **kwargs) end = clock() print "%s: %1.3f" % (f.func_name, end - start) n = 4 size = 100000 s = 'a' * size time_it(do_gen, s, n) time_it(do_while_simple, s, n) time_it(do_while_smarter, s, n) - From theller at python.net Mon Jul 1 06:04:18 2002 From: theller at python.net (Thomas Heller) Date: Mon, 1 Jul 2002 12:04:18 +0200 Subject: WindowsError in time.sleep !?!??!! References: Message-ID: "Eric Brunel" wrote in message news:afp8em$r0p$1 at wanadoo.fr... > Eric Brunel wrote: > [snip] > > Does anybody have an explanation and/or a workaround for this problem? We > > may of course delete this statement, but it doesn't sound quite safe: we > > have many time.sleep in our code, and if we don't understand why this is > > happening, it may break another one later... > > We tried to delete the statement, and it actually crashes later, but on an > even stranger line: it's an if statement, just comparing a plain variable > to an empty string (something like "if v == '':"). And we get the same > error: WindowsError, access denied... > This sounds like some C code (in an extension?)is setting an error, and failes to check for NULL afterwards. If you insert something like this before your "if v == '':" line try: 1/0 except: pass and the problem goes away, it seems to be the cause for it. Thomas From jonathan at onegoodidea.com Tue Jul 2 09:27:16 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 02 Jul 2002 14:27:16 +0100 Subject: Web templating/db tool with best designer/coder separation? References: <3d21259f$0$28006$afc38c87@news.optusnet.com.au> Message-ID: On 2/7/2002 5:00, in article 3d21259f$0$28006$afc38c87 at news.optusnet.com.au, "Stephen Tyler" wrote: > The other contenders for my "next-generation" web templating system > typically use XSLT to transform a variety of XML inputs into XHTML output. > But XSLT can be very obtuse for non-coders (and even coders). And it still > needs to be supplemented with a general-purpose programming language. Did anyone mention Cocoon yet in this thread? (I didn't follow the start) I think they've got a very interesting idea based on transforming XML. The main feature of their model is "Separation of Concern" - enabling content authors, designers, and programmers to all work independently. It's sort of like JSP tag libraries, but in multiple layers. Jonathan From gashton at cmedltd.com Mon Jul 8 13:14:36 2002 From: gashton at cmedltd.com (Graham Ashton) Date: 08 Jul 2002 18:14:36 +0100 Subject: Python 2.1 == Jython 2.1 != Python 2.2? In-Reply-To: References: Message-ID: <1026148476.6903.11.camel@walter> On Mon, 2002-07-08 at 17:18, Gustavo Cordova wrote: > > > > > > > > What is an ETA? > > > > > > Typo prolly. > > > > > > ;-) > > > > I think he wants Estimated Time of Arrival > > argh... When is a wink not a wink such that an included > wink does not a wink's function complete, which is to > make others understand that it's a joke? Clearly, it was a "joke" of sorts. ;) But can you really infer that Laura didn't get it, simply because she answered an earlier poster's question? -- Graham Ashton From markus.vonehr at ipm.fhg.de Mon Jul 22 04:23:20 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 22 Jul 2002 10:23:20 +0200 Subject: how to ask for class attribute? Message-ID: <3D3BC0F8.4648E69A@ipm.fhg.de> Hi, my class has several attributes self.* In one method I have to detect if there is already an attribute self.start_value How can I detect, if the attribute already exists? Thanks for any comments, Markus From tim.one at comcast.net Mon Jul 29 19:11:04 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 29 Jul 2002 19:11:04 -0400 Subject: sort() comparison lambda for floats/longs In-Reply-To: <20020729164454.13371.qmail@email.com> Message-ID: [Jack Diederich] > I had to sort a list of list of floats (Nx2 array) > but I couldn't find a comparison function that would take > a little error delta to do the std C-style comparison > > if (a + delta > b && a - delta < b) { > printf("Yeah, a == b"); > } > > here is a lambda I am using in a list.sort() > delta_cmp = lambda a,b,delta=0.00001: > int((((a+delta) > b and (a-delta) < b) and '0') or > (a > b and 1) or > (a < b and -1) > ) > > The int() is needed to turn the '0' from true into zero > It uses the side effects of 'or' and 'and' to return 0/1/-1 Brrrrrr. Throw that away before it breeds . def delta_cmp(a, b, delta=0.00001): if abs(a-b) < delta: return 0 else: return cmp(a, b) does the same thing, but without trickery. Note that there's nothing magical about a lambda expression -- it's exactly the same as a named function except for lacking a name , and .sort() couldn't care less whether you pass it a lambda expression or the name of a comparison function. The runtime is the same either way too. > I need the delta because I'm also sorting on the second > column, which could be an int or string, or anything. Sorry, couldn't follow this part. Careful input -> desired_output examples would be clearer than prose. > If it was just a single list of floats then a compare without > a delta would work because all the nearly-equal values would > still be next to each other. Ditto. > to sort this > ll = [[1.0, 'A'], > [2.0, 'B']] > > I would do > ll.sort(lambda a,b: delta_cmp(a[0],b[0]) or cmp(a[1], b[1])) > > Is there a better way to do this in python? It's completely unclear to me why plain ll.sort() doesn't do what you want. That automatically sorts on "the first column" as the primary key, and looks at "the second column" too if and only if two "rows" have identical values in the first column. The result will be sorted in increasing order of first column, with ties in the first column resolved by increasing order of second column. If you don't think plain .sort() does do what you want, then you really need to give us a specific example where it doesn't do what you want, and show us exactly what you do want instead. From howard at eegsoftware.com Fri Jul 26 16:39:56 2002 From: howard at eegsoftware.com (Howard Lightstone) Date: Fri, 26 Jul 2002 20:39:56 GMT Subject: DOS-Shell hangs up, python/Tkinter References: <3D3FBF1A.C1531FB3@ipm.fhg.de> <3D41171B.1F977845@ipm.fhg.de> Message-ID: Markus von Ehr wrote in news:3D41171B.1F977845 at ipm.fhg.de: > The problem is that with pythonw I don't get the Debug "prints". > > Markus > > Of course, I had a similar problem. There have been many threads discussing this issue. There are also some cookbook recipes about doing this ...... I chose to have a method in which I can choose to have stdout/stderr go to a (dynamic) Tkinter window which pops up when there is 'something' printed. That way, I "know" when something got printed because the window appears. I would be glad to mail it to you if you would like (although it's a little over 130 lines, I hate to waste newgroup bandwidth). I would post it on my website but ... it looks so dumb I hate to advertise it. From martin at v.loewis.de Thu Jul 25 04:27:11 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Jul 2002 10:27:11 +0200 Subject: random 64-bit int References: <5nM%8.30598$4T2.8891354@twister.socal.rr.com> Message-ID: Jeff Davis writes: > It seems like the above works, but I'd like to know whether I am losing > randomness, or whether there is a more efficient or faster way to > accomplish that. Would it be a good idea to include a call to > random.seed()? > > Also, it would be *really* nice if there was a good way to do that in > python2.1, which does not seem to allow the "q" type for unpack(). I think the randomness of this is as good as any other algorithm you could find. On speed and portability, you might consider using hex or octal strings, or plain arithmetic computations. Notice that each random() call really gives you roughly 32 bits of randomness, so you are wasting 16 of them. The approach based on octal numbers works on grounds of long("-12312357623526234343454642342164",8) being supported in all Python versions. Create 7 octal digits (21 bits, unsigned) with two call to random, then create the missing 22 bits (including sign) with another call; print the strings octal, concatenate them, and invoke long(). The approach based on arithmetic works the same, but avoids the string operations: Create three 21 bit numbers a, b, c (a should be signed), then use long(a)<<42 + long(b)<<21 + c You should time all three approaches if performance matters. HTH, Martin From gerhard.haering at gmx.de Tue Jul 9 06:23:41 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 12:23:41 +0200 Subject: [OT] native Java GUI libraries In-Reply-To: <200207091153.15904.b.maryniuk@forbis.lt> References: <96c7f32.0207081518.52ea644a@posting.google.com> <3d2aafce$0$94901$e4fe514c@dreader3.news.xs4all.nl> <200207091153.15904.b.maryniuk@forbis.lt> Message-ID: <20020709102341.GB1792@lilith.my-fqdn.de> * Bo M. Maryniuck [2002-07-09 11:53 +0200]: > On Tuesday 09 July 2002 11:39, Boudewijn Rempt wrote: > > Er, yes. Somebody could: there's qtjava. > May I ask You for link? I'm just curious: Java + QT + crossplatforming. Hmm... It's GPLed. There were also (several) attempts to produce a GTK binding. IBM's developed SWT for its Eclipse framework, which uses native controls where they are available. So, it's not like Swing is the only option (though IMO a very good one, provided you have recent hardware). Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 27.5 ?C Wind: 2.2 m/s From bowman at montana.com Wed Jul 17 00:15:48 2002 From: bowman at montana.com (bowman) Date: Tue, 16 Jul 2002 22:15:48 -0600 Subject: Serial Port Returning Garbage. Why? References: <%gVY8.204$fK3.80978@newsfeed.slurp.net> Message-ID: <786Z8.804$fK3.325642@newsfeed.slurp.net> max wrote: > > No, I'm not. It's just Transmit, Receive, and Ground. Our device > doesn't use any of the other signals, and the implementation doesn't > use QON/QOFF. Would it make a significant difference if I do? It might, if the slave end is a relatively slow device. For instance, the older SBC UARTs or microcontroller internal UARTs might not be able to keep up with the transmission, particularly if they have to do something with each byte as it is received. Usually the receiver will use a DTR signal to indicate it is busy, and the sender won't start the next byte until the receiver is ready. I'm assuming by 3 wires, you mean RX, TX and GND, so even if the hardware handshake is being attempted, it won't be seen across the cable. It is hard to say without knowing your setup. It is possible when you test with HyperTerminal, you are typing the command in, so it really is sent very slowly, but in the working system the master sends the command string much faster and they are getting out of sync. Or, it could just be that HyperTerm is setting the start/stop bits, parity, or something a little differently. I don't think it is the baud rate, since that usually results in all garbage characters. From guidance_shanghai at yahoo.com.cn Sun Jul 7 18:25:53 2002 From: guidance_shanghai at yahoo.com.cn (Leon Wang) Date: 7 Jul 2002 15:25:53 -0700 Subject: Chinese language support of Python? References: <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl> Message-ID: I found the best option: pythonwin, in win32 extension module, including source editor and debugger! Summarize the python for Chinese installation: 1) Python package from python.org 2) Win32all module from http://starship.python.net/crew/mhammond/win32/ 3) ChineseCodecs module from ftp://freebsd.sinica.edu.tw/pub/ycheng/python/ChineseCodecs1.2.0.tar.gz I think these are the best solution so far. Use this to display Chinese(GB) in Tkinter: >>> root.title(unicode('中文',"eucgb2312_cn")) and this in console: >>> root.title('中文') Thanks for all of your help!! Leon Wang > Meanwhile, you have the following options: > > - Don't use IDLE to edit Python source code (but, say, notepad), and > only put Chinese text into string literals. > - Set the default encoding in site.py to the encoding you want to use. > - Apply patch > http://sourceforge.net/tracker/index.php?func=detail&aid=508973&group_id=9579&atid=309579 > > which allows you to declare the source encoding for IDLE. > > In either case, you cannot use Chinese in Unicode literals. Instead, > you should always use > > unicode("chinese string", "chinese encoding") > > For portability, and if your editors support it, I recommend to use > UTF-8 as the "chinese encoding". > > Regards, > Martin From aleax at aleax.it Thu Jul 25 06:07:57 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 10:07:57 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: <16Q%8.116512$Jj7.2728704@news1.tin.it> Jonathan Hogg wrote: ... > Another thread here discussed wrapping a function to provide 'before' and > 'after' hooks. This is exactly the situation where I would use a __call__ > interface. Consider: In that thread I showed how a closure provides a much simpler way to perform the task as specified. You seem to be arguing that __call__ is good because it makes it easy and natural to slide into "mission creep", building components that are more complicated than needed, in order to support extra features outside of the specifications. If you think that supplying unrequested infrastructure is good, then it's quite consistent that you like __call__. I prefer simplicity. "Do the simplest thing that can possibly work". As you're showing, __call__ encourages tossing simplicity away. It's peculiar that Python as it stands feels pretty good to people with such totally divergent underlying philosophies of what software development is all about. I guess, in a way, that's a tribute to Python's pragmaticity. Warts such as N divergent ways to perform a task (lambda, instance with __call__, closure, etc) will no doubt remain due to both backwards compatibility constraints AND the different constituencies pulling in opposite directions, helping GvR to keep making his own decisions free from unbalanced "popular opinion" push in one direction or another. Good thing, too:-). Alex From max at alcyone.com Fri Jul 12 04:16:18 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Jul 2002 01:16:18 -0700 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <3D2E9052.2A8B60A6@alcyone.com> Peter Hansen wrote: > It's obviously a religious issue, but I get the feeling that while > some buy into the XML hype wholesale, and overuse it to their > detriment, others are now jumping on some anti-XML bandwagon > (possibly) without having really put it to the test. I often find > that a choice to use XML opens up interesting avenues which would not > even have occurred to me had I started off with another format, > and so far I'm not sure I regret any particular case where I've > used it. It's one of those things that has been elevated to the status of buzzword, regardless of its actual benefits and disadvantages. That means that some people will think it is the One True Way and will use it for absolutely every hole they can possibly cram the peg into (whether it's appropriate for it or not), and on the same side some antizealots who see some problems with it will exaggerate and insist that it's an awful tool (often indicated by "X sucks" and "X is evil" without further explication) and berate anyone who uses it. XML has its uses, and for those uses it is very well suited, but like any new idea there are those who will use it just for the sake of using it, totally disregarding whether it's well-suited to the task. It's an unfortunate fact of life, regrettably. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From robin.siebler at corp.palm.com Fri Jul 12 13:19:45 2002 From: robin.siebler at corp.palm.com (Robin Siebler) Date: 12 Jul 2002 10:19:45 -0700 Subject: Module for arj files Message-ID: <886c5e4b.0207120919.1d24749@posting.google.com> Before I try to write one myself, does anyone know if there is a module anywhere for dealing with .arj compressed files? From hgg9140 at seanet.com Thu Jul 11 20:01:45 2002 From: hgg9140 at seanet.com (Harry George) Date: 11 Jul 2002 17:01:45 -0700 Subject: Python to XML to Python conversion References: Message-ID: markvkane at hotmail.com (Mark) writes: > Hello, > > Recently my employer has asked me to do some computer work though I'm > just savvy enough to write minor programs of little significance. My > job is to write a program that will be generic enough to take any form > of Python dictionary and be able to convert it to XML and back. > Ladies and gentlemen I am completely at a loss, I'm not a good > programmer. If anyone one has any good, simple and complicated > examples, or tips I would be eternally greatful if you'd share them > with me. I have searched desperately through every posting I could > find on the subject, but to no avail. Please Help! > > Regards,______ > ______ | > Markus|_______| > ______| Get Gnosis Utils: http://gnosis.cx/download/ See gnosis/xml/pickle. That may do the job for you. -- Harry George hgg9140 at seanet.com From rs at onsitetech.com Tue Jul 9 17:23:37 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 21:23:37 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> <3D2B19CE.5040409@onsitetech.com> Message-ID: <3D2B540B.4030205@onsitetech.com> Alex Martelli wrote: >... And the reason you don't have to state that, is that it makes absolutely > no difference whatsoever -- you can try to get any attribute (methods > included) from any object, it either succeeds or fails (and that only > partly depends on the object's class). Well, I'd say that an object understanding the message I send to it, or being the type of object I think it is - success or failure - surely is a big difference! Sort of the name of the whole game... From tim at vegeta.ath.cx Sat Jul 27 21:50:42 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: 27 Jul 2002 18:50:42 -0700 Subject: redirect to > and to console ? References: Message-ID: Steve Holden graced us by uttering: > "Tim Hammerquist" wrote in message [ snip ] >> One thing that concerns me is how well do the COMMAND.COM/CMD.EXE >> shells handle redirection? I know that DOS used to support the >> standard '>' redirection, but I don't remember any robust way of >> handling stderr on the command line. >> >> Various *nix (and cygwin, yes) shells can use: >> >> $ command > file_out 2> file_err >> >> $ command > file_both 2>&1 >> >> $ command &> file_both >> >> ...and I think I heard CMD.EXE had slightly better support, but how >> does Win32's native command line stream redirection really compare? > > While I can't be definitive about htis (maybe Mark Hammond *could*), > one thing it's always worth remebering is that certain Windoze command > interpreters will fail to handle > > prog.py > output.txt > > when they *will* cirrectly handle > > python prog.py > output.txt > > I seem to remember this particular form of brain-death belongs to > Windows NT 4.0 (why was there never an NT 4.anything else, I wonder), > since "lesser" operating systems didn't even have the ability to > associate the ".py" extension with the Ptyhon interpreter. Yes, I also remember a similar problem with the .BAT file wrappers for scripts not handling stream redirection properly... that would be the solution for the Win95/98 systems what don't associate extensions with programs on the commandline. 'ly yrs, Tim Hammerquist -- Anyone who thinks that the act of programming is worth less than $50/hr should leave the industry. -- Randal L. Schwartz (clpm, 27 Jul 2000) From aleax at aleax.it Fri Jul 26 07:33:02 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 11:33:02 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: Michael Hudson wrote: ... >> Bingo. I had much the same approach for the first 20 years >> or so of my programming career, > > Then I'm ahead of you by ... erm ... 13 years. Wow, I've been > programming (admittedly only as a hobbyist) for nearly a third of my > life. That's scary somehow. Yes, the thought of a 99+ yo person who's been programming for almost 33+ years is indeed pretty scary. OTOH, if you were _behind_ me by 13 years, rather than ahead, then programming for 7 years out of 21 wouldn't be (scary). (BTW, I've been programming for over _25_ years now -- more than half of my life...). Alex From pinard at iro.umontreal.ca Sat Jul 6 19:25:47 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 06 Jul 2002 19:25:47 -0400 Subject: Given PID, make sure a process is running on Unix? In-Reply-To: <3D2761CD.1090503@lindbergs.org> References: <3D2761CD.1090503@lindbergs.org> Message-ID: [VanL] > I am trying to get write a python script that on Unix reads a PID from > a file and, if that process is still running, exits. If the process is > not running, the process would be started. [...] Any help? You could work along the lines of: try: os.kill(PID, 0) except OSError: print PID, 'is not running' else: print PID, 'is running' Killing a process with signal 0 never kills it. :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From hikage at parkour-belgique.com Tue Jul 30 00:03:06 2002 From: hikage at parkour-belgique.com (Hikage) Date: Tue, 30 Jul 2002 06:03:06 +0200 Subject: Python & X-Chat Message-ID: <3d4610d1$0$289$ba620e4c@news.skynet.be> Hello, I seach people who had make script for x-char or had doc about this.. I've found nothing ... HELP HELP ;) Thanks to the people who can help me :) From vovka_foreverREMOVE_THIS at hotmail.com Mon Jul 29 10:46:17 2002 From: vovka_foreverREMOVE_THIS at hotmail.com (Vladimir Cherepanov) Date: Mon, 29 Jul 2002 18:46:17 +0400 Subject: Newbie question about dictionaries References: Message-ID: Thanks for the quick answer! Is it right then that I have to implement a custom class for key objects if I want to use a custom hash function? "Gerhard Haering" wrote in message news:slrnakajpi.t8.gerhard.haering at lilith.my-fqdn.de... > In article , Vladimir Cherepanov wrote: > > I've read that dictionaries are implemented as hash tables. Is there any way > > to specify a hash function? > > Sure there is. You need to implement a __hash__ method. It's described here: > http://www.python.org/doc/current/ref/customization.html > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 > public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From huaiyu at gauss.almadan.ibm.com Thu Jul 11 13:29:46 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 11 Jul 2002 17:29:46 +0000 (UTC) Subject: A better self References: Message-ID: Gabe Newcomb wrote: >It seems to me that, given that most folks here agree the concept of >'self' is useful, we may as well stick with the word 'self' as is. It's >the explicit version--it makes things clear, and if anyone's really >dying to use the shortest identifiers possible, they might consider >Perl. > >Yes that last statement was partially tongue-in-cheek, but seriously, >readability is worth preserving IMO. Using self is indeed the most readable most of the time. However, there are situations, mostly in numerical computations, where it is necessary to have, say, a dozen variables in one expression, and a dozen statements containing such expressions and some other statements in one method. It is far more readable to have them all appear in one screen in a form that resembles written equations on paper, than to dogmatically follow a convention in a particular programming language. For anyone spending a few weaks sorting out these equations and several days making sure that they are correctly represented in the program, it is no big deal to notice that _ is used in place of self in this situation. Just like the shortest programs are not always the most readable programs, programs that follow a particular style convention (like using self) are not always the most readable programs. What is required is a convention that allows shorter notions when necessary in a disciplined way. I find that switching from self to _ is quite satisfactory for this purpose under the right circumstances. And, as such, there is no need to extend Python's syntax for this purpose, which was the initial topic of this thread. Huaiyu > >-----Original Message----- >From: Huaiyu Zhu [mailto:huaiyu at gauss.almadan.ibm.com] >Sent: Wednesday, July 10, 2002 10:01 AM >To: python-list at python.org >Subject: Re: A better self > > >Sean 'Shaleh' Perry wrote: >>> >>> Before you all react (programmers can be SO conservative), please >think >>> about it! >>> >> >>I have played with ideas like this in python and other languages, and >witnessed >>others do the same. >> >>.foo is REALLY hard to see if the font is not just right. >> >>.size = .r + .l >> >>is even worse. >> >>I am not 100% against the idea as an idea, but the actual usage is not >all that >>fun. > >A better (and currently available) convention is > >_.size = _.r + _.l > >It has been mentioned several times in this thread. I've used it >several >times in the past and liked it, esp in iterative algorithms. Some usage >patterns include > > def __init__(_, x, y, z): > _.x, _.y, _.z = x, y, z > > def process(_, x, y, z): > actions involving _.x, _.y, _.z, x, y, z > _.x, _.y, _.z = x, y, z > > def update(_): > x, y, z = _.x, _.y, _.z > actions involving x, y, z > _.x, _.y, _.z = x, y, z > >One could even think of _. as a magic persistence prefix that makes the >variable keep its value between method calls. It is also easy to >replace >_.x with self.x or vice versa in a good editor. > >Huaiyu >-- >http://mail.python.org/mailman/listinfo/python-list > > From ianb at colorstudy.com Fri Jul 12 15:16:09 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2002 14:16:09 -0500 Subject: Python for data driven website? In-Reply-To: References: <3D2E51A0.730F521A@engcorp.com> <3D2E946D.2838329C@engcorp.com> Message-ID: <1026501369.781.78.camel@lothlorien.colorstudy.net> On Fri, 2002-07-12 at 04:56, Alex Martelli wrote: > > No project like this should be worked on for three man-years > > before its first release, at least not in this day and age! > > Yep, but getting customers interested enough to be willing > to invest manpower is not a trivial problem. Getting customers > directly involved is the #1 advantage of Agile approaches and > also the hardest one to make into reality. Yes -- if you are making a tax application, it probably isn't the first time you've worked in that domain -- someone has connections to some preparers (or whoever your potential audience is). Finding just one or two sympathetic customers, and working with them early on, will make your application much more useful. You'll be able to develop a much better user interface if you have feedback, and the features will be targeted at real users and their real needs, not on your speculation of what they need. Ian From max at alcyone.com Wed Jul 10 03:30:38 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Jul 2002 00:30:38 -0700 Subject: Z-machine/Infocom interpreter in Python? Message-ID: <3D2BE29E.4C49B91C@alcyone.com> Anyone know of a Python library for interpreting Infocom Z-machine games, up to at least z5 (or whichever the version is _before_ the one that had support for graphics and sound, I have no need for that)? I'm looking for something that can be hooked into chat systems so that people can send it messages (as commands) and get back the results. I can't recall whether the status line in Z needs to be treated specially or not. Some Web searches came up with PUB, http://py-universe.sourceforge.net/ which is an authoring system and not an interpreter, and viola, http://sourceforge.net/projects/viola/ which as far as I can tell is a dead project which never made any releases [grumbles about the use of the present tense to describe projects which are not yet created]. Worst case, of course, this is possible with third party tools and pipes, but I'd rather have something fairly atomic so it can be manipulated asynchronously, and hopefully concurrently (i.e., multiple people playing multiple games at the same time). Any pointers? Thanks. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From otis_usenet at yahoo.com Thu Jul 18 22:55:38 2002 From: otis_usenet at yahoo.com (OtisUsenet) Date: 18 Jul 2002 19:55:38 -0700 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> <3D37429C.53BC0FDB@engcorp.com> Message-ID: <5606b639.0207181855.48496f5a@posting.google.com> Peter Hansen wrote in message news:<3D37429C.53BC0FDB at engcorp.com>... > OtisUsenet wrote: > > > > Python newbie question. How does one do something like this in > > Python: > > > > # assign the value of j to i and then increment j by 1 > > i = j++ > > > > I checked the FAQ at http://www.python.org/doc/FAQ.html, but this > > simple question wasn't covered :) I can't find it in 2 Python books > > either. > > Is there anything you don't like about doing it exactly as your comment > reads? Yes, actually :) I don't like the fact that if 'j' is some kind of a global counter variable, and I'm dealing with multiple threads, it is then, I believe, possible for 2 or more threads to execute i = j at the same time (i.e. before 'j' had the chance to increase). One can probably work around this.... ...although, now that I think about it, even i = j++ wouldn't be thread-safe completely, as on the machine code level this still gets executed in multiple steps.....I think. :) > >>> i = j > >>> j = j + 1 > > On newer Pythons, you can replace the second line with j += 1 if you wish. Thanks, Otis From cliechti at gmx.net Wed Jul 31 14:37:46 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 20:37:46 +0200 Subject: Use python without install it. References: Message-ID: "Bertrand Geston" wrote in news:ai917o$12j0d8$1 at ID-135695.news.dfncis.de: > Does somebody know if it is possible to use python on a computer under > Linux on that it's not allowed to install it for security reasons > (server in production) ? > The purpose is to have some shell scripts written in Python to make > some maintenance tasks. Those scripts are launched manually. McMillan's Installer http://www.mcmillan-inc.com/install1.html has linux support. Freeze should work too, but i think that's not that easy to use. > Run it from a CD rom ? How ? i have never tried that, but once you have an executable it should be possible. > Special user ? is it really secure ? it is as secure as any other executable. as python has advanced error handling, it's in fact more secure than say an average C program (less risk for a core dump etc.) > Other idea ? try to convince the admin of that machine. python is _very_ stable. your scripts will be better maintainable in python as well as faster developed. that should be enough resons to install it and save money ;-) chris -- Chris From heikowu at ceosg.de Fri Jul 19 14:40:29 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 19 Jul 2002 20:40:29 +0200 Subject: Funny behaviour of MySQLdb Message-ID: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> Hi List! I'm currently writing a little XML-RPC server in Python, which is used to power a database driven Web-Application. So far, so good... :) ? have a little problem with the newest MySQLdb, though. As the server is multithreaded (and the MySQLdb module isn't), I've followed their advice, creating a connection pool of database connections on startup, which are then distributed thread-safe (yeah, I'm sure it's threadsafe! :)) to the handlers when the XML-RPC server class fires them. So far, this works. When in the handler though, a funny thing happens: I try to lock tables for correct access of multiple handler instances working parallel, but the execution of "LOCK TABLES" just hangs. I'm sure that is the first place I'm executing a table lock, and that no other thread working on the database is running, but still locking hangs. If I start a mysql commandline session, and try to lock from there, locking also blocks, so a lock is acquired somewhere/somehow... Debugging is difficult, as multithreading isn't quite supported by pdb, is it? ;) Has anybody had this problem before? If not, maybe it's a bug in MySQLdb or in MySQL itself... Code that is executed (slightly simplified): Server class: # Acquire a mutex on the database mutex, and after that, enter a # critical section. self._dbmutex.acquire() self._mutex.acquire() # Retrieve a connection ID from the list and initialize the database # array. id = self._availdatabases.pop(0) dbs = {} # Retrieve the connections. for db in self._databases: # Enter database into array. dbs[db] = self._databases[db][id] # Release critical section. self._mutex.release() Handler class: # Get database. self._db = dbs["user_db"] # Create global binding. self._dbpsql = pSQL.pSQL(self._db,"User") # Lock tables. if not locks_set: print "Locking in _CheckLoginID" self._dbpsql.sql_query("LOCK TABLES logins READ, users READ, groups\ READ") print "Locking succeeded" "Locking in _CheckLoginID" gets printed, but then the process locks on the next statement. pSQL is a module that facilitates database access, but all it actually does is work on an global cursor (which is created when pSQL is bound), and sql_query executes the query you pass in on that cursor... Any help is appreciated! :) Yours, Heiko W. From bokr at oz.net Tue Jul 2 14:07:51 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Jul 2002 18:07:51 GMT Subject: Performance question about math operations References: Message-ID: On Mon, 1 Jul 2002 23:00:30 -0700 (PDT), "Andrew P. Lentvorski" wrote: >I have a VLSI layout editor written in Python. At its core, it has to >redraw a lot of polygons. This requires a lot of coordinate conversion >mathematics. Essentially the following loop: > >#! /usr/bin/env python > >def main(): > i = 0 > > while i < 1000000: > i = i + 1 > > (1-678)*3.589 > -((1-456)*3.589) > >if __name__=="__main__": > main() > Note that there is no constant expression folding in Python, so you are actually doing all the operations you are specifying. And there is no automatic hoisting of constant stuff out of the loop, so pre-compute and store constants outside the loop where you can. It's hard to say without actual code. There is a trick you could use to fold constant expressions, e.g., Say you wanted to translate a list of coordinates: >>> coordlist = [(1,2),(3,4),(5,6)] Say you _know_ these are constant for a particular translation >>> k1=5; k2=10 Then >>> exec 'newlist = [(x+%s,y+%s) for x,y in coordlist]' % (k1*20+10,k2*10) >>> newlist [(111, 102), (113, 104), (115, 106)] The trick was that what got compiled and executed was first evaluated as >>> 'newlist = [(x+%s,y+%s) for x,y in coordlist]' % (k1*20+10,k2*10) which produced the code 'newlist = [(x+110,y+100) for x,y in coordlist]' which has simple constants instead of expressions and lookups during the list comprehension. This would only be worth while on really long lists of coordinates, depending on how complex your constant expressions are. I'm sure you can see how to generalize the above to (x*%s+%s, y*%s+%s) with appropriate expressions for the four constant values to get any desired rotation/scaling/translation. However, you may want to consider what the array module might do for you (maybe in combination with the above trick), or you could look for some graphics software that may match what you're doing. >Now, I understand that looping in Python has overhead. It turns out that >the loop without the math operations takes about .5 seconds. Fine. >However, each line of math operations adds .75 seconds to the total loop >time for a total run time of about 2 seconds. This is with -O enabled >(even though it doesn't seem to have any effect). > >This same loop in C++ (with classes, indirection, copy contruction, etc) >takes about .05 seconds. > >That's about a factor of 30 (1.5 / .05) difference even if I cancel out >the loop overhead. I could handle factor of 2 or 4, but 30 seems a bit >high. > >What is eating all that time? And can I do anything about it? > Again, hard to say without actual code ;-) Regards, Bengt Richter From hancock at anansispaceworks.com Tue Jul 2 06:46:49 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 02 Jul 2002 03:46:49 -0700 Subject: curses-based menu module? Message-ID: <3D218499.38153895@anansispaceworks.com> Hi all, I'm converting a tcsh/csh management script at work over to Python. It has a lot of CLI-based menus (you know, the old, really dumb kind), and I was thinking about replacing these with curses-based menus. Curses itself seems really easy to use, but is kind of a low-level interface. Clearly, I will be well-served to make a higher-level interface for creating and using menus. But I have a couple of questions: #1: Am I reinventing the wheel? Is there already a high-level interface available (this seems rather likely, though I haven't found one). #2: If not -- does anyone want to discuss a good API for such a thing? It'd be really handy for installation and maintenance scripts (such as the one I'm writing). Right now, I'm thinking of emulating the sort of things you can easily do with HTML form widgets, just off the top of my head: "select" -- select one of several fixed options, immediately return selection to the caller. "radio" -- like select, but with an '*' or 'X' cursor that you move with the arrow keys -- the selection is registered by an "enter" or some similar keystroke. "checkbox" multiple-selections, like radio otherwise (and I'm sure there's more possibilities) The menu would be a class (instance) with __init__ taking a sequence of options, and some optional keywords to control behavior. The options would be tuples with menu-option-text, short-cut key, and an optional call-back function (if not given, the option just sets the selection). There should also be some codes for options which ought to be confirmed ("You have selected 'reformatting your hard drive' are you really sure you want to do that?"), etc. The menu object would be callable, displaying a curses menu to the user when called, and returning the selection as a result (callbacks would be called from within the menu call function). Anyway, that's the idea -- I don't want to go into any more detail until I know that this doesn't already exist. But I'm willing to discuss it and come up with a real API which I could then implement, and make generally available. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From huaiyu at gauss.almadan.ibm.com Mon Jul 29 15:53:07 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 29 Jul 2002 19:53:07 +0000 (UTC) Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: Fredrik Lundh wrote: >to fix the other "mistake", some needs to come up with a >really great syntax (and get michael hudson to implement >it for them ;-). ideas are welcome. No great syntax here, but some ideas on why it is difficult syntax-wise (in the hope that someone can overcome them). Python uses indentation to denote lexical scope at or above the statement level, while using parenthesis at the expression level. It is rather easy to embed parenthesis inside indentation, but the other way is difficult. So to allow statements in lambdas, it is either necessary to delimit statements with some begin/end marker in lieu of indentation, or to come up with a way to embed indentation scoping inside parenthesis scoping. Another possibility is to allow only those statements that do not have further scopes. For example, print and assert would be allowed but if/then/else would not. Huaiyu From thefleau at softhome.net Sat Jul 13 15:08:41 2002 From: thefleau at softhome.net (Colin Barschel) Date: Sat, 13 Jul 2002 21:08:41 +0200 Subject: Convert to Python and compile to executable References: <3D307578.9080307@softhome.net> Message-ID: <3D307AB9.9070707@softhome.net> I kind of answered the question myself with the (very good) faq at python.org where the solution would be with the freeze option. I guess I have to try it myself to see how it works. I still want to ask: does id work good? Is it a viable solution to distribute a program or is it better to go java or c++ from the beginning? Thanks Ciao Colin From peter at engcorp.com Thu Jul 11 23:31:07 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Jul 2002 23:31:07 -0400 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) References: <33803989.0207110328.5ef01f1e@posting.google.com> <7934d084.0207111530.130b00b6@posting.google.com> Message-ID: <3D2E4D7B.CFB9FCD4@engcorp.com> jepler at unpythonic.net wrote: > > On Thu, Jul 11, 2002 at 04:30:59PM -0700, Andrae Muys wrote: > > Well seeing as we are discussing Python Zen, the one I don't currently > > understand is "Flat is better than Nested". I had always thought the > > Nested is > A > B > C > D > > flat is > A > B > C > D > > Python has lots of namespaces, but they're relatively flat. Usually, > module->class->function or module->function, but with nested_scopes > sometimes an additional level of function is seen. > > That's my take on it ... If that's true (and it sounds good to me) then one might interpret the advice as "don't nest for the sake of nesting; nest only to manage complexity". It is not necessary to nest to manage three items. It might be necessary to nest a little more to manage twenty or thirty. Several hundred or thousand need a little more (i.e. the standard library, which does have a few levels of nesting, such as package xml). ? -Peter From gerhard.haering at gmx.de Tue Jul 30 15:02:22 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 30 Jul 2002 21:02:22 +0200 Subject: wxTextCtrl + wxGrid In-Reply-To: References: Message-ID: <20020730190221.GA1062@lilith.example.com> * Thorsten Gawantka [2002-07-30 11:16 +0200]: > Hi Group, > how can I get the Value of wxTextCtrl into a Cell of wxGrid? > my actual code is > > -- > ## Copy the textCtrl.Value into gridCell > self.grid.SetCellValue(i, 0, self.edit_p1.GetValue) > ## > -- > > this is not functional, because the python interpreter > want to have a string. > How can I get this solved? By calling the GetValue method :-) "self.edit_p1.GetValue" actually gets a reference to the GetValue method, but doesn't call it. if you actually call the method with .GetValue() you will get a string instead of the method reference you get right now. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From emile at fenx.com Mon Jul 1 10:53:36 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 01 Jul 2002 14:53:36 GMT Subject: communicate with serial port (ttyS0) References: Message-ID: "Shaun Schulze" wrote in message news:mailman.1025531703.8944.python-list at python.org... > Hi > > I am running Debian/Linux kernel 2.4.17. > I need to communicate between custom hardware and my > python script via a serial port, eg. ttyS0, at > 115.2kb/s. > I would like to know how to receive and send data to > and from the serial port. I would also like to know > how to set the baud rate of the serial port to > 115,2kb/s. If anyone has some examples it will also be > much appreciated. > You'll find some pointers in the FAQ at: http://www.python.org/cgi-bin/faqw.py?query=serial+port&querytype=simple &casefold=yes&req=search Check as well on google -- ISTM there are now some additional options, although the date on the faq entry is current... -- Emile van Sebille emile at fenx.com --------- From newfroups at jerf.org Fri Jul 12 10:52:32 2002 From: newfroups at jerf.org (Jeremy Bowers) Date: Fri, 12 Jul 2002 14:52:32 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <3D2EBE2F.6000506@jerf.org> Peter Hansen wrote: > It's obviously a religious issue, but I get the feeling that while > some buy into the XML hype wholesale, and overuse it to their > detriment, others are now jumping on some anti-XML bandwagon > (possibly) without having really put it to the test. I'm not anti-XML. But I will say XML is only appropriate in rather narrow circumstances as I outlined. As it so happens, these narrow circumstances are rather popular, so XML is frequently appropriate. But you should still use XML only when there are no better choices, *because* you need trasferability, extensibility, or human readibility, and nothing else really meets those needs, *not* because it's the first thing that leaps to mind. For instance, Pickle is quite challenging to match in XML, if you don't have the XML marshaler at hand, for a novice. Please don't read anti-XML sentiments into my message. ;-) I said what I meant and I means what I say. It's not a sweeping condemnation, it's a rather limited observation. From rs at onsitetech.com Mon Jul 8 15:24:41 2002 From: rs at onsitetech.com (Robb Shecter) Date: 08 Jul 2002 19:24:41 GMT Subject: Why self? References: <3D29DD1A.6040209@onsitetech.com> <080720021459493536%pecora@anvil.nrl.navy.mil> Message-ID: <3D29E6AE.5040801@onsitetech.com> Lou Pecora wrote: > In article <3D29DD1A.6040209 at onsitetech.com>, Robb Shecter > wrote: > > >>>> self.__velocity = self.__factor1 * self.__factor2 >>> > > You don't need the double underscores. I feel like I need them because: 1. AFAIK, without them, subclasses can inadvertently cause problems. 2. I'm used to the OO/encapsulation idea of private scope being the default. 3. It seems Pythonic: These variables aren't part of the public API, and so the underscores give clues to some Python tools. 4. It seems Pythonic: The 'property' feature would be confusing if both the new property, plus the internal representation were seen as being public API. Robb From tjreedy at udel.edu Tue Jul 9 18:06:48 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Jul 2002 22:06:48 GMT Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207091153.7b2484be@posting.google.com> Message-ID: "curt finch" wrote in message news:96c7f32.0207091153.7b2484be at posting.google.com... > Product is free at http://www.journyx.com/products/timesheet/ For up to 10 users, which covers me and, I suspect, most readers here. Having tried online demo, I may download and give this a try for personal use. > Our rebuttal (based on some of your comments) is here: > > http://www.journyx.com/pdf/PythonAtAGlance.pdf This is a nice, professional-looking promotional piece for Python. If you plan to keep it there, perhaps you could submit link to webmaster at Python.org. It might be useful to people trying to introduce Python in workplace and needing non-programmer manager approval. Terry J. Reedy PS. The notion that competitor would try to attack product by attacking invisible-to-user implementation language strikes me as bizarre. Reeks of desperation. From skip at pobox.com Sat Jul 6 12:58:40 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 6 Jul 2002 11:58:40 -0500 Subject: Syntax Error at end of file In-Reply-To: <3D24EE21.1090500@something.invalid> References: <3D22E6FE.9070705@thomas-guettler.de> <3D24EE21.1090500@something.invalid> Message-ID: <15655.8640.945433.597107@localhost.localdomain> Skip> In a similar thread which occurred just a few days ago it was Skip> observed (by Tim Peters, I think) that the set of acceptable Skip> characters at any particular point in the parse is big, so Skip> enumerating them in the error message would be counterproductive Skip> and would just serve to confuse the issue in most cases. Greg> But in the case of an unclosed triple quote, the scanner surely Greg> knows (or could remember) where the beginning of it was! True enough. I was responding to what I thought was a general request. I patched the scanner to distinguish EOF during triple-quoted string scanning and EOL during single-quoted string scanning. I'll apply them to the CVS source when I have a better Internet connection. Skip From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 15:36:51 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 12:36:51 -0700 Subject: HTML DOM parser? Message-ID: <7xwursj0a4.fsf@ruckus.brouhaha.com> Anyone know of a Python-callable HTML DOM parser? I mean a serious one that tries to understand the crappy malformed out there in the real-world Web, the way a browser does. If it can interpret Javascript that's even better. This is for a consulting client, so a commercial library would be acceptable (though not preferred). Thanks. From steven_shaw at iprimus.com.au Wed Jul 3 07:04:13 2002 From: steven_shaw at iprimus.com.au (Steven Shaw) Date: Wed, 3 Jul 2002 21:04:13 +1000 Subject: is attribute access a hash-lookup by name? References: <66715c02.0207021737.b488f07@posting.google.com> <3D228348.1070201@something.invalid> Message-ID: <3d22dab0_1@news.iprimus.com.au> Thanks, I'd forgotten about tuples. From shagshag13 at yahoo.fr Mon Jul 29 07:06:30 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 29 Jul 2002 13:06:30 +0200 Subject: Size in byte of a string ? References: Message-ID: [sorry for the previous incomplete post] hello, i had the following problem : i had huge files > 1,5 go. each of theses files contain some other small files and they are separate by a header. i need to do some kind of random access to the small files so i wish to write a script which would build some kind of a table of content for theses huges files. i would like to have something like samllfile_header_name_i : start_at_byte : end_at_byte and i will do : f.seek(start_at_byte) samllfile_header_name_content = f.read(end_at_byte) but to do this i need to be able at the building time to know how much bytes take a string ? (i think there is something with the size in byte of CR/LF but how to measure it ? i hope i won't have to would prefer to do some start_at_line, end_at_line as it will need to always read file from start...). From zopestoller at thomas-guettler.de Tue Jul 9 09:27:53 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 09 Jul 2002 15:27:53 +0200 Subject: Table Widget (without Installation) References: <3D2A9948.5090304@thomas-guettler.de> Message-ID: <3D2AE4D9.3060104@thomas-guettler.de> Gerhard H?ring wrote: > * Thomas Guettler [2002-07-09 10:05 +0200]: > >>Hi! >> >>I am searching for a table widget to >>use with python. Is it still true that >>tkinter has none? >> >>I need it for an application on win32 >>which should not be installed. All >>libraries will be in one directory. >> >>pyFox, pygtk, wxpython are options. >> > > The wxPython grid and list controls are excellent. I'd recommend you > download wxPython and click thru all the examples in the demo > application. This will show you what is possible and how to do it. wxPython is very nice on win32. I tried once to build the latest version for linux, but failed. Thank you thomas From mcherm at destiny.com Thu Jul 25 14:23:06 2002 From: mcherm at destiny.com (Michael Chermside) Date: Thu, 25 Jul 2002 14:23:06 -0400 Subject: if(debug), optimized away? Message-ID: <3D40420A.5090307@destiny.com> > I would like to use something like this when running in > debug mode: > > if(debug): > if(items > 9): > print "fatal error..." > do_some_check_foo(42) > ... > > > If I set debug=0, is this code optimized away as in most > C/C++?? compilers? > > The reason for asking is that I would like to have A LOT of > debugging code and would like to avoid the performance penalty > when not runing in debug mode. > > Are there other, perhaps more Pythonish, ways of doing the same > thing? No, it is not optimized away. I would recomend the following as being pythonic, but others might not agree, so get other opinions: # WARNING: Untested Code def itemsAreLT9AndValid(items): if items > 9: print "fatal error..." do_some_check_foo(42) ... LATER ON, in your code ... ... code here ... assert itemsAreLT9AndValid() ... more code here ... This way, you've put all of your code into an assert statement. Of course, (in my experience) 90% of all the debug code can be expressed as a single boolean expression, so 90% of the time you won't need the helper function, and you can just write something like this: assert items > 9 but there are a few cases (like running multiple things or testing with a loop) which are difficult or impossible to express without creating the extra function to wrap it. You'll probably want to enclose the definitions of ALL of the test functions inside an "if debug:" (one which executes just once), so that you don't even create the functions unless you need them. For instance, the following: ... code here ... def itemsAreLT9AndValid(items): if items > 9: print "fatal error..." do_some_check_foo(42) assert itemsAreLT9AndValid() ... more code here ... would be a bad idea for performance reasons (we may not CALL the function if debug is off, but we CREATE it each time. -- Michael Chermside From emile at fcfw.fenx.com Mon Jul 22 15:14:47 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: 22 Jul 2002 14:14:47 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 22) Message-ID: <5F52794632B37950.FEF14A887AEAE6A3.0F07FC50FF601135@lp.airnews.net> QOTW (QOTM?): "It's easier to write appropriate code from scratch in Python than to figure out how to *use* a package profligate enough to contain canned solutions for all common and reasonable use cases." timbot "I've learned from being in this business at least as long as many of you have, that when a project appears designed to fail, it probably was." Scott M. Fulton, III "I did something in java and php (finish and working) and now I rewrite it in python. Ask me if you want to know more about it, it's in early stage, but very promising when I compare it to what I did in java." -- William Dod? on comp.lang.py There are several alternatives for binding SNMP and python http://groups.google.com/groups?threadm=3d329ac0.330042218 at news.skynet.be Juliano Freitas wants a horizontal line to separate the frames in a tkinter application http://groups.google.com/groups?threadm=mailman.1026764423.13659.python-list at python.org Steven Knight announces the release of SCons.0.8, a software construction tool (build tool, or make tool) written in Python. http://groups.google.com/groups?selm=mailman.1026770363.9080.python-list at python.org With testing, John Hunter discovers that most of the total execution time of his code is spent clearing a map from memory, after all the lines of the script have executed... http://groups.google.com/groups?selm=m28z4bn227.fsf at mother.paradise.lost ...and Tim Peters provides the solution with pymalloc. http://groups.google.com/groups?selm=mailman.1026854126.29165.python-list at python.org David Mertz announces Gnosis (XML) Utils 1.0.3, a utility set that contains a number of Python libraries, most related to working with XML. http://groups.google.com/groups?selm=mailman.1027012380.3786.python-list at python.org Paul Rubin gets suggestions for "...a Python-callable HTML DOM parser? I mean a serious one that tries to understand the crappy malformed out there in the real-world Web, the way a browser does." http://groups.google.com/groups?threadm=7xwursj0a4.fsf at ruckus.brouhaha.com Kevin Altis release PythonCard 0.6.8, a GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux. http://groups.google.com/groups?selm=7cmZ8.447$KY5.70441 at news.uswest.net Sarayu Balu is looking for python for the Sharp Zaurus. http://groups.google.com/groups?threadm=1026919964.826307 at irys.nyx.net Mike C. Fletcher releases SimpleParse 2.0.0a4, a BSD-licensed Python package providing a simple parser generator for use with the mxTextTools text-tagging engine. http://groups.google.com/groups?selm=mailman.1027016222.3970.python-list at python.org Dinu Gherman announces Pycotin 0.1 (Python Cocoa Test Interface). Pycotin is a Cocoa GUI to Steve Purcell's PyUnit test framework on Mac OS X. http://groups.google.com/groups?selm=20020719131144181%2B0200 at news.t-online.de David LeBlanc tells that "Mastering Regular Expressions 2nd Ed." claims extensive Python re coverage. http://groups.google.com/groups?selm=mailman.1027121729.1720.python-list at python.org Paul finds out about changing maximum recursion depth and alternatives. http://groups.google.com/groups?threadm=ZCq_8.8646$_C2.688083 at newsread2.prod.itd.earthlink.net Jeff Epler shows a way to create unsafe_for_unpickling pickles in older versions of python. http://groups.google.com/groups?selm=mailman.1026910105.2112.python-list at python.org Syver Enstad asks about tutorials and how to get started with i18n. http://groups.google.com/groups?threadm=uy9cbtt05.fsf at online.no Trent Mick responds to questions about getting SOAP working with Activestate Python, ZSI 1.1 and PyXML 0.7. http://groups.google.com/groups?selm=mailman.1026852026.32019.python-list at python.org John Hunter posts an example of using pygoogle to query google directly from python code. http://groups.google.com/groups?selm=m2bs96icbv.fsf at mother.paradise.lost Sam Penrose finds a performance boost for pickle performance on larger objects. http://groups.google.com/groups?threadm=mailman.1026940226.16076.python-list at python.org Fredrik Lundh provides a snippet showing the use of the standard module pulldom in xml.dom to create something similar to XML::Twig. http://groups.google.com/groups?selm=QfQZ8.16550$p56.5392725 at newsb.telia.net Anthony Tuininga releases cx_Oracle, a Python extension module that allows access to Oracle and largely conforms to Python db API 2.0. http://groups.google.com/groups?selm=mailman.1026937026.31731.clpa-moderators at python.org Martin Gebert has written a python code beautifier and a small KDE frontend for source-highlighting. http://groups.google.com/groups?selm=mailman.1026937031.32146.clpa-moderators at python.org Erik Max Francis releases CAGE 1.1 -- Cellular automata engine in Python. CAGE is a fairy generic and complete cellular automaton simulation engine in Python. http://groups.google.com/groups?selm=3D3B94B1.F12E4A9C at alcyone.com ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From eric.brunel at pragmadev.com Thu Jul 4 08:44:28 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 4 Jul 2002 12:44:28 +0000 Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: Achim Domma wrote: > not tested, but something like this should work: > > // can this be done with lambda ??? > def myComp(a,b): return cmp(a[1],b[1]) > tmpList = yourDict.items() > tmpList.sort(myComp) > > for name,count in tmpList: print name,count Here is an almost one-liner version: l = [(i[1], i[0]) for i in yourDict.items()] l.sort() or: l = zip(yourDict.values(), yourDict.keys()) l.sort() I don't which one of these two or Achim's one is the most efficient. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From henrik.motakef at web.de Fri Jul 19 04:32:39 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 19 Jul 2002 10:32:39 +0200 Subject: XML::Twig-like module wanted Message-ID: <87k7ns9kyg.fsf@pokey.henrik-motakef.de> Hi, Does anybody know about something similar to XML::Twig (see ) for Python? It lets you work on parts of XML documents as trees, without having to parse all of it at once like a standard DOM requires. Very nice for processing really huge docs, but then again, its a perl module ;-) tia Henrik From gerhard.haering at gmx.de Thu Jul 18 11:34:25 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 17:34:25 +0200 Subject: smtplib and passwd's In-Reply-To: References: Message-ID: <20020718153425.GA1496@lilith.my-fqdn.de> * Rajarshi Guha [2002-07-18 11:04 -0400]: > Hi, > I'm using smtplib to let my script send some mail through my smtp > server. However I need a logon and passwd for my smtp server - how > does smtplib handle such servers? Where can I specify my username and > password? import smtplib srv = smtplib.SMTP("mail.myprovider.com") srv.debuglevel = 25 srv.login("myname", "mypassword") # ... You need at least Python 2.2 for this login method to be available. OTOH backporting SMTP AUTH to earlier Python versions would certainly be possible. If there are problems, report back to me and I can send you an improved version (bugfixes, support for old auth advertising, and additional LOGIN auth method) that will (most likely) end up in Python 2.3. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.9 ?C Wind: 6.2 m/s From K.Rdt at TU-Berlin.DE Thu Jul 4 02:16:56 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Thu, 04 Jul 2002 08:16:56 +0200 Subject: HT clear some wxPython fram? In-Reply-To: <20020703131607.6b154210.logiplexsoftware@earthlink.net> Message-ID: Am 03.07.02 22:16:07, schrieb Cliff Wells : >dc.DrawText(t, x, y) >where x, y are the screen coordinates relative to the top-left corner. I realized it a little later. --------------------------------------------------------------------- Hi BUT # it looks like a BUG y = 0 dc.DrawText(str(y),400,0) # y ever 0 for t in self.text: dc.DrawText(str(y)+t, 0, y) # y until 126 then clear # I took a font-height of 8 # there are 4 lines for each output # and I got 10 lines then clear y += self.fontsize + 2 This happens even if I use another name for y, cause y is used below for string. K at Rdt --------------------------------------------------------------------- From baas at ira.uka.de Mon Jul 8 02:25:54 2002 From: baas at ira.uka.de (Matthias Baas) Date: Mon, 08 Jul 2002 08:25:54 +0200 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 References: <3D24FF3A.4010205@something.invalid> Message-ID: On Fri, 5 Jul 2002 13:42:45 -0700, "David LeBlanc" wrote: >Making pyrexc use native (Visual C) compiler: >[...] I think the easiest way to compile Pyrex modules (either on Windows, Linux or anything else) is by using the distutils. For example, to compile the file shrubbery.pyx you just need the following setup.py script (which assumes you have "pyrexc" somewhere in your path): ######################################### from distutils.core import setup, Extension import os os.system("pyrexc shrubbery.pyx") setup(name="shrubbery", ext_modules=[Extension("shrubbery", ["shrubbery.c"])]) ######################################### Now you can compile the module with "setup.py build" or "setup.py install" and then the distutils take care of the build process. The nice thing is, that you don't have to set any paths (unless you need custom libraries/header files) and that it works on any platform. However, I don't know if the distutils can also be used for other compilers than Visual C++ on Windows. - Matthias - From gerhard.haering at gmx.de Sat Jul 6 10:08:31 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 6 Jul 2002 16:08:31 +0200 Subject: sqlite-python-0.2.0.win32-py2.2.exe fails In-Reply-To: <1b8c5fe1.0207060550.72952217@posting.google.com> References: <1b8c5fe1.0207060550.72952217@posting.google.com> Message-ID: <20020706140831.GB5932@lilith.my-fqdn.de> * Comcol [2002-07-06 06:50 -0700]: > I tried to run > sqlite-python-0.2.0.win32-py2.2.exe > on a Windows 95 machine, but it failed due to a page fault. *Sigh* Did you know that we have a list for users of PySQLite at http://lists.sourceforge.net/lists/listinfo/pysqlite-users ? Not all its developers are closely following comp.lang.python. > Any chance of getting one that works? I only have Windows XP Pro, one other developer has Windows 98, so we didn't test on Windows 95, yet. I might take out VMWare and install my old copy of Windows 95b, but that's honestly a PITA for me. > Also, I'm assuming that the file installs everything necessary to run > sqlite from python. Yep. It contains a Python extension module that is statically linked against SQLite. > I'm also assuming that the package is ready to go "out of the box" - > only installation being required. It would break my heart to find out > that I would actually have to (*try* to) compile something, or install > a whole bunch of other stuff (apart from Python, of course) to get it > to run. Am I right? Only Python and PySQLite are required. Date and time data types are supported if mxDateTime is installed. Now that doesn't solve your problem. What we need to debug your problem is a core dump, or DrWatson file, or whatever it's called on Win95. Does anybody here know by chance how to produce it? Comcol, would you be willing to install gdb and run a debug build of PySQLite so that we could get at the backtrace of your page fault? If yes, then I could try to assemble the necessary instructions for you. Gerhard PS: PySQLite 0.3.0 will most likely be released today. Maybe we are lucky and it solves your problem. PPS: Have you installed all updates for Windows 95? Service Pack 1? -- This sig powered by Python! Au?entemperatur in M?nchen: 15.9 ?C Wind: 1.9 m/s From shagshag13 at yahoo.fr Fri Jul 12 11:39:13 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 12 Jul 2002 17:39:13 +0200 Subject: Recomendations on Books References: Message-ID: "Ray Tux" a ?crit dans le message de news: hfrX8.3972$7W6.2920 at nwrddc02.gnilink.net... > Hello I am a beginer to programming and I have chose Python. I was just > wandering if you guys could recomend some good Python Beginers books. > > Thanks I'm also a beginner and decide to avoid buying one of these huge expensive books after getting/reading online ressources such as : http://systems.cs.uchicago.edu/~beazley/tutorial/beazley_advanced_python/advpy.pdf http://diveintopython.org/ http://www.ibiblio.org/obp/thinkCSpy/dist/ http://www.greenteapress.com/thinkpython.html http://www.mindview.net/Books/TIPython s13. From edream at tds.net Tue Jul 30 18:52:44 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 30 Jul 2002 22:52:44 GMT Subject: Leo.py: Some Thoughts References: <3D44EAA9.7010607@thomas-guettler.de> Message-ID: <0NE19.25664$fH5.26101723@kent.svc.tds.net> I have just released leo.py 3.2. I believe it addresses all issues raised here except the problem opening LeoDocs.leo. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From guy at lightwork.co.uk Tue Jul 2 07:30:49 2002 From: guy at lightwork.co.uk (Guy) Date: 2 Jul 2002 04:30:49 -0700 Subject: cpickle and classes Message-ID: Been reading alot of the messages posted to the python groups about cpickle, (old and new). Below I've got an exsample bit of code.(Please don't comment on this code its just AN EXAMPLE.) ---------------------------------------------------------------------------- import cPickle class mill: time = "" date = "" name = "" flourUsage = flour() add =[""] class flour: ammount = "" date = "" data = mill() data.time = "1" data.date = "2" data.name = "3" data.flourUsage.ammount = "4" data.flourUsage.data = "5" data.add=["adsfads","dsgdsfgdf"] Data001 = cPickle.dumps(data, 1) Data002 = cPickle.loads(Data001) print Data002.time print Data002.date print Data002.name print Data002.flourUsage.ammount print Data002.flourUsage.date file = open(os.getcwd()+"\\test.dump", "w") cPickle.dump(Data002, file) file.close() --------------------------------------------------------------------------- When this is run it puts some stuff to screen and file : Screen display : >>> 1 >>> 2 >>> 3 >>> 4 >>> 5 File display : (i__main__ mill p1 (dp2 S'date' S'2' sS'add' (lp3 S'adsfads' aS'dsgdsfgdf' asS'name' S'3' sS'time' S'1' sb. If you look at the file there is NO sign of the Data002.flourUsage.ammount and Data002.flourUsage.date values or var names. Why ? Can cpickle not handle this ? Is there anything I can do to improve the code to make cpickle work ? Are there any work arounds for this ? Maybe suggestions of how to do this in a different way. From vovka_foreverREMOVE_THIS at hotmail.com Sun Jul 21 12:06:13 2002 From: vovka_foreverREMOVE_THIS at hotmail.com (Vladimir Cherepanov) Date: Sun, 21 Jul 2002 20:06:13 +0400 Subject: XML with Python - supposed to be simple? ;) Message-ID: As a complete newbie to both XML and Python, I've been trying to create (any!) XML document using DOM API in PyXML package. Very simple task isn't it? It doesn't look very simple to me now, because I couldn't find out what should I pass to Document.__init__() and how can I save an instance of Document into a file. Could anyone help me with sample code or any other information? From markus.vonehr at ipm.fhg.de Fri Jul 12 02:21:00 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Fri, 12 Jul 2002 08:21:00 +0200 Subject: window icons in Tkinter References: <3d2e442c$0$11264$afc38c87@news.optusnet.com.au> Message-ID: <3D2E754C.DF43054A@ipm.fhg.de> I use hackicon: URL: http://hackicon.sourceforge.net Download: http://prdownloads.sourceforge.net/hackicon/hackicon00003.zip Steven schrieb: > > Can anyone shed some light on how to get the root window to use an icon > other than the 'Tk' symbol? > > I can't seem to find an example of this anywhere > > thanks > > Steven From paddy3118 at tiscali.co.uk Sat Jul 27 16:11:16 2002 From: paddy3118 at tiscali.co.uk (Donald McCarthy) Date: Sat, 27 Jul 2002 21:11:16 +0100 Subject: Two RE proposals/Group Variables References: Message-ID: <3D42FE64.8020109@tiscali.co.uk> Strange you should post this... I was thinking of a similar idea but as a wholly contained extension to the re syntax. Groups it seems group the text matched by the enclosed re section. References to groups are references to the text matched by the grouped re section. When groups are scanned by the re engine it seems that an association is made with the name of the group and the text that is matched. How about having 'meta-groups' or 'group variable' definitions within the re engine? A group variable definition would use the re extension syntax e.g. (?V...) rather like the definition of named groups, but when scanned, no characters would be consumed, instead the re engine would associate the name with the enclosed regular expression fragment. Group variables would have to be instantiated before they could be used. (?V=) would be expanded to the saved re associated with the variable and used as if defining a new un-named group in the re. For example: extended_re.compile(r"(?Vspam|eggs)xxxx(?V=)") would be equivalent to: re.compile(r"xxxx(spam|eggs)") (?P) would act in an equivalent way to the definition of group but where the enclosing re is that stored in the Group variable . i.e.: extended_re.compile(r"(?Vspam|eggs)xxxx(?P)") would be equivalent to: extended_re.compile(r"(?Vspam|eggs)xxxx(?P(?V=))") Which should work like re.compile(r"xxxx(?Pspam|eggs)") Your example would become: wordpunct = extended_re.compile(r"(?V\w+)(?V[,.;?])(?P)(?P!punct)") (Its around now when I realize why I hadn't posted earlier :-) ) Notice the extension in that I allow no groupname before the exclamation mark, !, and expect the fragment to then act as if it where a definition of an un-named group. Hierarchical composition: r"((?Vbudvar|stella)(?Vpizza|curry)(?V(?V=)|(?V=))" (Hey, I can leave the beer alone :-) ) I guess the match operator would have to be extended to return associations between variable names and groups created from them by the ! syntax. The main advantage I see is that it is a proposed extension to the re syntax and so could be used be considered by all the languages that use 'perl like' regular expression matching. Searches could return information about matches against the various instantiations of the named variable - giving 'higher level' information. David LeBlanc wrote: > 1. Add a substitution operator - in the example below it's "!<..>" > > word = r"\w*" punct = r"[,.;?]" wordpunct = re.compile(r"!!") > > The re compiler sees r"\w*[,.;?]" Trivial example, but for fancier patterns it would > be great IMO. A substitution pass should be done over the substituted text for > nesting: > > if = r"if" term = r"something" num = r"\d*" op = r"[-+*/]" factor = > r"!\s*!\s*!" expr = r"!|!" if_stmt = > re.compile(r"!\s*\(?\s*!\s*\)?\s*:" (this is just a muddle to give the idea) > From wyojustin at hotmail.com Sat Jul 20 00:48:11 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Sat, 20 Jul 2002 04:48:11 GMT Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: > Basicely I have two lists, one containing the future string-names > and one containing the values I want to give them. The order is > identical in both. Right now I'm solving this by a dictionary, but > I would really prefer to have straight strings as a result of my > operation. I like the idea of keeping your namespace clean. But if what you really want is to assign the values to your local namespace I have two solutions. 1. Ugly one-liner eval ';'.join(['='.join(x) for x in zip(names, [str(v) for v in values])]) 2. Update locals() locals().update(dict(zip(names,values))) > Thanks, Joh You bet Justin From aleax at aleax.it Fri Jul 26 17:18:56 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 21:18:56 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> Message-ID: <41j09.125397$Jj7.2891527@news1.tin.it> Robb Shecter wrote: > But to really answer you - I like lambdas and think lambdas can add > clarity because their scope directly reflects their 'scope'. (Make > sense?) Sorry, not to me. Take a typical bug sometimes posted here, such as: for word in 'fee fie foo fum'.split(): Button(frame, command=lambda: print word) The poster is typically nonplusses that all buttons print 'fum'. Lambda's scope (or 'scope') has taken another victim. Using a closure instead of the lambda: def makeprinter(word): def printword(): print word return printword for word in 'fee fie foo fum'.split(): Button(frame, command=makeprinter(word)) is one of several ways to make the bug disappear (another is to use a "lambda word=word: print word" snapshot-trick, but that seems to fly in the face of your liking lambda's "scope"...?). Closures' "scopes" can be said to directly reflect what they should reflect. I can't see how you can claim this for lambda. Alex From chris.gonnerman at newcenturycomputers.net Tue Jul 2 00:45:57 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 1 Jul 2002 23:45:57 -0500 Subject: Teaching programming -- circular data structures References: <60FB8BB7F0EFC7409B75EEEC13E20192F1AA6D@admin56.narex.com> Message-ID: <002801c22183$5c0d40c0$0101010a@local> ----- Original Message ----- From: "Bjorn Pettersen" > We had the same problem teaching recursion to first year CS students, so > I think it's pretty common. Once they got used to inductive proofs most > of them seemed to "get it" however, so my current theory is that some > sound CS theory makes for a better programmer > > You could always show him a fundamental data structures text that covers > AVL or Red-Black trees . I have a Red-Black tree implementation in Python at http://newcenturycomputers.net/projects/rbtree.html ... if anyone is interested ... Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jwilhelm at outsourcefinancial.com Mon Jul 22 15:26:40 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 22 Jul 2002 12:26:40 -0700 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: <20020721115251.12dd6d7d.alexandrecourbot@linuxgames.com> References: <20020721115251.12dd6d7d.alexandrecourbot@linuxgames.com> Message-ID: <1027366000.27398.1.camel@jwilhelm.ofsloans.com> > Note also that I > had to cross-compile the Python library myself from Python 2.2 sources, > as there is no lightweight Python distribution for the Arm. Actually..... there is. I haven't used it myself, but it can be found here: http://www.riverbankcomputing.co.uk/zaurus/index.php --Joseph Wilhelm From jepler at unpythonic.net Fri Jul 26 12:42:25 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 26 Jul 2002 11:42:25 -0500 Subject: redirect to > and to console ? In-Reply-To: References: Message-ID: <20020726164225.GB1452@unpythonic.net> Real OSes have a program called "tee" for performing this sort of task: someprogram | tee logfile Jeff From john.abel at pa.press.net Fri Jul 5 10:56:12 2002 From: john.abel at pa.press.net (John Abel) Date: 05 Jul 2002 15:56:12 +0100 Subject: Getting Process List On *nix Message-ID: <1025880972.1933.28.camel@lestat.howden.press.net> I am trying to write a script, capable of running on Win32, and *nix, which looks for certain processes. However, I can't seem to find any details of how to access of list of running processes under *nix, without shelling out, something I'm loathe to do. I'd be grateful for any pointers. John From pinard at iro.umontreal.ca Sun Jul 28 13:48:20 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 28 Jul 2002 13:48:20 -0400 Subject: How to detect the last element in a for loop In-Reply-To: References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: [Tom Verbeure] > Then what about this? > for a in myList: > if last_one: > special_stuff > do_stuff Eh! Some require a bit more work than others :-). -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From shimbawa at shimbawa.ch Sun Jul 14 16:54:47 2002 From: shimbawa at shimbawa.ch (=?ISO-8859-1?Q?C=E9dric_Dutoit?=) Date: Sun, 14 Jul 2002 22:54:47 +0200 Subject: Ann : PyUt 1.1 - little UML 1.3 editor with plugins and roundtrip support Message-ID: <3D31E517.1020700@shimbawa.ch> PyUt 1.1 is available at http://pyut.sf.net PyUt 1.1 ======== - is a little UML 1.3 editor which support class diagram and use-cases. - is written in Python - is GPL, free - works under Linux, Unix, Windows (the linux and unix version is a rpm which need wxPython-http://www.wxpython.org; a Macintosh version of wxPython is under construction) Functionalities : =============== - Class diagram - Use-cases - Export to bmp, jpg, ps - REVERSE-ENGINEERING java, python - CODE GENERATION java, python, C++ - XMI import (compatibility with Rational Rose - i18n (French-English) - Plugins support (python) Links ===== PyUt's website : http://pyut.sf.net Direct download : http://sourceforge.net/project/showfiles.php?group_id=39548 For PyUt's team, C.Dutoit - dutoitc at hotmail.com PyUt's team is composed of 6 students at EIVD - Ecole d'ing?nieurs du Nord Vaudois, Suisse (www.eivd.ch) (~Computer high school) This project is active and will continue ! From mark.charsley at REMOVE_THIS.radioscape.com Wed Jul 3 09:47:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Wed, 3 Jul 2002 14:47 +0100 (BST) Subject: Forward Declaring Py_complex Message-ID: Is there any way to forward declare Py_complex in C++ headers? I'm trying to create a C++ function that returns a Py_complex, and would really prefer not to have to pull in all of Python.h in the header file. If it makes any difference I'm using VC++ 6. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From trentm at ActiveState.com Tue Jul 30 13:55:04 2002 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 30 Jul 2002 10:55:04 -0700 Subject: Python equivalent to 'which'? In-Reply-To: <732d35a1.0207300836.3836892e@posting.google.com>; from ergeorge@worldnet.att.net on Tue, Jul 30, 2002 at 09:36:07AM -0700 References: <732d35a1.0207300836.3836892e@posting.google.com> Message-ID: <20020730105504.B17850@ActiveState.com> [eg wrote] > Is their a python equivalent to the bash shell command 'which'? I > haven't found it, and 'which' is such a common word that it may be > lost in the noise in my dejanews searches :( > > I could grab the PATH environment variable and walk all the paths, but > I'm hoping python has already done it for me! I wrote one that works on Windows and Unix. On Windows it understands the AppPaths registration that can be done to make specific application launchable without being on the PATH. It understands PATHEXT etc. It can be used as a module or as a script. http://starship.python.net/~tmick/ Cheers, Trent -- Trent Mick TrentM at ActiveState.com From aleax at aleax.it Sun Jul 7 10:06:59 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 14:06:59 GMT Subject: how to disable maximize button? References: Message-ID: <7WXV8.51674$vm5.1915116@news2.tin.it> Cameron Laird wrote: ... > though Tkinter proper doesn't provide a means to achieve this, > there are win32 calls accessible through *that* module that > make it happen. > > I've forgotten what they are. If I were going to pursue this, > I'd check with operating-system experts for the correct lower- > level calls. If you're willing to limit your application to running only under Win32, there are surely many ways. For example, message WM_NCHITTEST can be intercepted in the main windows' window- procedure, and rather than just passing it straight through to DefWindowProc as one usually does, one intercepts the return value from DefWindowProc and (e.g.) changes a return value of HTMAXBUTTON to HTNOWHERE, etc, etc. Obtaining a disabled _look_ for the maximize button, etc, is slightly trickier, but can be done by similar play with WM_NCPAINT. I guess one COULD tweak Tkinter's main window the Windows way, with win32all or calldll or the like, to achieve these kind of effects in Python (under Microsoft Windows only). I don't believe the original poster saying anything about being willing to limit his application to Microsoft Windows only, though, so I'm not sure any of this sub-thread is relevant. Alex From deltapigz at telocity.com Fri Jul 26 10:50:16 2002 From: deltapigz at telocity.com (Adonis) Date: Fri, 26 Jul 2002 10:50:16 -0400 Subject: tarfile.py question Message-ID: <3d41619d$1_2@nopics.sjc> i have downloaded tarfile.py by Lars Gust?bel and have trouble reading tar.gz files. i am using the following code: import tarfile, sys if len(sys.argv) == 1: print 'usage: untar ' sys.exit() x = tarfile.TarFile(sys.argv[1], 'r') tarfile.errorlevel = 1 tarfile.debug = 3 m = x.getmembers() for i in m: x.extract(i, sys.argv[2]) x.close() i attempted to read a tar.gz file (gadfly) and when i load it no error is posted nor any information at that, but the m variable is an empty list, and if i attempted to do x.list() to get a list of files it returns None, although it seems that it loaded the tar file properly no IOError was generated, is there something i am missing? i have tested this by generating a tar.gz file using the same module and it unpacked properly. any help is greatly appreciated. Adonis note: im a windows user so i have no tar archiving present. From fakeaddress at nowhere.org Sun Jul 7 05:35:08 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 07 Jul 2002 09:35:08 GMT Subject: sending a file through sockets References: <3D277DDC.1040705@nowhere.org> <1026007094.566332@yasure> Message-ID: <3D280B4B.8020008@nowhere.org> Donn Cave wrote: > Quoth Bryan Olson: > I read your first post, and I thought it was kind of inappropriate. > For "my first Internet application" (the original poster's, that is), > this was a mighty generous hint and more than adequate. One problem with e-mail/news is that some subtleties of expression get lost. In my defense, I did say "right" and "good advice" to a couple things. To those I thought not-so-good, I was intending to be perfectly matter-of-fact. I was deliberately pointing out that sockets programming is harder than it looks. A novice cannot tell whether an answer is a hint or a solution. He may not be ready to worry about signals, but he does need to know the distance between his question and a robust application. Also, there's tons of bad sockets code out there, some in the Python standard library. I did intend my post for people who were already doing sockets programming. Did you check out the signal issue? > One would > imagine that in the end, the parameter to connect() would have to be > filled in by the original poster. I doubt the original poster would imagine that, and I doubt most of the more experienced actually knew about the undocumented BSD'ism imitated by Linux (I didn't). Obviously "localhost" in place of "" makes the need to fill in the parameter much more clear. > Sure we're literally shutting the power off? That certainly wasn't > what I meant, but I gather it is what you have in mind. I gathered that you had in mind a kind of any-old-way of ending. Clean close of a TCP connection is a deliberate act, and the method you named doesn't do it. --Bryan From marklists at mceahern.com Mon Jul 15 15:31:23 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 15 Jul 2002 14:31:23 -0500 Subject: switch recipe? In-Reply-To: Message-ID: I want to thank everyone who posted to this thread. I've gotten many excellent suggestions. The following demo presents all the distinct variations I culled from the thread. I like Emile's suggestion of the name cycler, but I didn't use it in this demo--I think partly because for better or worse alternator has lodged itself in my brain. Cheers, // mark #! /usr/bin/env python from __future__ import generators import unittest def weave(setn, setm): """Return a generator that iterates over setn and setm until setn is exhausted. If setn is larger than setm, cycle over setm. """ m = len(setm) if not setn or not setm: raise ValueError, "Weaved sets cannot be empty" for i in range(len(setn)): yield setn[i], setm[i%m] def finite_alternator(length, *args): """Return a finite repeating alternator for args.""" c = 0 while args and c < length: for a in args: yield a c += 1 if c >= length: break def take(n, it): """Return n elements from the unbounded iterator.""" for j in xrange(n): yield it.next() def repeating_alternator(*args): """Return a repeating alternator for args.""" while args: for a in args: yield a def weave_items(iterator, alternator, weave_item): """Iterate over iterator, applying weave_item to each item with its pair in alternator. """ for item in iterator: yield weave_item(item, alternator.next()) def color_item(item, color): template = "<%(color)s>%(item)s" return template % locals() class test(unittest.TestCase): def setUp(self): self.colors = ("red", "orange", "yellow", "green", "blue", "indigo", "violet") self.expected = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] self.length = 10 def test_weave(self): colors = self.colors length = self.length expected = self.expected generated = [color_item(x, y) for x, y in weave(range(length), colors)] self.assertEquals(expected, generated) def test_zip(self): colors = self.colors length = self.length expected = self.expected iterator = range(length) alternator = repeating_alternator(*colors) weaved = zip(iterator, alternator) generated = [color_item(x, y) for x, y in weaved] self.assertEquals(expected, generated) def test_list_comprehension(self): colors = self.colors length = self.length expected = self.expected iterator = range(length) alternator = repeating_alternator(*colors) generated = [color_item(x, alternator.next()) for x in iterator] self.assertEquals(expected, generated) def test_map(self): colors = self.colors length = self.length expected = self.expected iterator = range(length) alternator = finite_alternator(length, *colors) generated = map(color_item, iterator, alternator) self.assertEquals(expected, generated) def test_map2(self): colors = self.colors length = self.length expected = self.expected iterator = range(length) alternator = repeating_alternator(*colors) generated = map(color_item, iterator, take(length, alternator)) self.assertEquals(expected, generated) def test_weave_items(self): colors = self.colors length = self.length expected = self.expected iterator = range(length) alternator = repeating_alternator(*colors) generated = [x for x in weave_items(iterator, alternator, color_item)] self.assertEquals(expected, generated) def test_empty(self): r = repeating_alternator() self.assertRaises(StopIteration, r.next) if __name__ == "__main__": unittest.main() - From robert_kuzelj at yahoo.com Sun Jul 7 11:19:14 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 7 Jul 2002 08:19:14 -0700 Subject: COCOMO - appropriate for languages like Python? References: Message-ID: hi skip, > It's been many years since I've considered software cost estimation models > like COCOMO. Is COCOMO appropriate to apply to high-level languages like > Python? I believe COCOMO assumes each fully debugged source line of code > (SLOC) in any language and for any purpose costs roughly the same amount to > produce. The cost savings for languages like Python would come because you > have to write so many fewer lines of code to implement the desired > functionality. dont know about cocomo (thou i read caper jones' book bout software estamating - but that was sometime ago). but i am a fan of function point analysis (fpa) and there they have the concept of a productivity factor (dont know the exact term, sorry) which tells you how many function points you are able to express with (if i remember correctly) 1K SLOC. i can remeber a table saying that this factor was twice as high for python as with java. i have looked on the net but could not find the exact link. > This constant cost per SLOC assumption seems at least marginally invalid to > me. For example, writing an extension module which wraps a preexisting C > library is generally pretty straightforward (even without tools like SWIG or > Pyrex), but is pretty verbose, so COCOMO would tend to overestimate the cost > to produce such code. It also seems the clarity of a language's constructs > will make a difference. For example, in C I can write > > if ((c = gets(s)) == EOF) { > ... > } > > while in Python, even though I have to express that concept in two lines: > > s = sys.stdin.readline() > if s == "": > ... > > you can argue the Python code is less likely to contain a bug. Together, > the cost to create those two (fully debugged) lines of Python code may well > be less than the cost to create the one line of C code, not twice the cost > of the one line of C code, as COCOMO would estimate it. > > Are there other (more modern?) cost estimation models which don't assume > cost-wise that a SLOC is a SLOC is a SLOC? one of the usual misconceptions about metric-suites, of which software estimating is one, is that they do treat everything uniformly. but every metrics book (and paper) advises you to tailor you metrics program to your (that is your project) needs. so for example if your projects consists of a lot of very dense declarative sourcefiles that will be transformed into very verbose sourcefiles (eg. python - > c) you are asked to measure those resulting sourcefiles differently than sourcefiles that might be written from hand. one very simple categorisation might be id | description | loadfactor -------------------------------------------- 1 | completely handmade files | 1 2 | partially generated | 0.5 3 | fully generated | 0.15 etc. so i dont belive that cocomo says a sloc a sloc is a sloc. at least fpa doesnt do that and it predates cocomo II. ciao robertj From paddy3118 at tiscali.co.uk Sat Jul 27 09:39:22 2002 From: paddy3118 at tiscali.co.uk (Paddy) Date: Sat, 27 Jul 2002 14:39:22 +0100 Subject: Two RE proposals/Group Variables References: Message-ID: <3D42A28A.6070300@tiscali.co.uk> Strange you should post this... I was thinking of a similar idea but as a wholly contained extension to the re syntax. Groups it seems group the text matched by the enclosed re section. References to groups are references to the text matched by the grouped re section. When groups are scanned by the re engine it seems that an association is made with the name of the group and the text that is matched. How about having 'meta-groups' or 'group variable' definitions within the re engine? A group variable definition would use the re extension syntax e.g. (?V...) rather like the definition of named groups, but when scanned, no characters would be consumed, instead the re engine would associate the name with the enclosed regular expression fragment. Group variables would have to be instantiated before they could be used. (?V=) would be expanded to the saved re associated with the variable and used as if defining a new un-named group in the re. For example: extended_re.compile(r"(?Vspam|eggs)xxxx(?V=)") would be equivalent to: re.compile(r"xxxx(spam|eggs)") (?P) would act in an equivalent way to the definition of group but where the enclosing re is that stored in the Group variable . i.e.: extended_re.compile(r"(?Vspam|eggs)xxxx(?P)") would be equivalent to: extended_re.compile(r"(?Vspam|eggs)xxxx(?P(?V=))") Which should work like re.compile(r"xxxx(?Pspam|eggs)") Your example would become: wordpunct = extended_re.compile(r"(?V\w+)(?V[,.;?])(?P)(?P!punct)") (Its around now when I realize why I hadn't posted earlier :-) ) Notice the extension in that I allow no groupname before the exclamation mark, !, and expect the fragment to then act as if it where a definition of an un-named group. Hierarchical composition: r"((?Vbudvar|stella)(?Vpizza|curry)(?V(?V=)|(?V=))" (Hey, I can leave the beer alone :-) ) I guess the match operator would have to be extended to return associations between variable names and groups created from them by the ! syntax. The main advantage I see is that it is a proposed extension to the re syntax and so could be used be considered by all the languages that use 'perl like' regular expression matching. Searches could return information about matches against the various instantiations of the named variable - giving 'higher level' information. David LeBlanc wrote: > 1. Add a substitution operator - in the example below it's "!<..>" > > word = r"\w*" punct = r"[,.;?]" wordpunct = re.compile(r"!!") > > The re compiler sees r"\w*[,.;?]" Trivial example, but for fancier patterns it would > be great IMO. A substitution pass should be done over the substituted text for > nesting: > > if = r"if" term = r"something" num = r"\d*" op = r"[-+*/]" factor = > r"!\s*!\s*!" expr = r"!|!" if_stmt = > re.compile(r"!\s*\(?\s*!\s*\)?\s*:" (this is just a muddle to give the idea) > From robin.siebler at corp.palm.com Fri Jul 12 13:28:35 2002 From: robin.siebler at corp.palm.com (Robin Siebler) Date: 12 Jul 2002 10:28:35 -0700 Subject: A better self References: <3D2BD37D.8CF82AE@alcyone.com> Message-ID: <886c5e4b.0207120928.67b019b@posting.google.com> You can do this with methods in VB: With Text1: .Height = 100 .Width = 200 End With Duncan Booth wrote in message news:... > Erik Max Francis wrote in > news:3D2BD37D.8CF82AE at alcyone.com: > > > Matt Gerrans wrote: > > > >> In keeping with that concept, '..' would be referring to the base > >> class > >> (equivalent to java's "super"). > > > > I think that's definitely mixing metaphors. For one thing, which base > > class? Python supports multiple inheritance. > > > Python already has a 'super' which works properly with multiple > inheritance, so presumably it would be a shorthand for super with > appropriate arguments rather than referring to a specific base class. From cliechti at gmx.net Tue Jul 23 09:54:25 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 15:54:25 +0200 Subject: Help On file IO References: Message-ID: "jayant kawadkar" wrote in news:mailman.1027428272.29932.python-list at python.org: > I want a help on File IO ,as I 'm new to Python langauge. welcome > As I want to use the API : > > char* PyModule_GetFilename(PyObject *module) > > in my python programm > What should I import for that I can use this . #inlude > Now it is giving the error that: > > PyModule_GetFilename is not defined. chris -- Chris From bokr at oz.net Sun Jul 14 17:43:57 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Jul 2002 21:43:57 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308c96_8@news.newsgroups.com> <3d315be9_1@news.newsgroups.com> Message-ID: On Sun, 14 Jul 2002 13:17:09 +0200, JB wrote: >Bengt Richter wrote: > [...] >> (Is this like your data? Or how does it differ?) > >This is ok. The real data are much longer strings, but it is >ok. A further question: What generates the "id" number, and what do you need it for besides verifying order? Do you need it as a key to other data locally or remotely? Or is your concern just guaranteeing unchanged order as the selection narrows? If it's just order, we can probably eliminate them, and gain speed. If you need the id's, and the rest of the tuple is just a single string item, then we will gain speed by combining the id into the string, perhaps as a suffix. The gain will come from having a list of string-only elements so that we can search for substrings without a subscript operation on a tuple for every element, and being able to use map or filter using builtin functions. This may allow simpler approaches with adequate speed. [...] > >> >> Here we initialize a search object with a master starting >> list and nothing selected >> >>> is1 = IncSrch(master1) >> >>> is1 >> >> >>> `is1` >> '' >> I.e., there is nothing selected to the curr list yet. >> >> Here we do a first search based on containing substring >> 'D': >> >>> is1.new_search('D') >> Just typing the name calls repr to print the current state >> of the search object: >> >>> is1 >> (7, 'item_DY') >> >> That wasn't much to do a secondary search on, so we do a >> new search on the master list for 'B': >> >>> is1.new_search('B') >> >>> is1 >> (1, 'item_BX') >> (2, 'item_BY') >> (3, 'item_BZ') >> (5, 'item_BW') >> (6, 'item_BW') >> (8, 'item_BY') >> >> That got a few, so we incrementally search for 'Y': >> >>> is1.inc_search('Y') >> >>> is1 >> (2, 'item_BY') >> (8, 'item_BY') >> >> And so forth. Is that the kind of thing you want to do? > >Yes. Well, maybe the question was a little too broad ;-) My example searched first for 'B' then for 'Y' within the results of the first search, but it did not search for 'BY'. This is an important distinction, since you will presumably want to refine a search for, e.g., Bach by incrementally refining based on 'B', 'Ba', 'Bac' and 'Bach', but if you want to find his Italian Concerto, you don't want to continue refining results by searching them for 'BachI', 'BachIt', 'Bachita', etc. I.e., you are finished with Bach and should presumably refine further based on 'I', 'It', 'Ita', etc. found anywhere in the entries you have so far. > >> I presume you have to pass a list of items in some form to >> the display widget, and that you will not want to pass >> more than say MAX_FOR_WIDGET items for a reasonable >> scrolling display, and you may(??) need the items as a >> list of strings, not tuples, so you might want to add a >> first_for_widget() and next_for_widget() method to the >> class as part of the definition (but I'll do it separately >> here since I have some state above to use): > >Of course, only 40 or so lines can be displayed at the same >time. It plays no r?le if I pass list or tuples of strings. > You mean no difference if you pass ('x','y','z') or ['x','y','z']? But I was referring to tuples including the integer id number. IOW, I wouldn't expect to pass [(24,'x'), (25,'y'), (26,'z')] to a low level single column dropdown list widget that I wanted to show x, y and z. So the question is in what form your parameters need to be passed. >> If you will comment on what this simple class does and >> doesn't do that you need functionally, that will establish >> unambiguous requirements. Then we can make it fast one way >> or another. > >That is exactly. what I want. I do not quite understand in >your soulution, what you do, when the search string is >shortened by the user. Let us assume, he had typed in "Mo" >(for Mozart) but then he decides he is looking for "Me" >(another composer). So he deletes the "o". What happens >then? This is, why I thought, I should need two lists. There's a number of things you could do. You will note that the class does have two lists: self.master and self.curr. Of course, self.master is just a reference to the starting list passed to the __init__ method, since we haven't re-bound self.master. The simple thing would be just to call new_search('M') when the user deletes 'o' from 'Mo', and then inc_search('Me') when s/he types the 'e', and so forth. But if we want to do multiple words, we probably want to re-search on the results from the previous complete word, not the original master list. We could keep track of previous complete-word results in a separate list and copy self.curr to it when we start a new word, and start all over with new searches on the master list when the user wants to abandon a previous word. We could modify the interface so that the search object handles multiple words internally if we pass them as blank-separated words plus the trailing word fragment that the user is currently typing or backspacing over. This way we only need a single search method, though it will be more complicated. Once this really nails your functional requirements, we can see about performance. If you anticipate a really large database, you might want to consider a relational database to do primary selections. And/or you might want to get the first 40 results quickly for user feedback and let a separate thread work on a full search while the user ponders. As you notice, we are now a long way from discussing just "Moving list entries from one list to another" ;-) You may yet want to do something like that, but let's get the role of the id cleared up, and the functionality settled first. Regards, Bengt Richter From tim.one at comcast.net Mon Jul 8 20:37:51 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 08 Jul 2002 20:37:51 -0400 Subject: Idle setup install falis on Win2k In-Reply-To: Message-ID: [David LeBlanc] > Idle.py assumes that it's scripts are in the same directory as itself It assumes they're on sys.path. This is normally true. > and they're not after install. As opposed to what, "before install"? I can't tell what you're getting at. All of Idle is installed under Tools\idle\ on Windows, and the Start menu shortcut reads (assuming the default install path): C:\Python22\pythonw.exe "C:\PYTHON22\Tools\idle\idle.pyw" > Idle.pyw just silently fails if they're not in the same dir as itself. > > This is PythonLabs Python 2.2.1 binary on Win2k with the included > distribution of Idle. Where do you think Idle got installed? Don't get paranoid, but this is another thing that works for everyone but you . From mbub at meta-level.de Tue Jul 16 03:45:41 2002 From: mbub at meta-level.de (Michael Bub) Date: 16 Jul 2002 00:45:41 -0700 Subject: Webware 0.7/Singleton pattern Message-ID: Hi folks, I am currenty working on my diploma thesis. I chose to use Webware and Python to build my WebApp. During the development it turned out that some classes should become singletons. I implemented all my singleton classes with the following code: class myClass: __instance=None def __init__(self): # init stuff pass def get_instance(): if myClass.__instance is None: myClass.__instance=myClass() return myClass.__instance get_instance=staticmethod(get_instance) This generally seems to work just fine when using it. However, in my WebApp built with Webware 0.7 (using Python 2.2 on a FreeBSD4.4 system), the second or third time the get_instance method is called, the one instance that was created by the singleton seems to be forgotten about (or rather, it seems as if the file that holds the class definition was imported and used for the very first time) and another one is created. This, of course, sucks. I do not know where the first one goes, its __del__ does not get called during that process, but it is replaced by the second instance created by the singleton. after that has happened, everything is back to normal and the singleton classes behave as expected and do not create any new objects. does anyone know how to get "safe" singleton classes to get rid of that problem? -- Michael From brueckd at tbye.com Thu Jul 18 23:41:41 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Thu, 18 Jul 2002 20:41:41 -0700 (PDT) Subject: win32com: makepy causes ie problems. In-Reply-To: Message-ID: On Thu, 18 Jul 2002 brueckd at tbye.com wrote: > I use a function like this: > > def WaitForDoc(doc, extraDelay=0.0): > if extraDelay: > time.sleep(extraDelay) > while not (hasattr(doc, 'readyState') and doc.readyState == 'complete'): > time.sleep(0.1) I realized I might need to add a little more code to give this better context; here's some additional functions I use: def Navigate(ie, url): ie.Navigate(url) while ie.Busy: time.sleep(0.05) doc = ie.Document WaitForDoc(doc) return doc def HasLink(obj, pattern): 'Returns matching link or None. obj does not have to be a document' pattern = pattern.lower() try: links = obj.Links except AttributeError: links = obj.all.tags('a') # Slower, but works for non-doc objs for i in range(links.length): link = links[i] if fnmatch.fnmatch(link.href.lower(), pattern): return link return None def ClickLink(obj, pattern, delay=0): 'Clicks on the first link that matches the text pattern. obj can be non-document object' link = HasLink(obj, pattern) assert link, 'No such link in document' link.Click() try: doc = obj.document except AttributeError: doc = obj WaitForDoc(doc, delay) def CreateInstance(isVisible): ie = win32com.client.DispatchEx('InternetExplorer.Application.1') doc = Navigate(ie, 'about:blank') ie.Visible = isVisible if isVisible: # Hack alert! Make the window come to the foreground try: hwnd = win32gui.FindWindow(None, 'about:blank - Microsoft Internet Explorer') if hwnd: win32gui.SetForegroundWindow(hwnd) except pywintypes.error, e: print e return ie Sample usage: ie = CreateInstance(1) doc = Navigate(ie, 'http://www.google.com') doc.f.q.Value = 'python' doc.f.Submit() WaitForDoc(doc) -Dave From max at alcyone.com Thu Jul 18 19:25:31 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 Jul 2002 16:25:31 -0700 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <3D374E6B.2E964604@alcyone.com> OtisUsenet wrote: > Python newbie question. How does one do something like this in > Python: > > # assign the value of j to i and then increment j by 1 > i = j++ j += 1 # or j = j + 1 for Python < 2.0 i = j -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From aleax at aleax.it Sun Jul 7 10:19:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 14:19:51 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <3D282413.1010801@ob_scure.dk> Message-ID: Thomas Jensen wrote: > Alex Martelli wrote: >> >> If you have substantial numeric computations to perform on large >> arrays, you're almost surely better off using the Numeric package >> to extend Python, particularly if performance is an issue. > > http://www.pfdubois.com/numpy/ ? > It looks just like what I need! It's indeed a wonderful tool for computations on large arrays, vastly extending Python's applicability to scientific applications. > Thanks! You're welcome! I take advantage of the occasion to mention that Paul Dubois is among the nominees for the "Programmers' Choice" award, http://www.activestate.com/Corporate/Awards/ActiveAwards.html (so am I, but I never contributed to Numeric!-), open for everybody to vote until July 17. If you find Numeric the best thing since sliced bread, visiting the site and voting for Paul might be a nice way to signal your appreciation. Alex From peter.bittner at gmx.net Wed Jul 31 17:17:00 2002 From: peter.bittner at gmx.net (Peter Bittner) Date: 31 Jul 2002 14:17:00 -0700 Subject: 'import mod_python' fails Message-ID: <158d3913.0207311316.6e2b3e7b@posting.google.com> Hi there! I have a question about getting mod_python to run. (Please do not flame me, I know there is a mod_python mailing list!) I have SuSE Linux 8.0 and I have Python, mod_python and Apache installed using YaST, the SuSE setup tool. At the first glance everything seems alright (Apache shows at startup that it does load the mod_python module.) But I can .py-scripts be executed, because (mod_)python fails to import the Python module 'mod_python': > >>> from mod_python import apache > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named mod_python I don't know if this helps, but I have searched my whole system and there is no file named 'mod_python.pyo' anywhere! I'd really be happy about any help to make me get running mod_python on my Apache! Please help! Cheers, Peter From rpm at wag.caltech.edu Tue Jul 2 14:54:45 2002 From: rpm at wag.caltech.edu (Rick Muller) Date: Tue, 02 Jul 2002 11:54:45 -0700 Subject: Thanks to the distutils dev team! References: Message-ID: <3D21F6F5.4090606@wag.caltech.edu> I finally got a chance to play around with building python modules using the distutils package (only about two years after they came out with the package, which is remarkably up to date for me). I'd like to thank everyone who worked on the package -- really is remarkable and professionally done. To think that I can just type 'python setup.py build' and get working modules on every platform I own! I had always been a Makefile kind of guy, and had figured that whoever came up with the distutils simply had too much time on their hands. But then, after having gotten an Apple OS X box to play with, and not being able to figure out all of the different flags that I was supposed to use to build modules, I rolled up my sleeves and learned how to make a setup.py script. Wonderful, and my sincerest thanks for the effort the team put into this. Rick From wurmy at earthlink.net Tue Jul 23 15:52:48 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Tue, 23 Jul 2002 19:52:48 GMT Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: Message-ID: <3D3DB42D.3080404@earthlink.net> Mack wrote: >>>>[elem*2 for elem in li] >>> > File "", line 1 > [elem*2 for elem in li] > ^ > is what i'm getting. Is my python too old? Is something else wrong? > I've just cut and pasted from the tutorial into python ide. That's a list comprehension, which wasn't available in 1.5.2. I think it first appeared in 2.0. Upgrading to a more recent Python version should fix this. -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 20:51:50 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 17:51:50 -0700 Subject: HTML DOM parser? References: Message-ID: <7x8z48czfd.fsf@ruckus.brouhaha.com> "David LeBlanc" writes: > I put the above code into "ienavigate.py" and tried it and got: > > Traceback (most recent call last): > File "ienavigate.py", line 6, in ? > dom = ie.document > File "J:\Python22\lib\site-packages\win32com\client\dynamic.py", line 448, > in __getattr__ > raise pythoncom.com_error, details > pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, > None, 0, -2147467259), None) > > Also got a browser window with a "403" error telling me I don't have > permission to access index.html on www.nightsong.com. > > I would be interested in getting this working, so any help is appreciated. The exception might be legitimate, because of the 403 error. Try www.yahoo.com instead of www.nightsong.com. www.nightsong.com really does return a 403. From maxm at mxm.dk Mon Jul 15 03:31:46 2002 From: maxm at mxm.dk (Max M) Date: Mon, 15 Jul 2002 09:31:46 +0200 Subject: Numarray vs Numpy References: <080720021452508286%pecora@anvil.nrl.navy.mil> Message-ID: <3D327A62.8060000@mxm.dk> Chris Liechti wrote: >>Are these compatible with the Numeric module? > > yes, as numpy _IS_ Numeric or vice-versa .... > one is the name of the distribution the other the name of the package when > you use it. Then Numarray is probably a bad name if the module is to be used outside the scientific comunity. regards Max M From shalehperry at attbi.com Thu Jul 11 11:52:07 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 11 Jul 2002 08:52:07 -0700 (PDT) Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: Message-ID: On 11-Jul-2002 Mark McEahern wrote: >> Although it's in the Humor section I take the Python Zen >> (http://www.python.org/doc/Humor.html#zen) quite seriously. >> However I can understand what does “Sparse is better than >> dense” means. > > Here's one of my pet peeves: > > if x: do_one_thing() > > or: > > try: foo() > except: pass > > The problem with collapsing these single statement blocks into one line is > that it complicates visual scans of a block of code. It certainly doesn't > make a hill of beans difference to the compiler. > It also guarantees the next coder will have to move the code around to add anything, even a debug print. Which generates overly large diffs. From phr-n2002b at NOSPAMnightsong.com Wed Jul 10 16:39:16 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 10 Jul 2002 13:39:16 -0700 Subject: try/finally question References: <7xd6twow3x.fsf_-_@ruckus.brouhaha.com> Message-ID: <7x3curfhcb.fsf@ruckus.brouhaha.com> Erno Kuusela writes: > | So the obvious way to use it is: > > | try: > | db.begin() > | x = db.do_action(first_thing) > | y = db.do_action(second_thing) > | db.commit() > | finally: > | db.cancel() > > | The trouble is db.cancel() is an ordinary method call--it's not atomic > | in the interpreter. It can be interrupted and blast out of the > | finally block before finishing, and then control returns to some > | higher level with the database still locked. > > would it be different from the an interrupt coming > at any point between the begin and the commit? If an interrupt comes between the begin and the commit, the idea is that the finally clause runs and db.cancel() releases the lock. > if you want to do database transactions in the > signal handler, you will probably get an error if you try to > begin() before closing the previous transaction, but that same > problem would be in the try block too. I don't want to do database transactions in a signal handler. I just want to run db.cancel (which discards the pending changes and releases the lock) atomically. > if you never call neither commit or cancel but just exit, the effect > in all the systems i have seen is effectively the same as calling > cancel. db here isn't a wrapper around a remote SQL connection. It's just something that serializes access to a dbm database in the same process. More generally though, this seems like a deficiency in Python. In Java I believe that this issue can be solved by a synchronized object, but Python doesn't have those. From shalehperry at attbi.com Tue Jul 23 11:16:49 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 08:16:49 -0700 (PDT) Subject: re.finditer In-Reply-To: <2259b0e2.0207230706.41ff60b@posting.google.com> Message-ID: > > $ python > Python 2.2.1 (#1, Apr 9 2002, 13:10:27) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import re >>>> re.finditer('r+?','library') > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'finditer' > > The command re.finditer is not recognized ! All the other commands > work, for instance > import re regex = re.compile(r'\s'+) dir(regex) ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] as you can see, finditer() is a method of a regular expression object and is not a generic function in the re module. This may still be a bug because it is handy to call regex's directly and not need to compile them. From tjreedy at udel.edu Thu Jul 11 21:35:29 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Jul 2002 01:35:29 GMT Subject: pygame question References: Message-ID: "Michael Bauers" wrote in message news:uis3ccnreo0u32 at corp.supernews.com... > I was curious as to why 'is K_SPACE' worked, but 'is K_r' did not. I had to > change the test for 'r' to ==. > > * code snippet * > elif (event.type is KEYDOWN and event.key is > K_SPACE): > # DO SOMETHING > elif (event.type is KEYDOWN and > event.key == K_r): > # DO SOMETHING ELSE I don't know about your question, but I do about eliminating redundant code 8-) I would redo as elif event.type == KEYDOWN: keyhit = event.key if keyhit == K_SPACE: #do x elif keyhit == K_r: # do y Should K_r be K_R? What was your error message? (ie, what does 'not work' mean?) Terry J. Reedy From K.Rdt at TU-Berlin.DE Mon Jul 1 05:31:12 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Mon, 01 Jul 2002 11:31:12 +0200 Subject: Europython pictures In-Reply-To: <9ZUT8.21128$l6.4303892@newsfep2-win.server.ntli.net> Message-ID: Am 01.07.02 11:07:17, schrieb Duncan Grisby : > http://www.grisby.org/Photos/085/ --------------------------------------------------------------------- Hi Nice, where is Duncan? -) K at Rdt --------------------------------------------------------------------- From wester at ilt.fhg.de Tue Jul 9 11:01:10 2002 From: wester at ilt.fhg.de (Rolf Wester) Date: Tue, 09 Jul 2002 17:01:10 +0200 Subject: Problems building a Python module References: <3D2AE97B.4020908@ilt.fhg.de> Message-ID: <3D2AFAB6.4070508@ilt.fhg.de> Hi Gerhard, thank you for your reply. ldd gave me the information I needed. Regards Rolf Gerhard H?ring wrote: > * Rolf Wester [2002-07-09 15:47 +0200]: > >>Hi, >> >>I want to build a Python module from C-files. I made the wrapper file >>using swig. During linking I get the following message: >>[...] >>/usr/lib/python2.2/config/libpython2.2.a(thread.o): In function >>`PyThread_start_new_thread': >>thread.o(.text+0x7f): undefined reference to `pthread_sigmask' >>[...] >> > > This wants to tell you that you should really use distutils to compile > your Python extension module instead. > > >>I link against following libraries: >> >>-lpython2.2 -lm -ldl >> >>Can someone tell me what other libraries I have to link against? And >>what means: >> > > ldd /path/to/your/python will tell you. > > >>posixmodule.o(.text+0x3614): the use of `tmpnam_r' is dangerous, better >>use `mkstemp' >> > > This is a warning from the linker that's emitted as soon as certain > functions are linked against. As long as you don't use these functions > in the tmpfile module, you can safely ignore this warning. > > Gerhard > From K.Rdt at TU-Berlin.DE Mon Jul 1 04:00:08 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Mon, 01 Jul 2002 10:00:08 +0200 Subject: stream to string-question Message-ID: --------------------------------------------------------------------- Hi y=os.popen( 'netstat -a -n','r').read() # Aktive Verbindungen # # Proto Lokale Adresse Remote-Adresse Status # TCP 0.0.0.0:1171 0.0.0.0:0 LISTENING # TCP 130.149.164.212:1171 130.149.4.11:110 ESTABLISHED print y for i in y: print "--------: ", i The last is outputting each character in a single line. Is there a function to convert this stream in the text-rows? K at Rdt --------------------------------------------------------------------- From lac at strakt.com Mon Jul 8 12:11:57 2002 From: lac at strakt.com (Laura Creighton) Date: Mon, 08 Jul 2002 18:11:57 +0200 Subject: Python 2.1 == Jython 2.1 != Python 2.2? In-Reply-To: Message from Gustavo Cordova of "Mon, 08 Jul 2002 10:56:23 CDT." References: Message-ID: <200207081611.g68GBvci011029@ratthing-b246.strakt.com> > > > > > If so, is there an ETA on Jython 2.2? > > > > What is an ETA? > > > > Regards, > > Martin > > > > ETA == "Environmental Turnover Announcement" > > Typo prolly. > > ;-) > > -gus I think he wants Estimated Time of Arrival -- i.e. when can he get his hands on Jython 2.2 Laura From aleax at aleax.it Sat Jul 6 13:35:48 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Jul 2002 17:35:48 GMT Subject: Understanding properties References: Message-ID: merman wrote: >> class MyObject(object): > > Why it needs the inheritance from object - I don't understand. Backwards compatibility. To be precise, a class using properties needs to be new-style -- subclassing object is the simplest way to achieve this (there are quite a few others) -- because by default a class is a "classic" one, implementing exactly the same semantics as in Python 2.1 and older, ensuring no major code breakage in porting from 2.1 to 2.2 but constraining the applicability of the new features to classic classes. Alex From emile at fenx.com Wed Jul 24 08:52:12 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 24 Jul 2002 12:52:12 GMT Subject: crc32 with wintel files References: <7cgrjukbcu3piev8mn1uuc94g104pu9d9n@4ax.com> Message-ID: <0qx%8.19503$uh7.4074@sccrnsc03> Chris Hartemink > I'm trying to create crc32 checksums for files, not strings. > zlib has a crc32 function and google is your friend. http://groups.google.com/groups?threadm=3c355398$1_1 at nopics.sjc -- Emile van Sebille emile at fenx.com --------- From ods at fep.ru Tue Jul 16 07:05:01 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Tue, 16 Jul 2002 15:05:01 +0400 (MSD) Subject: Newbie: Capture output of compile_dir In-Reply-To: <20020715210428.52622.qmail@web13001.mail.yahoo.com> Message-ID: On Mon, 15 Jul 2002, Becky Hehn wrote: BH> Thanks for the response. I tried the code you gave BH> me, but it didn't quite work like I wanted. I created BH> a syntax error in my python file (left out a quotation BH> mark) and tried the code. Below is the information BH> from my interpreter session: [...] BH> If an the prompt I just type the compile command, I BH> get all the output at once(see below). I would like BH> the output variable to contain all this feedback from BH> the compile_dir command. Not just the initial two BH> lines. Any thoughts on what I did wrong? Thank you BH> in advance. Informational messages from compile_dir go to stdout and error messages go to stderr. You should redefine both. orig_so = sys.stdout orig_se = sys.stderr sys.stdout = sys.stderr = captured = StringIO() ... -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From nntp at ebusinessresults.com.au Tue Jul 2 00:00:46 2002 From: nntp at ebusinessresults.com.au (Stephen Tyler) Date: Tue, 02 Jul 2002 14:00:46 +1000 Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: <3d21259f$0$28006$afc38c87@news.optusnet.com.au> Bengt Richter wrote: > E.g., if you were hoping for an improvement over current practice, > which do you consider to be the tool(s) to beat, and what would > the killer improvement(s) be? TIA. Well, there are more parties involved than just designer and coder. What about content providers (authors, illustrators), database administrators and management (project managers etc). They also play an important role, and their productivity is affected by the choice of web templating/db tools. Most of the web templating debate focuses on the separation (or otherwise) of the programming code (python) and the markup code (HTML). Most solutions are variants of: Python code ----- New programming language \ / \ / HTML [That is meant to be a triangle] where "New programming language" is some kind of intermediate execution model (loops, conditionals) that is supposedly easier for non-coders to embed (or leave alone) in their HTML. A simple "include" mechanism whould be on the Python-HTML axis, very close to the HTML end. Echo statements in Python is a point very close to "Python code". And most of the web templating solutions trend towards either defining a new programming language, or a way to embed Python in HTML. But, as the new programming language becomes more expressive, it tends to become yet-another-PHP, and becomes yet another thing to mystify the non-coders, and another way to write obfuscated code for the coders. Code should be written in an efficient code for coding (eg Python). And likewise for the other elements (but I will stop short of saying that HTML is an efficient code for markup). In my view, the next generation of web templating/db tool needs to move beyond the issue of python/HTML separation and start solving some higher level issues: - Reuse (both of code, markup and content) - Authorisation and security - Higher level structures (forms, tables, lists, trees, navigation should be handled and manipulated at an abstract level, rather than as a mess of HTML markup) - Consistency and style (the "style" of the site should be able to be changed across an entire site by making small changes to a small number of items in a small number of places - and my definition of style is much broader than just CSS) - Configuration management (Can we revert to the previous version if the change is not working properly? Can we test the new version on particular users (or classes or users) before fully commiting to the new version? Can we track changes to the system?) Just take the example of form handling: You have certains fields in certain tables in your database. And you want the user to be able to change those fields. This is a pretty simple requirement, yet the solution in most web templating systems is pretty complex: - is the user authorised to view, change, or create this record? - how do we verify the integrity of the user input for each of these fields? For things like range checks, to date validation, email validation and dependencies on other fields. - how do we notify the user of errors in user input? - how do we notify the user of errors in authorisation? - how do we notify the web administrator of errors? - how do we label these fields? If the label needs to be changed or localised, where do we make those changes? - how do we access these fields? Do we have to write an SQL query for this (and every other) data access? Or can the templating system generate the appropriate efficient SQL query? - How do we save the results back to the database? How do we cope with results spread across different tables? Can the templating system generate the appropriate efficient SQL query? What about transactions? Now in my view, all the templating systems I have seen turn this "simple" exercise into a fairly complex code. And 99% of the time, the implementations of this code ignore several important steps in the process. And 99% of the time, the code has to be reimplemented for every new form that is required. In my view, Zope (with suitable add-ons) comes closest to meeting these goals. But it is not without its problems: - It has strong links to a non-standard database. Support for commonly deployed enterprise databases (Oracle et al) is relatively weak (but that is not to say that it is strong in other python-based systems) - It has a version control system, but this is not well integrated with other version control systems (eg CVS) - It is difficult to integrate with non-Zope workflow processes usable by non-coders - Zope also strongly influences the http-server choices, yet it is not clearly superior to other http-server alternatives. - Zope has a mean learning curve. You can't just walk up to it and become productive from day one. You need good documentation and examples (which used to be very difficult to find). The other contenders for my "next-generation" web templating system typically use XSLT to transform a variety of XML inputs into XHTML output. But XSLT can be very obtuse for non-coders (and even coders). And it still needs to be supplemented with a general-purpose programming language. For my own code, I have developed a number of libraries over the years to solve these problems. But they have all fallen somewhat short of my goals in one or more ways (too complex, too specific, inefficient, obtuse or missing functionality). But I keep trying. Good luck in your search, Stephen Tyler www.ebusinessresults.com.au From shalehperry at attbi.com Mon Jul 29 17:00:20 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 29 Jul 2002 14:00:20 -0700 (PDT) Subject: Python design failures (was Re: Let's Talk About Lambda Func In-Reply-To: <20020729135546.D31926@glacier.arctrix.com> Message-ID: On 29-Jul-2002 Neil Schemenauer wrote: > Sean 'Shaleh' Perry wrote: >> I could submit a patch for the repr cleanup in pretty short order. > > Guido's not big on this kind of "hit and run" cleanup. He prefers it if > someone looks at the entire module while modernizing it. Keep in mind > though, I'm an amateur when it coming to channelling the BDFL and he > might tell you differently himself. > > Neil That is a reasonable attitude. Comments from the direct python hackers? Would more work on the lib be welcomed? Do we want the standard library to be a good example of python best practices? (sorry i know that sounds like a loaded question). From borges at let.rug.nl Wed Jul 31 03:25:22 2002 From: borges at let.rug.nl (Francisco Borges) Date: Wed, 31 Jul 2002 09:25:22 +0200 Subject: alternatives to getopt? Message-ID: Hi all, I've just started using getopt and I'm not very fond of it. Is there a better alternative to it? thanks! -- Francisco From phr-n2002b at NOSPAMnightsong.com Tue Jul 30 17:50:47 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 30 Jul 2002 14:50:47 -0700 Subject: global interpreter lock not working as it should References: Message-ID: <7xofcoopfs.fsf@ruckus.brouhaha.com> brueckd at tbye.com writes: > When you get right down to it, there's really *little* difference between > Python threads and C threads, so the above statement doesn't make too much > sense to me. Sure the GIL makes sure that Python object internals are > fiddled with one thread at a time, but if you have only 1 CPU, there's > only one thread running at a time anyway, regardless of whether your > program is in C or Python. IOW, the GIL has no real effect on the > applicability or usefulness of threads (assuming a single CPU). But that is precisely the gripe about the GIL. If you have multiple CPU's, you can use them with C threads but not with Python threads. From just at xs4all.nl Tue Jul 23 11:42:13 2002 From: just at xs4all.nl (Just) Date: Tue, 23 Jul 2002 17:42:13 +0200 Subject: re.finditer References: Message-ID: In article , "Sean 'Shaleh' Perry" wrote: > > > > $ python > > Python 2.2.1 (#1, Apr 9 2002, 13:10:27) > > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import re > >>>> re.finditer('r+?','library') > > Traceback (most recent call last): > > File "", line 1, in ? > > AttributeError: 'module' object has no attribute 'finditer' > > > > The command re.finditer is not recognized ! All the other commands > > work, for instance > > > > import re > regex = re.compile(r'\s'+) > dir(regex) > ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', > 'search', 'split', 'sub', 'subn'] > > as you can see, finditer() is a method of a regular expression object and is > not a generic function in the re module. This may still be a bug because it > is > handy to call regex's directly and not need to compile them. I think the reason is that "finditer" is not listed in sre's __all__ attribute, so it doesn't get exported to re. Just From rajarshi at presidency.com Thu Jul 4 12:02:52 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Thu, 04 Jul 2002 16:02:52 GMT Subject: testing a sequence for 'identicalness' Message-ID: Hi, does anybody knwo how I can check a sequence for 'identical ness', ie given a sequence: [1,1,1,1,1,1,1,1,1,1] it would be classified as 100% identical and [1,1,1,1,1,1,1,1,1,2] would be classified as 90% identical. TIA, From pinard at iro.umontreal.ca Mon Jul 8 18:42:51 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 18:42:51 -0400 Subject: stackless python In-Reply-To: <20020708124540.A5014@glacier.arctrix.com> References: <20020708102618.A4681@glacier.arctrix.com> <20020708124540.A5014@glacier.arctrix.com> Message-ID: [Neil Schemenauer] > Fran?ois Pinard wrote: > > (My main question, maybe already answered in there -- I did not check yet > > -- is how one proceeds to `yield' from within a nest of function calls, > > and to later kludge resuming the function nesting sequence on `.next()'.) > You can't since only one stack frame is saved per generator. That's why > one of the reasons they are called simple generators (two others being > ease of implementation and of understanding). You probably want to look > at stackless Python if you haven't already. I'm aware of Stackless, of course, yet I prefer to stick to standard Python if possible. My need for "non-simple" generators is not at all serious at this stage. Since it has been in previous projects, it is likely to be in future projects, and I merely wanted to foresee problems and solutions in an informal way, while looking at Python generators. Maybe one could find how to chain generators in the same way one nests functions, with some idiomatic writing for moving back and forth along the chain. Most probably, I'll try a bit harder if I ever have a real, immediate need. :-) Stackless is a always there, too! Thanks for the help you provided already. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From raims at dot.com Sun Jul 14 16:06:25 2002 From: raims at dot.com (Rhymes) Date: Sun, 14 Jul 2002 22:06:25 +0200 Subject: python2 import trouble (linux - redhat) References: Message-ID: <7bm3juov83ledl8r304gpbfmjnnh4mpoj0@4ax.com> On Sun, 14 Jul 2002 14:17:57 -0400, Mike Mellor wrote: >I am having trouble importing modules with python2 (Python 2.2) that I think should be >there, for example, _gtk and GTK. What do I need to do to get >python (actually python2) to import these modules? What kind of problems? Does the import statement failes? However, take a look at your PYTHONPATH environment variable and check if the pygtk lib directory is listed there -- Rhymes rhymes at myself.com " ride or die " From robert_kuzelj at yahoo.com Wed Jul 3 15:45:48 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 3 Jul 2002 12:45:48 -0700 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: > I guess the reason why Robert feels better /protected/ when he doesn't say > it in /public/ is that he's used to languages like Java. At least I heard > so in /private/ ;-) ooh, you fool! ;-) now i am discovered. what im experimenting with at the moment is a sort of typing system for python . ciao robertj From dr.t.huebner at gmx.de Thu Jul 18 09:27:25 2002 From: dr.t.huebner at gmx.de (Dr. Thomas =?iso-8859-1?Q?H=FCbner?=) Date: Thu, 18 Jul 2002 15:27:25 +0200 Subject: Help with win32ui.CreateFileDialog Message-ID: <3D36C23D.A487E18A@gmx.de> Hi, I am running into a problem with win32ui.CreateFileDialog during the selection of multiple files. I am successful in selecting files only up to a certain number. The number depends on the length of the path, e.g. selecting files from "E:\Dokumente und Einstellungen\thomas\Eigene Dateien\GP\kunden\tracker\" works up to 7 file, doing the same for "E:\temp" doesn't break until 10+ files. Here is the code I use: def test(): import win32ui, win32con dlg = win32ui.CreateFileDialog(1, None, None, (win32con.OFN_FILEMUSTEXIST| win32con.OFN_EXPLORER| win32con.OFN_ALLOWMULTISELECT), 'all (*.log)|*.log||') dlg.SetOFNTitle('Image to Print') testvalue = dlg.DoModal() if testvalue == win32con.IDOK: print "did get IDOK", testvalue print dlg.GetPathNames() else: print "did not get IDOK", testvalue print dlg.GetPathNames() def main(): # Get Logfile test() if __name__ == "__main__": main() Example output, that I get up to 7 files: >>> import Script2 >>> Script2.main() did get IDOK 1 ['E:\\Dokumente und Einstellungen\\thomas\\Eigene Dateien\\GP\\kunden\\tracker\\Kopie (4) von unix.log', ... a.s.o. and the one that I get from 8 files upwards: >>> Script2.main() did not get IDOK 2 ['-\x01'] >>> Any ideas to get past the limit? By the way I am using Python 2.1 and About PythonWin calls itself win32all build 145 Txs for your help Thomas -- Thomas H?bner dr.t.huebner at gmx.de From fperez528 at yahoo.com Thu Jul 25 17:53:49 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 25 Jul 2002 15:53:49 -0600 Subject: Completion in emacs mode References: Message-ID: Sandy Norton wrote: >> http://www.geocrawler.com/archives/3/338/1993/12/0/1878323/ > > Useful enough link except for the fact that a portion of the code is > missing from the post due to some cut-and-paste mishap. Subsequently, > a couple of nice fellows try to salvage the problem by providing diffs > of the emacs extension... > > Given that we are now in dodgy waters, is there an alternative to this > route? (perhaps post a complete version of the extension here :-) Well, as far as I can tell, my current XEmacs (21.1, stock in RedHat 7.2) does all this. Considering that this post is from 1993 and we are in 2002, I wouldn't be all that surprised if those enhancements have percolated already to the core tree. Cheers, f. From rajarshi at presidency.com Thu Jul 18 11:04:50 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Thu, 18 Jul 2002 11:04:50 -0400 Subject: smtplib and passwd's Message-ID: Hi, I'm using smtplib to let my script send some mail through my smtp server. Howveer I need a logon and passwd for my smtp server - how does smtplib handle such servers? Where can I specify my username and password? TIA From BPettersen at NAREX.com Sun Jul 21 17:03:14 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Sun, 21 Jul 2002 15:03:14 -0600 Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192012527FF@admin56.narex.com> > From: Fredrik Lundh [mailto:fredrik at pythonware.com] > > Alex wrote: > > > I do hope Ascher and Lundh find the time to update "Learning" to 2.2 > > very soon, of course.' > > Ascher and Lutz. > > Lundh is busy updating and expanding "Library" for 2.2/2.3. Argh, and here I just bought the current version last week for our CTO -- he wanted a book to teach him how to _use_ Python, I figured this one was the best I've read so far (I still have the print-out of my old e-book copy :-) Any idea what timeframe we can look for the next edition? -- bjorn From never at mind.info Mon Jul 15 07:31:00 2002 From: never at mind.info (G. Willoughby) Date: Mon, 15 Jul 2002 12:31:00 +0100 Subject: Getting an error when quitting an app using a call 'self.master.quit'? References: Message-ID: > which Python version, versions of extension modules and where you got them. > And if these were built in debug mode, and the stripped (or whatever the > Windows equivalent of that is). ActiveState Python 2.1 (#15, Jun 18 2001, 21:42:28) with PIL installed. This problem happens with every call to self.master.quit in all my programs :( --G. Willoughby From t.gawantka at freenet.de Tue Jul 30 16:19:21 2002 From: t.gawantka at freenet.de (Thorsten Gawantka) Date: Tue, 30 Jul 2002 22:19:21 +0200 Subject: wxTextCtrl + wxGrid References: Message-ID: On Tue, 30 Jul 2002 12:19:41 +0200, Steve Holden wrote: > You probably want to *call* the GetValue method of the wxTextCtrl rather > than referring to it. It's a mistake most have made ... try > > self.grid.SetCellValue(i, 0, self.edit_p1.GetValue()) > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > ----------------------------------------------------------------------- Thanks that help -- mfg Thorsten Gawantka From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 25 12:48:31 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 25 Jul 2002 16:48:31 +0000 Subject: Jython newbie question In-Reply-To: <3D401577.65D61189@ingenta.com> References: <3D401577.65D61189@ingenta.com> Message-ID: <200207251548.g6PFmV020491@helios.gatwick.geco-prakla.slb.com> On Thursday 25 Jul 2002 3:12 pm, Christopher Myers wrote: > I just downloaded Maxq (http://www.bitmechanic.com/projects/maxq/) > > (etc . . .) I forgot to add that as of python 2.0 (and Jython 2.0) you don't need the string module for anything apart from obscure (IMHO) methods as string objects have methods: >>> "aaaaa".upper() 'AAAAA' >>> _.lower() 'aaaaa' >>> ",".join('abcdefg') 'a,b,c,d,e,f,g' etc..... Martin From jhalttun at pp.htv.fi Tue Jul 23 10:01:53 2002 From: jhalttun at pp.htv.fi (janne halttunen) Date: Tue, 23 Jul 2002 17:01:53 +0300 Subject: curses and terminal resize Message-ID: <3D3D61D1.8010600@pp.htv.fi> Hello all, I am writing a curses widget library. The trouble I am having is to obtain new values for lines and columns in terminal after resize event. I have a short program below that should demostrate the problem: """curses window resize test program. ctrl-c to exit""" import curses import signal def main(w): w.nodelay(1) count=0 def handle(*args): w.erase() w.addstr(0,0, str(count)+str(w.getmaxyx())) signal.signal(signal.SIGWINCH, handle) handle() # to get the initial values while 1: count+=1 w.refresh() if __name__=='__main__': curses.wrapper(main) # EOF If you run this in a xterm, you will see that the screen dimesions remain the same after every resize. I have tried calling curses.initscr again, but to no avail. Also the curses.tigetnum for 'lines' and 'cols' always return the same values. $ python -V Python 2.2 $ python -c 'import sys; print sys.platform' linux-i386 Any help is appreciated, janne From b.hall at irl.cri.nz Wed Jul 31 02:40:31 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Wed, 31 Jul 2002 18:40:31 +1200 Subject: A generic question: idiom for a paramterized base class? References: <3D47042E.33823879@irl.cri.nz> Message-ID: <3D47865F.67E8D20D@irl.cri.nz> Perhaps this is the answer to my question. Any comments? I can use execfile(), instead of import, to bring the base class into context. i.e.: #### base.py class GenericBase(object): def __iadd__(self,other): return TAdd(self,other) # Problem!! def __add__(self,r): return GenericBase.__iadd__(self,r) def __radd__(self,l): return GenericBase.__iadd__(l,self) #### new file example.py execfile("base.py") # One type of TAdd: class TAdd(object,GenericBase): def __init__(self,l,r): print "TAdd instance" class TNode(object,GenericBase): def __init__(self): print "TNode instance" It works: >>> import example >>> x = example.TNode() TNode instance >>> y = example.TNode() TNode instance >>> t = x + y TAdd instance But is it 'good' (or at least acceptable) Python?! From edream at tds.net Wed Jul 10 10:49:33 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 10 Jul 2002 14:49:33 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> <3D2C432E.5FEDD75E@tds.net> Message-ID: <3D2C497A.93C73ABE@tds.net> > > I've no idea about Tkinter at all, but this should accomplish what you > > need: > > > > command=lambda: self.myCallback(val) > > Thanks very much. That did the trick. I've been wondering how to > define lambda expressions with no args ;-) I spoke too soon. This does _not_ work. All the callbacks get bound to a callback that uses the last val in the list. Alex's way _does_ work. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From aleax at aleax.it Wed Jul 10 09:48:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 13:48:47 GMT Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> Message-ID: <3XWW8.64416$vm5.2344638@news2.tin.it> Wolfgang Draxinger wrote: ... >> For getting rid of builtin functions, why bother? > > Because some of them can mess up all. I know what I'm talking about. > I should have said, getting rid of all where it is possible and > replacing the rest with custom stuff at a low level base. What you choose to expose to client scripts as "builtins" is entirely under your control. This is exactly what the rexec module is all about -- controlling what builtins, names from sys, names from os, and built-in modules, are made available to untrusted scripts. Subclass rexec.RExec appropriately and use an instance of your class to build the "sandbox" in which the untrusted scripts execute -- building the sandbox includes possibly populating it with your supplementary or replacement builtins etc, of course. Alex From robin at jessikat.fsnet.co.uk Wed Jul 10 03:47:28 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 10 Jul 2002 08:47:28 +0100 Subject: PDf creating with Python? Howto? References: <3D2BE41E.3040508@weknowthewayout.com> Message-ID: In article <3D2BE41E.3040508 at weknowthewayout.com>, Johan Holst Nielsen writes >Hi people, > >Im right now beginning a project where I have to make a generator to PDF >files. It includes images, and fonts (thats not are embedded in the >Adobe PDF specification). > >It have to be used for Offset printing, so all images must have a >resolution about 304 dpi. > >Anyone know tutorials or libraries in Python that can help me with this >project? > >Regards, > >Johan Holst Nielsen > you might get some help from the ReportLab project, try emailing andy at reportlab.com or the users list reportlab-users at reportlab.com. The ReportLab toolkit tries to do exactly what you describe. -- Robin Becker From pinard at iro.umontreal.ca Wed Jul 17 13:38:26 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 17 Jul 2002 13:38:26 -0400 Subject: get a list printed in hexadecimal notation In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C8D@hendrix.empolisuk.com> References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C8D@hendrix.empolisuk.com> Message-ID: [Harvey Thomas] > print [type(x) == type(1) and hex(x) or x for x in l] A tiny detail. I guess that `type(x) == type(1)' is better written `isinstance(x, int)' under Python 2.2. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From dswegen at software.plasmon.com Mon Jul 22 09:36:10 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Mon, 22 Jul 2002 14:36:10 +0100 Subject: Webmin-alike cgi script and security Message-ID: <20020722133609.GB2610@software.plasmon> I'm currently looking at writing a set of cgi scripts that will perform similiar functionality to webmin (i.e. system configuration and running various processes as root) for configuring an embedded system. Now I know that this is a can of worms, but I would appreciate some feedback on my current line of thinking: The scripts themselves are run as the default webserver user, and take care of stuff like authentication and basic sanity checking. If all input checks out an external script is called using sudo to gain root privs. Any data that should be provided is pickled and stored in a file with a unique name, which is then the only argument to the sudo'ed script. Depending on the return value any return data is picked up again by the cgi script from a pickled data structure with the same name. All web traffic goes over SSL (using self signed certs, which at least encrypts traffic), possibly using the cookie scheme described at http://www-106.ibm.com/developerworks/library/secure-cgi/ For this project I have the luxury of only targeting later browsers which talk HTML 4.0 (i.e mozilla & co and later IEs). So, given the task, is this a reasonable way of going about it, or are there any screamingly obvious holes? Cheers Dave From jonathan at onegoodidea.com Fri Jul 12 12:20:46 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 12 Jul 2002 17:20:46 +0100 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: Message-ID: On 12/7/2002 15:37, Fran?ois Pinard wrote: >> You might say that this is verbose and monstrous, > > Your wish is my command. This is verbose and monstrous! :-) > >> but it's readable and fairly obvious in meaning. > > The original non-XML format is also pretty readable and obvious in meaning. > Surely, there are advantages to XML, but at first glance here, it seems we > gain nothing but verbosity and monstrosity. In my opinion, the advantages > have to be pretty real to justify such a change. We should not go XML > for the only sake of going XML. I had thought I'd given arguments and examples as to why the XML was more useful in the rest of the post, but perhaps I wasn't as clear as I thought I had been. To summarise the advantages of using XML as I see them: * Standardised parsing (PyXML etc.) * Standardised validation (DTDs, XSchema) * Standardised editing (XML-aware editors) * Standardised querying (XPath, XQuery) * Standardised transformation (XSLT) * Standardised storage (XML:DB) I really am willing to eat humble pie here and admit that I'm mistaken if someone can give me a similar list of good reasons to *not* use XML for off-line hierarchically structured data. Like I said before, I can spend time trying to think of a structured file format for each application I work on, or I can just use an XML schema. Thanks to batteries-included parsers it's easy to read and write, the data is readily re-purposed for other uses, and I get syntax highlighting and basic syntax checking in my editor. At a later date I can easily shift to using an XML database instead of XML files. Perhaps I'm missing something blindingly obvious here, but what benefits would I gain from coming up with my own format? [Other than people who have some kind of allergic reaction to XML would like it more.] Jonathan From tgrogan at datamarksystems.com Wed Jul 24 14:12:44 2002 From: tgrogan at datamarksystems.com (Terry Grogan) Date: Wed, 24 Jul 2002 14:12:44 -0400 Subject: Numeric data question In-Reply-To: References: Message-ID: Thanks Alex. Probably, typeless was not the right word. You have given me hope and direction. terry >> >> > I'm guessing now (from lack of real experience) that being >> > a 'typeless' language that I would be forced into >> > contriving a method for handling money such that I could >> > never code something straightforwardly like: >> > TotalCost = Quantity * UnitCost >> > (where Quantity is integer and the others money). >> >> If you were working with a typeless language, that might be >> the case. >> >> Fortunately, Python is strongly typed, so that's no problem, >> of course. This statement would probably be equivalent to >> something like: >> >> TotalCost = type(UnitCost).__rmul__(Quantity( >> >> for example (or UnitCost.__class__.__rmul__ if UnitCost was >> an instance of an old-fashioned class, but that comes to much >> the same thing). Just code your __rmul__ (and __mul__, etc) >> methods and voila, whatever numeric type you want is there. >> >> http://starship.python.net/crew/aahz/Decimal.py is an >> example, though Aahz still doesn't consider it finished. >> >> > Am I loonie, or is Python just not inherently suitable for >> > accounting applications for this reason? >> >> If you're saying that Python is "typeless", then I guess >> "loonie" might be applicable, yes. >> >> >> Alex -- Terry Grogan Datamark Systems 703-975-6250 From steven_shaw at adc.com Tue Jul 2 21:37:31 2002 From: steven_shaw at adc.com (Steven Shaw) Date: 2 Jul 2002 18:37:31 -0700 Subject: is attribute access a hash-lookup by name? Message-ID: <66715c02.0207021737.b488f07@posting.google.com> As I understand it, in Python, an object is an associative array or hash. I imagine this means that every attribute access is a hash-lookup by name. Does the implementation optimise this away somehow? Is there a way to have structs/records in Python where the members of the struct are looked up by offset (not by name)? From martin at v.loewis.de Thu Jul 11 03:02:26 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Jul 2002 09:02:26 +0200 Subject: How to replace multiple-line text References: <3D2D0782.45FCEC98@bellatlantic.net> Message-ID: Alex Martelli writes: > Not sure what regular expressions would have to do with the case. > I see it as a case of bunching. Matching multiline text, as long > as you manage to get it in memory, is just as easy with string > operations as with re's if it's an exact match you're lookin for -- > re's would be useful if you needed more sophisticated matching, > but they still need the file's contents to be in memory. My suspicion is that David is not looking for an exact match - but he did not provide enough detail to tell. Regards, Martin From duncan at NOSPAMrcp.co.uk Wed Jul 24 07:22:19 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 24 Jul 2002 11:22:19 +0000 (UTC) Subject: Make me beautiful (code needs help) References: Message-ID: [posted and mailed] Mark wrote in news:HVd%8.6582$I4.1825 at nwrddc03.gnilink.net: > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] > > That is, I want to get the successive differences into their proper > place. I don't care what is in the question mark spot. I'll figure > that out later. How about this? >>> from __future__ import generators >>> def adjacent(it): it = iter(it) value = it.next() for value2 in it: yield value, value2 value = value2 >>> a = [1, 2, 4, 10, 50] >>> print [ q-p for p,q in adjacent(a)] [1, 2, 6, 40] >>> -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From fakeaddress at nowhere.org Tue Jul 30 23:33:03 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 31 Jul 2002 03:33:03 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: <3D475AB5.2060207@nowhere.org> Ian Bicking wrote: > I've seen people argue that you can do all the same things with > iterators as Smalltalk does with code blocks. And, really, it's not as > though Smalltalk has truly novel control structures -- everything still > boils down to while, for, and if. Decades before anyone implemented a programming language, Alonzo Church boiled all the control structures down to just one: lambda. --Bryana From ld at nospam.com Sun Jul 14 16:29:13 2002 From: ld at nospam.com (Larry) Date: Sun, 14 Jul 2002 20:29:13 GMT Subject: List to STR to List Message-ID: I can convert a list to a string as follows: List1 = [1,2,3] String1 = str(L1) Is there now a way to convert my String1 variable back into a list??? From russblau at hotmail.com Sat Jul 6 08:33:04 2002 From: russblau at hotmail.com (Russell Blau) Date: Sat, 6 Jul 2002 08:33:04 -0400 Subject: problems with a for loop (noobie) References: <1IsV8.42194$Fc1.850199@wagner.videotron.net> Message-ID: "Charles Mantha" wrote in message news:1IsV8.42194$Fc1.850199 at wagner.videotron.net... > Reading the Python Tutorial by Guido van Russom and there's an example that > I don't get, and seems to not be explained (at least not enought for me). > > >>> for n in range(2, 10): > ... for x in range(2, n): > ... if n % x == 0: > ... print n, 'equals', x, '*', n/x > ... break > ... else: > ... # loop fell through without finding a factor > ... print n, 'is a prime number' > ... > ps : and for some reason, the output is not the same as in the tutorial when > I try this. This is kind of hard to explain if we don't see the output that you saw. Are you certain you typed it exactly as it appeared in the tutorial (including indentation)? From john.abel at pa.press.net Wed Jul 10 04:02:26 2002 From: john.abel at pa.press.net (John Abel) Date: 10 Jul 2002 09:02:26 +0100 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <003b01c2276f$1aae7850$bd5d4540@Dell2> References: <003b01c2276f$1aae7850$bd5d4540@Dell2> Message-ID: <1026288146.20796.63.camel@lestat.howden.press.net> The revised server code, looks like this: import sys, os, gzip, smtplib, SimpleXMLRPCServer, string class AuthenticatingSimpleXMLRPCRequestHandler (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): UnknownIP = 'Error' def _dispatch( self, method, params ): print "client_address %s:" % self.client_address if self.client_address not in ["144.178.233.83","144.178.234.189", "localhost"] : raise UnknownIP, "Client IP Is Not Authorised" else: SimpleXMLRPCServer.SimpleXMLRPCRequestHandler._dispatch( self, method, params) def GetFiles(FileRequest): print FileRequest RetrFile = open(FileRequest,"r") FileContents = "Not Found" for FileLine in RetrFile: if FileContents == None: FileContents = FileLine else: FileContents = FileContents + FileLine return FileContents if __name__== "__main__": XMLRPCServer = SimpleXMLRPCServer.SimpleXMLRPCServer ( ("127.0.0.1",8000), AuthenticatingSimpleXMLRPCRequestHandler ) XMLRPCServer.register_function(GetFiles) XMLRPCServer.serve_forever() Thanks again for your help and patience. Regards John From andrewm at object-craft.com.au Wed Jul 17 00:11:33 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 17 Jul 2002 14:11:33 +1000 Subject: map del efficiency python2.2 and 2.1 In-Reply-To: Your message of "Tue, 16 Jul 2002 23:54:43 -0400." Message-ID: <20020717041133.2407C38F61@coffee.object-craft.com.au> >This is exactly the kind of "seemingly random disaster" we see when the >platform free() goes nuts, although it's usually much more pronounced than a >measly factor of 2. If so, rebuilding with pymalloc is likely to fix it, >while if you don't you'll never answer "why?" without a deep understanding >of your platform C's implementation of free(). I recently got curious about the relative performance of various python versions, new style classes and slots. I wrote a very simple benchmark that allocated and deallocated a million small objects on a 600MHz P3 running linux 2.4.18 and glibc-2.2.4 with enough memory to prevent paging. Results and code are below. It's clear that the system malloc hurts badly for deallocation, but even with pymalloc deallocation is still an expensive exercise (the attribute dictionary, presumably). Slots are very efficient for small objects, in terms of CPU and memory footprint. Create and set attr Set attr Del+GC RSS -------- -------- -------- ------- py22 slots 20.3s 4.6s 19.5s 48M py221 slots 21.0s 5.0s 21.5s 48M pymalloc slots 16.2s 4.7s 0.7s 40M py22 obj 65.9s 7.4s 401.5s 185M py221 obj 62.1s 7.3s 492.8s 185M pymalloc obj 57.9s 7.2s 125.8s 185M py22 trad 55.8s 6.8s 275.8s 192M py221 trad 56.8s 7.1s 284.7s 192M pymalloc trad 52.6s 6.8s 115.0s 185M py211 trad 52.6s 6.6s 239.4s 154M With gc.disable(), and explicitly calling gc.collect(): Create and set attr Set attr Del+GC RSS -------- -------- -------- ------- py22 slots 13.6s 4.6s 19.7s 48M py221 slots 14.0s 5.0s 19.4s 48M pymalloc slots 10.6s 4.7s 0.7s 40M py22 obj 18.0s 7.3s 400.5s 185M py221 obj 18.7s 7.6s 399.0s 185M pymalloc obj 16.2s 7.2s 117.0s 185M py22 trad 11.2s 6.8s 270.8s 192M py221 trad 12.1s 7.2s 240.7s 192M pymalloc trad 11.4s 6.8s 115.3s 185M py211 trad 11.6s 6.5s 229.0s 154M py152 trad 7.8s 3.1s 75.5s 123M KEY ------ ----------------------------------------------------------- slots with new-style objects and using slots obj with new-style objects trad with traditional objects py22 Python 2.2 py221 Python 2.2.1 pymalloc Python 2.2.1 compiled with --with-pymalloc py211 Python 2.1.1 with traditional objects py152 Python 1.5.2 with traditional objects (no cyclic-GC) ---------------------------------------------------------------------------- import time, gc iters = 1000000 def start(): global ts ts = time.time() def stop(msg): delta = time.time() - ts if delta < 0.00001: print msg, "took %.1fus" % (delta * 1000000) elif delta < 0.01: print msg, "took %.1fms" % (delta * 1000) else: print msg, "took %.1fs" % (delta) try: class slots(object): __slots__ = ('a') def __init__(self, n): self.a = n def set(self, x): self.a = x class obj(object): def __init__(self, n): self.a = n def set(self, x): self.a = x except NameError: pass class trad: def __init__(self, n): self.a = n def set(self, x): self.a = x def testit(ctor, count): print "testing", ctor.__name__ start() a = map(ctor, xrange(count)) gc.collect() stop(' create + setattr') start() aa = ctor(0) map(aa.set, xrange(count)) gc.collect() stop(' setattr') start() del a gc.collect() stop(' del') if 0: gc.disable() if 0: testit(slots, iters) if 0: testit(obj, iters) if 1: testit(trad, iters) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From wurmy at earthlink.net Thu Jul 11 00:05:01 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Thu, 11 Jul 2002 04:05:01 GMT Subject: Deriving from Exception References: <3d2bf4b6.183387921@news.skynet.be> <3d2c1758.192254296@news.skynet.be> Message-ID: <3D2D03C4.3040709@earthlink.net> [/F] >>If this behaviour is fine for your exception subclass, there's >>no need to override anything. [pixie888] > class CMyException(Exception): > def __init__(self,ID): > self.ID = ID > > I do NOT call the __init__ function of Exception in the __init__ > function of CMyException: how does that relate to the explanation you > gave above? Will those args (what are they anyway, is args a reserved > word?) be copied then? I tought that *not* calling the __init__ of > Exception in the __init__ of CMyException resulted in not running the > code provided in that base __init__ function. Did I miss something > here? Sort of: the point is that in normal cases, you don't have to write your own __init__ here. For example: class CMyException(Exception): pass try: raise CMyException("42") except CMyException, e: print e.args # prints ('42',) What you pass to the exception can be retrieved using the args attribute. Of course, your situation is a bit different, you store the ID as an attribute of the exception object... is there a special reason why you want to do that? -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From dstuart at orsys.com Tue Jul 30 18:29:25 2002 From: dstuart at orsys.com (Doug Stuart) Date: Tue, 30 Jul 2002 17:29:25 -0500 Subject: pyexpat error Message-ID: <3D471345.B373E240@orsys.com> **** Post for FREE via your newsreader at post.usenet.com **** I am attempting to compile python with the Expat library included. I am running Solaris 7 and python 2.2.1. Originally, I did the 'configure-make dance' for python, then was told that I needed to add the Expat library. I did the 'configure-make dance' for Expat (version 1.95.4). I then went to redo my python doing a configure, make clean and make. During the build of the pyexpat extension I get an warning from line 1518 of Modules/pyexpat.c saying that subscript has type char. It then removes the library because 'an error occurred." In the setup.py script there is a setting for the EXPAT_DIR. I have tried setting that to the directory where the Expat source files are located and to the location of the library the Expat install creates. What am I missing here? Doug -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From aleax at aleax.it Sun Jul 14 04:08:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 14 Jul 2002 08:08:23 GMT Subject: Problem with shelve / nested lists References: Message-ID: Michael Schmitt wrote: > Hello. > I'm trying to use a shelve as a disc based dictionary, but have problems > with nested lists. If I store a nested list as value, inner lists seem to > be immutable. It's a well-known but underdocumented defect of shelves whose values are mutable objects -- mutations don't "take" unless you take very specific steps to help. I pointed it out both in the Python Cookbook (official launch in 2 weeks, at OSCON) and in the Nutshell (target date October), but that doesn't help much right now:-). Easiest way to reproduce the problem: >>> import shelve >>> s=shelve.open('x.y') >>> s['a']=range(3) >>> s['a'] [0, 1, 2] >>> s['a'].append(4) >>> s['a'] [0, 1, 2] >>> Workaround: >>> x = s['a'] >>> x.append(4) >>> s['a'] = x >>> s['a'] [0, 1, 2, 4] >>> I.e. you must arrange to assign the new value to s[thekey] -- it's only on assignment to its items that the shelve object notices any changes. Proposed fixes mooted for Python 2.3 are probably not going to happen. Having s "cache" all the s[whatever] that are being accessed (just in case they might be mutated) would, it is felt, have enormous memory costs in the common case where the objects are just being examined, not mutated. > According to the library reference, shelves can store "essentially > arbitrary Python objects" and "recursive data types". They do. They just don't give you exactly those objects when you fetch s[x], but rather, copies (reconstructed from the objects' pickles) -- and then promptly forget about whatever they just returned (holding on to it might, it is felt, have too-high memory costs). So, when you call mutating methods on s[whatever], you're mutating a copy -- the shelve object still holds on to the original pickle, and if and when you ask for s[whatever] again you'll get another fresh copy. Notice...: >>> s['a'] is s['a'] 0 >>> each s['a'] has different object identity, so "is" is not satisfied. > What is my misunderstanding? I think you expect sensible behavior, sensible behavior is hard to supply here, and the fact that shelve's behavior is NOT sensible is not clearly documented anywhere (at least until my books come out:-). I also think this situation is exceedingly unfortunate. Python and its libraries have VERY few gotchas that are at all comparable to this veritable trap laid out for the perfectly reasonable unwary user expecting perfectly reasonable behavior. This makes such traps stand out as _particularly_ troublesome when they do happen. Unfortunately, I have no 'magic wand' fix that will both make shelve's behavior reasonable AND still provide decent performance in common use cases:-(. Alex From aleax at aleax.it Fri Jul 5 10:45:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 14:45:05 GMT Subject: Memory ? References: Message-ID: Shagshag13 wrote: > > Hello, > > i'm still looking for a way to check which are the best ways to save > memory because i work on many GB with float, etc. so is there a way to > check how many bytes needs an object, a tuple, a list, a dict of objects > and so on ? (something like itemsize for array - in fact array should be > great if they weren't boxed) I'm not sure what you mean by "boxed" in this context. If you mean that arrays can only hold items of one type, well, that's how they get most of their memory-savings! An array of N floats for example takes 8N+x bytes for a rather small x, a list of N float Python objects MUST take at least twice as much -- each item in the list is a pointer (there go 4N bytes at least) to an object which, besides holding a float, must take at least another 4 more bytes for a pointer to the float type -- so, at least 16N + y for some small y. Package Numeric offer powerful arrays that (if I get your meaning right) can be "unboxed", i.e., hold arbitrary objects (just use typecode 'O'), but then it's unlikely this will save you any really significant amount of memory. How many bytes an object takes is a rather fuzzy concept and there's no single way to answer this at the Python level. Studying the C sources on the specific machine you're interested in will start to give you an answer, but in most cases you're only halfway. Since no object "owns" another, but rather each object is held alive by any number of references to it, as soon as there's more than one reference you have to take arbitrary decision about how to account for the bytes the object takes up. Plus, there's always "waste" of some sort or other -- e.g. depending on your machine's malloc, or pymalloc if your Python implementation uses that, but, moreover, dicts are hash tables that are never more than some-fraction full, lists most always have some extra 'free' slots allocated at the end, etc, etc. It's not clear which heuristics will be of practical use to you. > i also have troubles like : > > - which way is the best to handle a sequential dictionary : having 2 This reminds me of Alice asking about which way she should go - that very much depends, goes the answer, on where you'd like to arrive. > dicts, one for the order and other for my data ? but i think, it's better > to use a list to handle order an a dict for data (like in seqdict) What ARE your purposes? What operations do you want to optimize along which axes? If you have a list and need to insert or remove at arbitrary points you get O(N) performance, which can be a killer -- dictionaries don't suffer from that. But if you don't need such alterations and insertions, a mapping from the compact set [0..N) to any multiset of N values is indeed faster and less memory-hungry as a sequence, typically a list, than as a dictionary -- that's easy to benchmark, too. > - how many subclassing can i use ? (is this time or memory consuming in > any ways ?) There's no limit to subclassing in either breadth or depth -- any class may have any number of direct/immediate bases (breadth) and the inheritance tree can be of arbitrary depth. Memory costs are per-class and thus most often irrelevant (generally it's only per-instance costs that you need worry about -- most programs tend to have many more instances than classes). Time costs are indeed high (using ordinary classes of either classic on 2.2-new object model) since inherited lookups are performed at runtime. If your class has N bases, direct or indirect (depth or breadth, no real matter here) and all are equally likely to be the location of any given attribute, a typical lookup has O(N) cost. It wouldn't be hard to write a custom metaclass to 'flatten' this (at some, still per-class, memory cost -- and substantial cost in 'dynamism', since behavior would then be fixed at class-creation time rather than dynamically), were profiling to show that this is the program's bottleneck (unlikely, but, I guess, not impossible). > and so on... > > i didn't find such answers in PEP, etc. or maybe i missed them, That's probably because typical Python users don't focus on such micro-optimization issues all that much. Make it work, then make it right, then make it fast. After a program is developed and fully functional, and after it's refactored to the best architecture possible, THEN (if performance is not acceptable at this point) one starts profiling to determine where optimization would be of use (and even then, it's more likely that big-O issues, or at any rate issues best addressed by wholesale rearchitecting/refactoring rather than micro level tweaking, yield the highest gains, for the first few iterations of any such optimization effort). Let's take a simple example. Optionally in Python 2.1 and 2.2, and by default in 2.3, Python allocates small objects via pymalloc. It's thus easy to make a little patch to learn about how many bytes are actually allocated for each given object, itself -- quite apart from its items and attributes. I've done so in my Python 2.3 cvs tree image and exposed the function as sys.bytes for demonstratory purposes. >>> for i in range(5): print i, sys.bytes(range(i)) ... 0 32 1 32 2 32 3 32 4 32 As you see, any list object, per se, takes exactly 32 bytes on my platform (Linux on a 32-bit Athlon chip) -- clearly the slots for the items are being kept elsewhere, so the information "a list object takes exactly 32 bytes" is absolutely of no possible use. >>> for i in range(5): print i, sys.bytes(tuple(range(i))) ... 0 24 1 32 2 32 3 40 4 40 Tuples, on the other hand, as we see, are keeping their itemslots as part of "the object itself" -- taking 4 bytes per slot (on this machine -- 32 bit architecture, so, 4 bytes per pointer), but pymalloc rounds up to a multiple of 8 bytes (most system malloc implementations round like that, or even more grossly). So, a tuple of length N takes 24+4*N (rounded up to multiple of 8) bytes -- plus, of course, whatever its *items* take up (and this entirely depends on how you debit the space for items that would be in memory anyway even when this tuple disappeared). >>> sys.bytes(1) -2 We can't know this way how many bytes integer 1 takes up, because it's not being handled by pymalloc (that's what -2 means in my rapidly kludged up sys.bytes function). And indeed, studying the Python sources will show you how int's are special-cased -- and the "freelist" strategy they use for their own allocation. Similarly, you'll see any dictionary, per se, takes 136 bytes; an instance of any class whatsoever, 32 (...which *of course* ignores its __dict__ or __slots__...!); strings of length 0, 24 bytes -- length 1 to 8, 32 bytes -- length 9 to 16, 40 bytes -- and so on (24+N rounded up to a multiple of 8, in general); &c. I hope it's pretty clear by now, why this is of so little use (which is why I'm not going to check in my "sys.bytes" patch and no doubt why AFAIK nobody even bothered doing so previously). Alex From Simon.Foster at smiths-aerospace.com Tue Jul 9 08:43:14 2002 From: Simon.Foster at smiths-aerospace.com (Simon.Foster at smiths-aerospace.com) Date: Tue, 9 Jul 2002 13:43:14 +0100 Subject: Converting a hex string to a number Message-ID: <0017278C.C22236@smiths-aerospace.com> Tal said: >Hello, > I am trying to convert a hex string (for example: "0x12345678") to a >number (0x12345678 or just 12345678). > Can you help me please? >Thanks, Tal. eval! C:\WINNT\Profiles\syf\Desktop>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> string = '0x12345678' >>> eval( string ) 305419896 >>> From donn at u.washington.edu Mon Jul 8 12:55:27 2002 From: donn at u.washington.edu (Donn Cave) Date: 8 Jul 2002 16:55:27 GMT Subject: sending a file through sockets References: <3D277DDC.1040705@nowhere.org> <1026007094.566332@yasure> <3D280B4B.8020008@nowhere.org> Message-ID: Quoth Bryan Olson : ... | I was deliberately pointing out that sockets programming is harder than | it looks. A novice cannot tell whether an answer is a hint or a | solution. He may not be ready to worry about signals, but he does need | to know the distance between his question and a robust application. | | Also, there's tons of bad sockets code out there, some in the Python | standard library. I did intend my post for people who were already | doing sockets programming. Did you check out the signal issue? If you feel the standard distribution's modules are really bad, then maybe it would make sense to address that. They certainly ought to be much more robust than the present example needed to be, since it really was more introductory. What perhaps is really harder than it looks, is deciding "how much is enough". Part of my job is to decide how robust an application needs to be, and while it may be good to err on the side of safety, that doesn't excuse me from making the call. If you go ahead and code up the changes that the standard distribution needs in your estimation, it will be interesting to see how they fly. Probably be gratefully accepted, but if the gang thinks the complication is going to be a burden on future maintenance, for example, or there's a portability problem, then they could justifiably say thanks, but no thanks. The standard library modules really are useful, in real applications. The signal issue with httplib.py is another matter. It isn't so much about sockets, as C stdio via file objects. I wouldn't have written it that way myself, because of liabilities like this. recv(2) will return EINTR, and socketobject.recv() will accordingly raise an exception, so there is no ambiguity. fileobject.read() ignores the error. The example used recv(), so it didn't put its foot in that hole to start with. But that's another trade-off - the authors of those modules apparently felt that the simplicity of a file object solution was worth the lossage. | I gathered that you had in mind a kind of any-old-way of ending. Clean | close of a TCP connection is a deliberate act, and the method you named | doesn't do it. Let's review what I said: Fine if the file is all you're sending, but it's like "who needs an on-off switch on this appliance, when you can just cut the power cord with a pair of insulated wire cutters." A byte count prefix usually is needed, and in the rare case when it isn't, it doesn't cost much to do it anyway. "Appliance" means, to me, popcorn popper, steam iron, whatever you like. It's an analogy. I would send a byte count. Donn Cave, donn at u.washington.edu From ods at fep.ru Wed Jul 24 10:40:44 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Wed, 24 Jul 2002 18:40:44 +0400 (MSD) Subject: Detecting pipe on stdout? In-Reply-To: Message-ID: On 24 Jul 2002, Alexander Schreiber wrote: AS> Is there any way for a Python program to detect wether its AS> stdout has AS> been redirected to a pipe/file (like "./programm | less")? AS> I've didn't AS> find anything about this in the FAQ and failed to come up AS> with the right AS> search terms for google. AS> AS> Reason: I've got a Python program[0] here which normally AS> colorizes its AS> output (to the terminal) using escape sequences. This is AS> fine and nice AS> while running on a terminal, but when running the program AS> with less AS> attached to it the escape sequences are annoying. Ideally, I AS> want to AS> detect a pipe attached to stdout and switch of the color AS> (the flag is AS> already there) in this case. sys.stdout.isatty() -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From keith_s at ntlworld.nospam.com Wed Jul 24 15:12:24 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Wed, 24 Jul 2002 20:12:24 +0100 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> Message-ID: <3D3EFC18.30705@ntlworld.nospam.com> Just wrote: > Have a look at code.py in the std library. Hmm, that looks interesting... So in my C code I've something like: char *code = "class Sout:\n" " def write(self, s):\n" " output(s)\n" "\n" "class Sin:\n" " def __init__(self, prompt):\n" " input(prompt)\n" "\n" "import sys\n" "from code import *\n" "from gld import *\n" "sys.stdout = Sout()\n" "sys.stdin = None\n" "interact('---Starting Python---, Sin)\n" PyRun_SimpleString(code); The input() C function returns Py_BuildValue("s", cmd ), where cmd is the cmd typed in the cmd line. However this does not work... the output is something like: ---Starting Python--- >>> Traceback (most recent call last): File "", line 15, in ? File "C:\Python22\lib\code.py", line 307, in interact console.interact(banner) File "C:\Python22\lib\code.py", line 244, in interact more = self.push(line) File "C:\Python22\lib\code.py", line 265, in push source = "\n".join(self.buffer) TypeError : sequence item 0: expected string, instance found Any clues on what's wrong here? - Keith From janto_d at hotmail.com Mon Jul 8 04:59:26 2002 From: janto_d at hotmail.com (Janto Dreijer) Date: 8 Jul 2002 01:59:26 -0700 Subject: the meaning of life References: <3eeda89d.0207071133.4c07a86e@posting.google.com> Message-ID: aoeu at go.com (Thinkit) wrote in message news:<3eeda89d.0207071133.4c07a86e at posting.google.com>... > Take a break from python and realize the meaning of ALL conscious beings. > > MEANING > > --The meaning of a conscious being is to pursue one of two goals. > > Among the criteria listed below, only LOVE part 2 is achievable. > I think someone is in need of a little retraining. Look up "Meaning of Life" under "Scripts": http://www.montypython.net Better yet, get the video. Most video stores should have a copy. From tundra at tundraware.com Wed Jul 10 04:20:03 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 10 Jul 2002 08:20:03 GMT Subject: Win32 Registry Manipulation w/PythonWin? Message-ID: Does some kind soul out there happen to have a pointer to a tutorial/examples on fiddling with the Win32 registry from PythonWin? TIA, -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From dpinol at hotmail.com Mon Jul 8 04:40:23 2002 From: dpinol at hotmail.com (=?ISO-8859-1?Q?Daniel_Pi=F1ol_Laserna?=) Date: 8 Jul 2002 01:40:23 -0700 Subject: pythoncom from jython Message-ID: <46585325.0207080040.1ac2fffd@posting.google.com> Is it possible to use pythoncom from jython? Ideally, I'd like to build a com component in python (this works with win32 extensions), and from there make calls to java classes (this need jython). I tried to manually import win32 modules from jython, but i didn't suceeded from win32 import * from win32com import * from win32comext import * execfile ('lib\\win32\\Lib\\regutil.py') Here I get an error because win32api is not available. From fperez528 at yahoo.com Thu Jul 11 22:28:15 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 11 Jul 2002 20:28:15 -0600 Subject: How to replace multiple-line text References: <3D2D0782.45FCEC98@bellatlantic.net> <3D2E35C6.5B2612CF@bellatlantic.net> Message-ID: David Lees wrote: > >>>> import string >>>> x='this is junk' >>>> string.replace(x,'junk','stuff') > 'this is stuff' > > Time to do some more reading on classes, since I don't understand why it > is not necessary to import string here. > > what you posted is ok, simply an alias to the string methods. After 2.x (or earlier?) python has subsumed most of the string module's functionality into methods which are part of all strings you create. cheers, f. From aoeu at go.com Thu Jul 11 02:10:22 2002 From: aoeu at go.com (Thinkit) Date: 10 Jul 2002 23:10:22 -0700 Subject: coding python by web? References: <3eeda89d.0206170317.100549db@posting.google.com> Message-ID: <3eeda89d.0207102210.581f9508@posting.google.com> Gerhard H?ring wrote in message news:... > * Thinkit [2002-06-17 04:17 -0700]: > > Is there any way to test out simple python code with only a web > > browser (no input or files, just printing text)? I'm guessing a > > simple cgi setup could do this, but has it been implemented anywhere? > > Hi, "Thinkit", > > dunno if it's implemented, yet, but it's not difficult to do. Below I've > put a quick, working draft, replace exec with print to see the code. > > The trick is to redirect sys.stdout and use exec. > > Things not implemented in the draft: > - using a restricted environment > - handling exceptions gracefully, displaying a traceback > > import zlib,base64 > exec(zlib.decompress(base64.decodestring(""" > eNpdUstq3TAQ3esrplMu2HBjh0IpBNubQKCrLLItFNnWdURkSUjjJCbk3zvy49atVvM4OjNnZr5+ > KacYSuM6acpW29LP9Oys0KN3gaAb9BniHHf/iYK2w89HIUiGQRHUgCWDbtLXVnYvvXOh8DMK8Uyj > SWnEKplN1bp+bgRsr7q4MMLKUuMpW6084gFC6p3DSoKVo6oxdkF7QgjuLdb47Rahc4atH98R3oL0 > Nb7qQJM02JyyFZzHqtxZGvjLrK2fCGj2iXZqR03YVOUSPdQvU49H/z8JPqhrJTcRf071UrQqF80s > XohFaJ1GWTxoZfonckEOKsvF+pNzCVKw/FdpJpXtQs88vFwIF/TwO1LPFRjKyyhWR7TT5aICx/at > FLuRuK84BqxIIcZ5MK6VJnLs45PdZe+bJ9S76mDrSVu4gs+wA8W/tIfOtmaKqNRLdstde+6EAO+d > JWXpJo36DtIqlsn8srhDljs5wQeuF4B321Gw+uNkOb6V4FX2WX5Nc2I1WIH4A+u46F4= > """))) > > Gerhard I haven't tried this yet...problem for me is I don't know where I'll get custom cgi access. It would be really great if this kind of thing was available for quick testing of snippets of code in any language. From alexandrecourbot at linuxgames.com Mon Jul 22 17:19:16 2002 From: alexandrecourbot at linuxgames.com (Alexandre Courbot) Date: Mon, 22 Jul 2002 23:19:16 +0200 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: <1027366000.27398.1.camel@jwilhelm.ofsloans.com> References: <20020721115251.12dd6d7d.alexandrecourbot@linuxgames.com> <1027366000.27398.1.camel@jwilhelm.ofsloans.com> Message-ID: <20020722231916.5a8540ad.alexandrecourbot@linuxgames.com> > > Note also that I > > had to cross-compile the Python library myself from Python 2.2 > > sources, as there is no lightweight Python distribution for the Arm. > > Actually..... there is. I haven't used it myself, but it can be found > here: > > http://www.riverbankcomputing.co.uk/zaurus/index.php Yep, I had a first look there of course. Unfortunately the package contains the Python interpreter (which is statically linked to the library), but not the Python library itself, so it is useless to me. That's why I've re-compiled it from the sources, made a shared library, and at the same time build an interpreter that links to this library. That way the interpreter itself is only 3kb large, and the library is available for applications to link with. If someone of Riverbank Computing is listening here, maybe they could consider doing this for their next builds. It doesn't eat up extra space at all, open new opportunities for developers, and fits well with the space-saving philosophy of the Zaurus. Alex. -- http://www.gnurou.org From pecora at anvil.nrl.navy.mil Tue Jul 23 07:59:35 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 23 Jul 2002 07:59:35 -0400 Subject: A better self References: Message-ID: <230720020759355808%pecora@anvil.nrl.navy.mil> In article , Delaney, Timothy wrote: > On my machine, the results are: > > 2.30967285289 (1) > 2.14318686404 (2) > 2.982054833 (3) [I added the (numbers) above for clarity] First, thanks for that nice study. Very interesting. (1) is using t, x, y, z = v.t, v.x, v.y, v.z (2) is t = v.t; x = v.x; y = v.y; z = v.z (3) a function call to a formula f(v.t, v.x, v.y, v.z) It looks like some of the guesses people had on this NG are correct. (2) is fastest (1) is slower (by ~ 8%) (3) is slowest (by ~ 40%) I'd call (1) and (2) a near draw, but (3), if it accurately reflects a function call has non-negligible overhead, IMO. I understand these were quick and dirty tests. More tests would be nicer. I may try a few. Thanks, again. -- Lou Pecora - My views are my own. From tim at zope.com Wed Jul 3 11:22:33 2002 From: tim at zope.com (Tim Peters) Date: Wed, 3 Jul 2002 11:22:33 -0400 Subject: Thread safetyness in Python In-Reply-To: Message-ID: [John Goerzen] > I have some questions about what is thread-safe in Python. Can > someone tell me whether each of the following are thread-safe: Yes . Assuming you mean thread-safe in the sense of sequential consistency: > 1. a = a + 1 > 2. a = a + 2 No and no. Others have suggested Python a += 1 is atomic, but it isn't. > 3. list.append(x) > 4. list.remove(x) > 5. del(list[0]) Yes, yes, and yes. Note that del isn't a function, and del list[0] is more idiomatic. Also, x = list.pop(0) is an atomic way to remove the first item and retrieve its value in one gulp. > Here's why I'm asking: > > 1. In C, a++ would be atomic because CPUs have an atomic increment > operation, in most cases. Do a reality check before relying on this. I don't know of any platform where C compiles a++ to atomic code, even assuming a is of integral type. On platforms that have some sort of atomic increment instruction, you typically need to use inline assembly, or call a vendor-supplied builtin function, to get at it. Else you're going to get code like this (from a listing of generated code on an Intel box, where 'a' is of the native int type): ; 6 : a++; 00022 8b 55 fc mov edx, DWORD PTR _a$[ebp] 00025 83 c2 01 add edx, 1 00028 89 55 fc mov DWORD PTR _a$[ebp], edx > In Python, it might be the case that if two threads hit this code at the > same time, a would only be incremented once because both threads would > read a, add 1, and store the same result back. So one might need a lock > here. Yes, although the same is equally true of C a++. From whisper at oz.net Sun Jul 21 16:33:33 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 21 Jul 2002 13:33:33 -0700 Subject: Book: "Learning Python" Is it still a good reference for a Python Beginner? In-Reply-To: <0BC_8.112265$vm5.3832285@news2.tin.it> Message-ID: > I do hope Ascher and Lundh find the time to update "Learning" to > 2.2 very soon, of course. But if they don't, it's still a good > book indeed. There are other good books, but "Learning" is still > my first recommendation to a programmer experienced in other > languages who wants to get started with Python on the right foot. > > (Bias warning: working with David on the Python Cookbook has made > us friends -- but I liked Learning Python even before then!-). > > > Alex You know, I have a book called "Learning Python" (O'Reilly & Associates; ISBN: 1565924649; (April 9, 1999)), but this version is written by Mark Lutz, David Ascher and Frank Willison (Ed.) - is the Ascher/Lundh book a different version? Dave LeBlanc P.S. Whoever wrote it, I second the motion favoring a new revision! From sandeep182 at hotmail.com Mon Jul 1 19:16:09 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: Mon, 01 Jul 2002 23:16:09 GMT Subject: execvp on Windows References: Message-ID: It turns out that this is a known issue: http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=43 6259 "Sandeep Gupta" wrote in message news:sz0U8.16135$eF5.561799 at twister.austin.rr.com... > On Linux, os.execvp(executable, args) replaces the current process, while on > Windows, it seems to spawn a new process and then complete the current > process. On Windows, this means I get back the command prompt followed by > the output of my executable. > For example, > ====================== > D:\>python > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> os.execvp("python",["python"]) > > D:\>Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> > ====================== > On Windows, is there any way to delay the completion of the first process > until the execvp executable returns? One idea is to use os.spawn*, but I > was looking for others. > > Thanks > Sandeep > > From krissepu at vip.fi Tue Jul 2 09:46:25 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Tue, 02 Jul 2002 16:46:25 +0300 Subject: Where python especially good ? References: Message-ID: <3D21AEB1.44DD59FE@vip.fi> I think python is good for small tools that needs to be developed quickly. Also, in organizations where people do not have formal education of programming languages, python syntax is a plus. However, the current trend of picking best of other languages will eventually lead to a situation where you have a language which performance and features are "average". The current trend of adding C-extensions and inline compilers shows that something is wrong in Python. Also, the bigger the standard library, the harder to make engineering changes to language Stackless IS a good idea, but if that cannot be implemented because of the current userbase, we got a problem. -pekka- Jonathan Hogg wrote: > On 2/7/2002 9:02, in article afrmbm$d28$07$1 at news.t-online.com, "Andrey > Koubychev" wrote: > > > What do you think, at what tasks pythons shows great benefits comparing to > > other script languages ? > > I think the Python language shows its greatest strength when you aren't > writing scripts ;-) > > Seriously, I don't think of Python as a scripting language the way I'd think > of perl or sh or awk. I view it as a systems programming language, and some > fair size systems have been written in it. > > The main advantages of it to me are speed of development and ease of > maintenance. I think Python has the edge over other "scripting" languages in > both of these areas: it has an interactive interpreter; it is strongly, but > simply, object-oriented (Perl doesn't come close here); it has a very good > standard library; Python code tends to be readable. > > I think comparing Python to Java is fairer, and I find Python to be a much > more pleasant language to work with. > > [When I was doing my last big Java project, we prototyped the whole thing in > Python first then re-coded it into Java. Even during the Java development I > used Jython to test and explore the Java code.] > > If you just want to munge a log file with some heavy regular expressions and > spit out some statistics or something, then you might be better off with > Perl. But if you want to write a program, look at Python. > > Jonathan From p.magwene at snet.net Fri Jul 12 08:37:36 2002 From: p.magwene at snet.net (Paul Magwene) Date: Fri, 12 Jul 2002 12:37:36 GMT Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> Message-ID: On Wed, 10 Jul 2002 10:19:20 -0400, Thomas Guettler wrote: > Hi! > > Does someoone know an editor for editing hierarchical text data? > > I need it for something like a todo-list. One task can have several > subtasks. > > Should be a GUI, not an web application. > > Thank you > > thomas It's not Python-based but I've been using a curses based program called "Hierarchical Notebook": http://hnb.sourceforge.net/ I haven't bothered trying to compile it for windows but on the sourceforget site some of the older releases seem to have pre-compiled windows versions. From peter at engcorp.com Tue Jul 16 07:55:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Jul 2002 07:55:37 -0400 Subject: namespaces in python References: Message-ID: <3D3409B9.6AF523D6@engcorp.com> Jeff Davis wrote: > > Is there a way to put functions and variables in a different namespace > without putting it in a seperate file or instantiating a new object? Is > there a way to have static methods that don't require instantiating the > object first? > > I just want a clean way to divide up my modules a bit without cluttering up > the filesystem (or requiring seperate i/o operations to fetch several > files). While you've got some interesting responses from others, I want to ask "Is it really that bad a thing?". The filesystem, after all, is _there_ to be "cluttered up" with files. And what is wrong with separate I/O operations? This is Python, so it can't be that performance is that big a concern, so what's wrong about fetching a few files? I ask only because this sounds like swimming against the current, without even the benefit of that nice moment when you breed and die after you reach the spawning grounds. :) -Peter From aahz at pythoncraft.com Thu Jul 11 13:49:11 2002 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2002 13:49:11 -0400 Subject: How to organize test cases with PyUnit References: Message-ID: In article , Roy Smith wrote: > >BTW, I started out with the test cases in a "test" subdirectory, and ran >into a slight uglyness. My initial idea was to just have module-test.py >do an "import ../module", until I discovered that gives you a syntax >error. I can get around it with: > >import sys >sys.path.insert (1, '..') >import module > >but that seems clumsy. Is there a cleaner way to do that? Keeping in mind that I don't actually have any experience with this, I'd make your test directory a package and include a driver script with your main modules. Then the driver script only needs to import from the package. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From simon at uggs.demon.co.uk Sun Jul 7 18:37:37 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Sun, 07 Jul 2002 22:37:37 GMT Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> <3d28bdb0.71631360@news.dsl.pipex.com> Message-ID: <3d28c29a.72888518@news.dsl.pipex.com> On 7 Jul 2002 22:30:55 GMT, William Park wrote: >'1\n2\n3\n'.split() works as follows: > 1\n2\n3\n -> 1\n2\n3 -> 1 \n 2 \n 3 -> 1 2 3 > >'1\n2\n3\n'.split('\n') works as follows: > 1\n2\n3\n -> 1 \n 2 \n 3 \n -> 1 2 3 '' >where the last '\n' separates '3' and '' (null). > >-- >William Park, Open Geometry Consulting, >8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin Still seems odd! -- Simon Foster Cheltenham England From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 21:13:45 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 18:13:45 -0700 Subject: performance problem in python 2.2 References: <7xd6tayqt6.fsf@ruckus.brouhaha.com> <7xptxaj9kq.fsf@ruckus.brouhaha.com> <6_l09.28101$_M2.10183516@twister.socal.rr.com> Message-ID: <7xznwem0qe.fsf@ruckus.brouhaha.com> Jeff Davis writes: > If you read my C code, you'll see that I used the 'unsigned long long type' > which is a 64-bit int. And I only stored 2^32 in it. When I needed to > crunch the numbers, I treated 2^64 as p*p (because 2^64 == > sqrt(2^64)*sqrt(2^64) == 2^32*2^32), and then I commuted the > multiplication so it would happen in a way that wouldn't overflow. Oh whoops, yes, I missed that. "Long long" is not part of standard C, though some compilers support it. From johnroth at ameritech.net Tue Jul 30 11:59:44 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 30 Jul 2002 11:59:44 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> Message-ID: "Daniel Fackrell" wrote in message news:3d46964b$1_2 at hpb10302.boi.hp.com... > "John Roth" wrote in message > news:ukb31ell2rh643 at news.supernews.com... > > > > > for word in 'fee fie fo fum'.split(): > > Button(frame, command = def (): > > print word > > ) > > > > This isn't really the world's best example, because IMO, the > > lambda form is easier to read for something this small. However, > > it does give the guts of the idea: > > > > > 2. The remainder of the syntax exactly models def, including > > statement indentation within the expression. Notice that the > > first statement in the anonamous function has to be indented > > two from the preceeding line, because the continuation of > > the expression has to still be indented from the line with the > > 'def', and dedented from the statements. > > IIRC, there's no such ting as "indenting two" in Python as the size of an > indentation is automatically detected as you go along, making the following > indentation style valid (although no one would ever want to do it): > > toplevel > secondlevel > thirdlevel > secondlevel > thirdlevel > fourthlevel > secondlevel > toplevel The reason I say "indenting 2" is that you need two dedents to make it work: one to close the def, which does not have it's own indent, and one to finish off the expression in which the def is imbedded. Does this make it clearer? John Roth From erict at millfilm.co.uk Mon Jul 15 10:29:26 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Mon, 15 Jul 2002 15:29:26 +0100 Subject: multiple inheritance and __slots__ Message-ID: <3D32DC46.3B360D1C@millfilm.co.uk> In short, I am getting the error message: TypeError: multiple bases have instance lay-out conflict when I try to declare a subclass of 2 classes with __slots__ Is there an easy way around. (In this case, I really would like to keep the multiple inheritance.) Following is an example: ######################################### class aBasicTask(object): __slots__ = [ "_aBasicTask__Name", "_aBasicTask__OuputType"] def __init__(self): super(aBasicTask,self).__init__() self.__Name = "unknown" self.__OuputType = "NoType" def setName(self,name): self.__Name = name def getName(self): return self.__Name name = property(getName,setName,doc = "task name") ########################################### class OutputFile(object): ''' getFile from any file ''' __slots__ = ["_OutputFile__fileName"] def TypeOutName(): return "OutputFile" TypeOutName = staticmethod(TypeOutName) def __init__(self): super(OutputFile,self).__init__() self.__fileName = "" def getFile(self): return self.__fileName class foo(aBasicTask,OutputFile): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: multiple bases have instance lay-out conflict From sanjay2kind at yahoo.com Tue Jul 2 13:02:51 2002 From: sanjay2kind at yahoo.com (sanjay) Date: 2 Jul 2002 10:02:51 -0700 Subject: Is there any simple way to get all HTML tags and remove attribute Message-ID: <63170f57.0207020902.25fac937@posting.google.com> Hi, I am trying to get all HTML tag and remove color attribute using SGMLparser. Can anyone provide simple code .. Thanking you, From aleax at aleax.it Fri Jul 26 17:21:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 21:21:12 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: Britt A. Green wrote: > I guess that begs the question: what's the advantage of functional-style > programming? :) Working with higher-order functions, closures, list comprehensions and other approaches typical of functional programming often offers clear, concise and powerful ways of expression. But you don't need to pay the price of lambda's obscurity for that. Alex From joshualevy at yahoo.com Thu Jul 11 13:24:42 2002 From: joshualevy at yahoo.com (Joshua Levy) Date: 11 Jul 2002 10:24:42 -0700 Subject: python binaries for Solaris Message-ID: <5fa44575.0207110924.7dff8ba8@posting.google.com> Does anyone know where there are python binaries pre-compiled for Solaris 9 / SPARC3 / sunfire type hardware? I need to do some quick benchmarking, and I don't even have a compiler on the Solaris 9 machine, so building python would be a pain. Joshua Levy From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 11 14:49:06 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 11 Jul 2002 20:49:06 +0200 Subject: Good SOAP lib for Python 2.2 References: <3D2D9B2C.3030606@NOSPAMREMOVETHISxs4all.nl> <3D2DD110.4080605@NOSPAMREMOVETHISxs4all.nl> Message-ID: <3D2DD322.3050402@NOSPAMREMOVETHISxs4all.nl> I wrote: > > Anyway I'll try the updated SOAP.py from the PyGoogle stuff. > That suggestion came by email from Andy Ptak. Thanks, Andy. Irmen From ms at NOMAIL.de Sat Jul 13 19:53:10 2002 From: ms at NOMAIL.de (Michael Schmitt) Date: Sun, 14 Jul 2002 01:53:10 +0200 Subject: Problem with shelve / nested lists Message-ID: Hello. I'm trying to use a shelve as a disc based dictionary, but have problems with nested lists. If I store a nested list as value, inner lists seem to be immutable. According to the library reference, shelves can store "essentially arbitrary Python objects" and "recursive data types". What is my misunderstanding? Python2.2: >>> import shelve >>> d1= shelve.open('dict.dat','c') >>> d1['bla']= [1,2,[10,20]] >>> d1['bla'][2] [10, 20] >>> d1['bla'][2].append(30) >>> d1['bla'][2] [10, 20] Using a dictionary instead of the shelve, lets append to the inner list. >>> d2= {} >>> d2['bla']= [1,2,[10,20]] >>> d2['bla'][2] [10, 20] >>> d2['bla'][2].append(30) >>> d2['bla'][2] [10, 20, 30] Thanks for any hint, Michael From e.d.andersen at mosek.com Sun Jul 21 06:19:31 2002 From: e.d.andersen at mosek.com (edadk) Date: 21 Jul 2002 03:19:31 -0700 Subject: Fail pyton build. What to do References: Message-ID: Hi Well, I solved the problem by uncommenting 3 lines or so in setup.py. Erling e.d.andersen at mosek.com (edadk) wrote in message news:... > Hi, > > I am build python 2.1.1 on Solaris/Intel 8 and get the error meassage > below. [I do not need the audio stuff at all. Can I shut it off for > instace.] > > What can I do? > > Thanks. > > Erling > > > building 'sunaudiodev' extension > gcc -g -O2 -Wall -Wstrict-prototypes -fPIC -I. > -I/tmp/Python-2.1.1/./Include -I/usr/local/include -IInclude/ -c > /tmp/Python-2.1.1/Modules/sunaudiodev.c -o > build/temp.solaris-2.8-i86pc-2.1/sunaudiodev.o > /tmp/Python-2.1.1/Modules/sunaudiodev.c:24: sun/audioio.h: No such > file or directory > WARNING: building of extension "sunaudiodev" failed: command 'gcc' > failed with exit status 1 > running build_scripts > not copying /tmp/Python-2.1.1/Tools/scripts/pydoc (up-to-date) > bash-2.03# From rhymes at myself.com Wed Jul 3 13:45:04 2002 From: rhymes at myself.com (Rhymes) Date: Wed, 03 Jul 2002 19:45:04 +0200 Subject: PythonWin + other GUIs = CRASH! References: <3D232FEE.3010606@gmx.de> Message-ID: On Wed, 03 Jul 2002 19:10:06 +0200, Ingo Linkweiler wrote: > Do you know other IDEs, which can be used with [Qt, wxPython, Pygame]? try SCITE or IDLE -- Rhymes rhymes at myself.com " ride or die " From sdeibel at wingide.com Mon Jul 8 08:22:56 2002 From: sdeibel at wingide.com (Stephan R.A. Deibel) Date: Mon, 8 Jul 2002 08:22:56 -0400 (EDT) Subject: Using Python for processing of large datasets (convincing managment) In-Reply-To: <200207061653.g66Grjci001759@ratthing-b246.strakt.com> Message-ID: On Sat, 6 Jul 2002, Laura Creighton wrote: > 2) He said, "Name 3 companies using Python for key functions" 1) Industrial Light and Magic uses Python extensively, e.g. in creating Star Wars II. 2) Google is based on Python. 3) Nasa uses Python quite a bit. For example: http://builder.com.com/article.jhtml?id=u00420020617DGS01.htm (does require a free membership to see the article) Some more links to possibly useful marketing-python sort of stuff are here: http://pythonology.org/ HTH. - Stephan ------------------------------------------------------------------------ Wing IDE for Python Archaeopteryx Software, Inc www.wingide.com Take Flight! From gerhard.haering at gmx.de Sun Jul 7 07:05:26 2002 From: gerhard.haering at gmx.de (=?ISO-8859-1?Q?Gerhard=20H=E4ring?=) Date: Sun, 7 Jul 2002 13:05:26 +0200 (Central Europe Daylight Time) Subject: sqlite-python-0.2.0.win32-py2.2.exe fails In-Reply-To: <1b8c5fe1.0207070212.679882af@posting.google.com> References: <1b8c5fe1.0207060550.72952217@posting.google.com> <1b8c5fe1.0207070212.679882af@posting.google.com> Message-ID: <20020707110302.390404DF@gargamel.hqd-internal> Comcol wrote: > Gerhard H?ring wrote: > > * Comcol [2002-07-06 06:50 -0700]: > > > I tried to run sqlite-python-0.2.0.win32-py2.2.exe on a Windows 95 > > > machine, but it failed due to a page fault. *Sigh* > > Now that doesn't solve your problem. What we need to debug your problem > > is a core dump, or DrWatson file, or whatever it's called on Win95. > > Does anybody here know by chance how to produce it? > > Before we do this ... > > The actual problem is with the original exe itself (i.e. the INSTALLATION > program - the self-extracting executable). It reports an unhandled > exception (COMCTL32.DLL) 0xC0000005: Access Violation. In other words, there's a general problem with the installers created with the installers created with Python distutils. It would be worthwhile to find out what the problem really is, but for now, I'll try to produce a workaround. > I don't think that this is of use to you, though. As far as I know > there's nothing wrong with PySQLite itself, but with the self-extracting > installation program. If the distribution had been available as a zip > file then I would probably be able to install it. Nothing's easier that that. http://sourceforge.net/project/showfiles.php?group_id=54058 now has an additional file called pysqlite-0.2.0.zip. You can install it by unzipping it and issuing a "python setup.py install" in the pysqlite-0.2.0 directory that gets created. If Python is not in your path, you need to provide the complete path, something like "c:\python22\python setup.py install" on a command prompt. > > PPS: Have you installed all updates for Windows 95? Service Pack 1? > > Good Lord no. I don't know where one could get a service pack anyway. http://www.microsoft.com/windows95/downloads/ With zero updates, even without the Winsock update, it's a wonder anything runs at all on your machine <0.5 wink> Gerhard -- mail: gerhard.haering at gmx.de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mlh at vier.idi.ntnu.no Mon Jul 15 17:05:53 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 15 Jul 2002 21:05:53 +0000 (UTC) Subject: "Tickets" and XML-RPC authentication References: <0FiY8.16023$p56.5181944@newsb.telia.net> Message-ID: In article <0FiY8.16023$p56.5181944 at newsb.telia.net>, Fredrik Lundh wrote: >Magnus Lie Hetland wrote: > >> If I have only one server/service, and that service takes care of its >> own authentication (i.e. no Kerberos-like stuff), is there any point >> to using a ticket/cookie-based system? >> >> In other words, is there any point to doing this: >> >> ticket = server.authenticate('username', 'password') >> server.performService(ticket, some, other, params) >> >> rather than >> >> server.performService('username', 'password', some, other, params) >> >> ? > >if you assume that a potential attacker sees everything you do >all the time, and don't care about performance and complexity, >no. Well, I do care about complexity... Not sure if the performance boost here is something I care too much about, though ;) As for attackers listening in -- I guess you mean that I might want to have one secure (ssl) login-call, and then do the rest in the open? I'm not completely sure why I then wouldn't want to wrapp it all in a secure connection... >tickets can make both the client and the server simpler if you >want to associate lots of content with an XML-RPC "connection"; I see -- session handling, more or less. >it allows you to distinguish between different clients using the same >username/password, it makes it easier to let "connections" expire, >etc. Yes. The API complexity and session handling were the two things I was able to think of... >(and Dave Winer would never think of doing things that way ;-) Eh... OK...? :-] >and yes, if a potential attacker doesn't see everything, it may >even be a bit safer. why keep sending the password over and >over again, when you don't have to? Hm. Good point. > -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From martin at v.loewis.de Sat Jul 6 16:52:26 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Jul 2002 22:52:26 +0200 Subject: Chinese language support of Python? References: <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Boudewijn Rempt writes: > > root.title('中文') # this is Chinese [...] > If you use _real_ unicode -- for instance > root.title(u'\u028A\u0288') # no chinese, because of lacking fonts, but IPA > then everything works fine -- at least, with my window manager, on my OS. It's more likely that the OP meant root.title(u'\u4e2d\u6587') Regards, Martin From dcinege at psychosis.com Wed Jul 24 16:27:04 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Wed, 24 Jul 2002 16:27:04 -0400 Subject: cmd, readline, and /path/filename completion In-Reply-To: <20020724140022.G10625@prim.han.de> References: <20020724140022.G10625@prim.han.de> Message-ID: <200207241627.04037.dcinege@psychosis.com> On Wednesday 24 July 2002 8:00, holger krekel wrote: > More exactly, the OP needs to erase the '/' character from the delims list. > e.g. > > readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>?') Yes! Thank you. Though I don't understand why this works...at least I have some idea where to look in the readline docs. I began going through them last night but didn't get much out of them. : P > should work the way you want it. > > Are you implementing your own completion handler? I don't know if I going to need to. As I said I'm toying with this now. One thing still 'broken' is it will not complete against executables, in the curdir or path. Can you comment on doing this? It does currently complete against builtin's, IE def do_XXXX(self,line): methods. Dave -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From jb at cascade-sys.com Sat Jul 27 00:41:55 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 26 Jul 2002 21:41:55 -0700 Subject: calendar lameness! References: <1o24kugq5amid8fndc6ds6q53u6rfp9j3n@4ax.com> Message-ID: <3D422493.CD84ECAA@cascade-sys.com> Tim Roberts wrote: > That's easy, too: the first Sunday after the first full moon after the > vernal equinox. That's the common rule of thumb but it's actually a little more complex even than that. "The calculation is complicated because it is linked to (an inaccurate version of) the Hebrew calendar." Also, upon further study, I find The Church's interest in making sure Easter happens before Passover was not merely some kind of one-upmanship but rather because it is understood to be a historical fact that Jesus was executed just before Passover. > Of course, that phrase is not so easily translated into a Python > expression... Curiously, it IS translateable into code that takes only the year as a dependent variable. Google( "calculating easter" ) will probably cover this in more detail than anybody can stand. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 15:36:06 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 15:36:06 -0400 Subject: python threads and the linuxthread pthread library References: Message-ID: <3D20AF26.4090801@removethisandallhyphens-o-n-e.net> I, too, am greatly interested in this - multithreaded python applications do not perform as well as I expected, so an explaination/pointers would help greatly. -c anton wilson wrote: > > I've been attempting to understand how python threads will interact with my > Linux system (mainly the linuxthread library and the scheduler). I've > concluded that the python interpreter's context switching every 10 byte-codes > will rely on the Linux scheduler to somehow switch between threads after one > thread releases the global interpreter lock. However, I am a bit confused on > how threads interact with the python interpreter at a low level. Is the > Python Virtual Machine it's own thread? How do threads aquire the global > interpreter lock once they are awoken? How exactly do the byte-codes for a > particular thread get run by the Python interpreter? Does each thread run the > interpreter? > > If anyone has any explanations, links, or pointers please let me know. > > Thanks, > > Anton Wilson > > > > > From peter at engcorp.com Tue Jul 23 22:16:34 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Jul 2002 22:16:34 -0400 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> Message-ID: <3D3E0E02.89EC9D1@engcorp.com> Huaiyu Zhu wrote: > > Peter Hansen wrote: > >Paul Rubin wrote: [about putting __call__ in modules] > >Although you can do as you wish, of course, I want to chime in > >with a "this is a really bad idea" and hope you don't follow through > >on it. This is, even in the best case, going to make your code > >less readable to anyone else. It is also likely to cause maintainability > >problems because making the claim "but this module has only one function!" > >almost certainly means it will not stay that way forever. > > Why is this so? Modules appear to be just singletons associated with files. > Why making them more similar to other objects would make programs less > readable? Maybe some examples of usage would help to clarify the issues. > As a counterexample, I've been confused many times by 'from foo import foo', > not knowing which foo is which. You can make them as similar to other objects as you wish, but it wouldn't change my opinion that "module" refers to a specific *kind* of object for which the __call__ convention has little or no merit. I'm not saying it should not be there, just that it should not be used if it is. :-) -Peter From fredrik at pythonware.com Sat Jul 27 18:02:52 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 22:02:52 GMT Subject: How to detect the last element in a for loop References: Message-ID: Tom Verbeure wrote: > I am not familiar with iterators as objects in Python. I understand that > > for a in myList: > ... > > will result in an implicit iterator on myList. How would you create an > explicit iterator object of myList? the built-in iter() function will do this for you: >>> L = [1, 2, 3, 4, 5] >>> I = iter(L) >>> L [1, 2, 3, 4, 5] >>> I >>> I.next() 1 >>> for i in I: ... print i ... 2 3 4 5 >>> I.next() Traceback (most recent call last): File "", line 1, in ? StopIteration From opengeometry at NOSPAM.yahoo.ca Tue Jul 2 16:51:07 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 2 Jul 2002 20:51:07 GMT Subject: Splitting Text files References: <%XnU8.4057$aJ4.853781@news20.bellglobal.com> Message-ID: Ken Seergobin wrote: > "William Park" wrote in message > news:aft0r5$go61b$3 at ID-99293.news.dfncis.de... > >> Perhaps, you should remove 'X-No-Archive'. Most people won't give >> answers, let alone reply, to such posts. > > Personally, I'm not thrilled by every scrap of information being > recorded. However, if the no-archive option makes getting information > easier the content of the original post will be repeated in this message. > (That said, I do understand why posts like these should be archived.) > > Original Post: > > I've looked around, but have been unable to locate a good example of how > to split a text file. Specifically, I have datafiles with an > identification line marked with the name of a BMP file followed by many > lines of data. This repeats a number of times for each datafile. Within > the data lines I'm only interested in extracting the those with a > specific keyword. Ultimately, I'd like to have a datafile for each BMP > listed in the original file. > > Suggestions would be appreciated. I really couldn't make sense of the > regular expression notes I found. > > Thanks, > Ken I'm guessing that your data file looks something like file1.bmp ...... ... file2.bmp ...... ... file3.bmp ... 1. In shell, you'd do like csplit file '/\w*\.bmp/' '{*}' --> xx00, xx01, ... mv xx00 file1.bmp mv xx01 file2.bmp ... 2. However, since you're only interested in those data lines with certain keywords, simply do egrep -e '^file[0-9]\.bmp$' -e 'your_search_pattern' file or for x in xx[0-9][0-9]; do egrep 'your_search_pattern' $i done Translating these to Python is left as exercise for readers. ;-) -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From kxuqxf at yahoo.com Sat Jul 13 00:28:52 2002 From: kxuqxf at yahoo.com (kxuqxf at yahoo.com) Date: Sat, 13 Jul 2002 04:28:52 +0000 (UTC) Subject: Psychic Seduction for attracting the girl you want - Free Download 2433 Message-ID: http://seduction.best2web.com MIND POWER SEDUCTION FREE DOWNLOAD AVAILABLE NOW. Click the above link to get it Get the girl you wanted with MIND POWER SEDUCTION Irresistible Hypnotic Mind Control Imagine being able to sensually attract anyone at will... attract women & men with subliminal mind control disciplines Say nothing and watch as perfect strangers fall into a deep state of enthrallment... Penetrate the minds of others and unleash charisma so potent and long lasting... Would you like to discover a secret that allows you to generate extreme fascination in anyone with your thoughts alone? The secrets of mind control have largely been untapped. Now, the knowledge of hypnotic seduction has been revealed. It is pure mind control power to influence, attract and more... Secretly tantalize and attract women or the opposite sex with covert mind control techniques, right in their presence! Generate instant charisma! attract women & men with subliminal mind control disciplines Easily master long-range remote influence with scientifically verified telepathic mind control powers. No special skills needed! Mind Power Seduction is a uni-sex discipline that naturally infuses you with irresistible covert seduction skills in 30 days! http://seduction.best2web.com hqwndjimluutpsleyiuvruqqjywczhlfkxyhpmgwpj rsxfzxwuwlhim From matt_gerrans at hp.com Wed Jul 10 14:52:53 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Wed, 10 Jul 2002 11:52:53 -0700 Subject: Excel type 'time' conversion to string problem References: Message-ID: I'm not sure if this is the same time object returned in the FindFiles() tuple, but if it is, it has a Format() method that will return something you can print: >>> import win32api >>> sometime = win32api.FindFiles(r'c:\*.*')[0][1] >>> sometime.Format() '06/03/02 19:04:52' If this doesn't look good to you, you want to format it differently yourself, you can get at the properties like so: >>> sometime.year 2002 >>> sometime.month 6 >>> sometime.day 3 >>> sometime.hour 19 And so on. You could also pack all this into a tuple that looks like what you get from time.localtime(), then you could use asctime() on it (actually, maybe there is a way to do that directly? I don't know...). - Matt From spam at aturuxo.net Sun Jul 14 07:00:59 2002 From: spam at aturuxo.net (Afonso Fernandez Nogueira) Date: Sun, 14 Jul 2002 13:00:59 +0200 Subject: isA function? References: Message-ID: <003801c22b25$c045cf20$28e4533e@fonso> > We're writing some unit tests, and one of the tests is "foo() returns > something which isA (bar)". I read this yesterday, and I think it could be an interesting reading about the mentioned builtin. "isinstance() considered harmful": http://www.mail-archive.com/kragen-tol at canonical.org/msg00007.html fonso From whisper at oz.net Wed Jul 31 17:54:58 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 31 Jul 2002 14:54:58 -0700 Subject: 'import mod_python' fails In-Reply-To: <158d3913.0207311316.6e2b3e7b@posting.google.com> Message-ID: I have mod_python running on Apache on a windows box - no problem. You should have a directory called "mod_python" in python22/lib/site-packages - if you don't, you don't have mod_python properly installed. It is more then just a matter of putting mod_python.so in the apache/modules dir and modifying httpd.conf to load it (that only takes care of the Apache side of things). Try running "setup.py" in the mod_python dist directory. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Bittner > Sent: Wednesday, July 31, 2002 14:17 > To: python-list at python.org > Subject: 'import mod_python' fails > > > Hi there! > > I have a question about getting mod_python to run. (Please do not > flame me, I know there is a mod_python mailing list!) > > I have SuSE Linux 8.0 and I have Python, mod_python and Apache > installed using YaST, the SuSE setup tool. At the first glance > everything seems alright (Apache shows at startup that it does load > the mod_python module.) But I can .py-scripts be executed, because > (mod_)python fails to import the Python module 'mod_python': > > > >>> from mod_python import apache > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: No module named mod_python > > I don't know if this helps, but I have searched my whole system and > there is no file named 'mod_python.pyo' anywhere! > > I'd really be happy about any help to make me get running mod_python > on my Apache! Please help! > Cheers, Peter > -- > http://mail.python.org/mailman/listinfo/python-list From rs at onsitetech.com Mon Jul 8 17:46:20 2002 From: rs at onsitetech.com (Robb Shecter) Date: 08 Jul 2002 21:46:20 GMT Subject: Why self? References: Message-ID: <3D2A07DE.10303@onsitetech.com> Brian Quinlan wrote: >... Actually, private instance > variables are uncommon in general. > Sounds like a difference in design philosophies. In my code, private everything is the norm, with a very thin/small public API. > Python forces you to be explicit. That way we will know what you are > doing, right or wrong. Mmmm - I dunno; I think this same argument could be used in the Java world for some of the things the language forces you to do, like explicit casting and declarations: String name = (String) aVector.element(0) Python doesn't have any problems with implicitness here... From peter.maas at mplusr.de Thu Jul 18 09:44:58 2002 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 18 Jul 2002 15:44:58 +0200 Subject: property problem Message-ID: <3D36C65A.5040300@mplusr.de> Hi, while experimenting with class properties using Python 2.2.1 I encountered the following weird behaviour: This is my testclass: class proptest: def __init__(self): self.__data = 0 def get_data(self): return self.__data def set_data(self, value): self.__data = value data = property(get_data, set_data) def meth(self): return self.__data This is my testcode: >>> x = proptest() >>> x.data=234 >>> x.data 234 >>> x.meth() 0 >>> x.set_data(234) >>> x.meth() 234 Explanation: The "data" property works but a change using the property name doesn't show in meth(). If I use the access function set_data it works as expected. Is it my fault or Python's? Thanks for your help. Regards, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From fredrik at pythonware.com Fri Jul 19 04:21:30 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 Jul 2002 08:21:30 GMT Subject: ANN: Pyrex 0.3.4 References: Message-ID: Matthias Baas wrote: > I thought you only need that if you import the dll through an > import library which Python doesn't do. nope. without dllexport (or a DEF file or an exports directive to the linker), the module's init function won't be exported. if it's not exported, Python's PYD loader refuses to load the module. the correct solution (in 2.2 and earlier) is to use the DL_EXPORT macro, which is set to the right thing for whatever platform you're using. From pan-newsreader at thomas-guettler.de Sat Jul 27 14:53:06 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Sat, 27 Jul 2002 20:53:06 +0200 Subject: Image Loading References: Message-ID: On Sat, 27 Jul 2002 05:14:18 +0200, Ali K wrote: > How do you load a picture inside a frame? What do you mean with "frame"? Do you want to write a GUI application? Which toolkit do you want to use? (pygtk, tkinter, wxpython)? Which platform do you use (Python, Operating System Version)? Do you want to write a web application? thomas From mgilfix at eecs.tufts.edu Wed Jul 31 10:21:03 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 31 Jul 2002 10:21:03 -0400 Subject: Python equivalent to 'which'? In-Reply-To: <3D46D2E3.4000008@ActiveState.com>; from DavidA@ActiveState.com on Tue, Jul 30, 2002 at 10:54:43AM -0700 References: <3D46D2E3.4000008@ActiveState.com> Message-ID: <20020731102102.B26901@eecs.tufts.edu> This module looks pretty good and does seem kinda appropriate. I wonder why Tent Mick hasn't suggested it? -- Mike On Tue, Jul 30 @ 10:54, David Ascher wrote: > Doing 'which' right is actually fairly complicated -- Trent Mick has the > best version I know of at: http://starship.python.net/~tmick/ > > """ > GNU which is a common command line app on Unix. There are Windows ports > (for example, the one in the Cygwin distribution), though I find the > ones I have seen to be a little stupid. They don't understand the use of > the PATHEXT environment variable. They don't support the useful '-a' > option to listing all matches on the current PATH. > > This which has the following features: > > it is portable (Windows, Linux); > it understands PATHEXT on Windows; > it can print all matches on the PATH; > it can note "near misses" on the PATH (e.g. files that match but may > not, say, have execute permissions); and > it can be used as a Python module. > """ `-> (DavidA) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From jdhunter at nitace.bsd.uchicago.edu Mon Jul 15 19:28:06 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Jul 2002 18:28:06 -0500 Subject: how can I do this? References: Message-ID: >>>>> "Eric" == Eric Yohanson writes: Eric> I would like to know if it is possible in python 2.21 to Eric> make a text entry widget that initially show nothing but Eric> when the user type the first character displays a template Eric> like "00#00:01+2" for the previous I have only enter the Eric> numbers 1 & 2. the numbers would need to enter from right Eric> and travel to the left as more are entered replacing the "0" Eric> place holders. How difficult would this be to do and what Eric> should my approach be to this. Any help wuld be great. Getting sinlge chars in python is platform and GUI dependent (search for getchar on groups.google.com in comp.lang.python for some suggestions). But assuming you can get the chars, here is some code that will do the template substitution. I use a list of chars as input. I found it easier to do this by first flipping the template string from left to right and using python's index function, which searches from the left. import string def fliplr(s): "flip the string s from left to right" out = '' for i in range(len(s)-1, -1, -1): out += s[i] return out def replchars(template, chars, token='0'): "replace the kth instance of token in template with chars[k]" out = map(None, template) # out is a list of chars in template for c in chars: ind = out.index(token) if ind==-1: raise ValueError, 'Could not find token %s in template' out[ind] = c return string.join(out, "") template = "00#00:00+0" chars = ['1', '2', '3', '4', '5', '6', '7'] rtemplate = fliplr(template) for i in range( len(chars) ): rchars = fliplr( chars[0:i+1] ) print fliplr( replchars( rtemplate, rchars) ) The output is: 00#00:00+1 00#00:01+2 00#00:12+3 00#01:23+4 00#12:34+5 01#23:45+6 12#34:56+7 Here's a shorter, but possibly more obscure version: import string def rsub(template, chars, token='0'): out = map(None, template) # get the indicies of the tokens in reverse order inds = [ i for i in range(len(template)-1, -1, -1) if template[i]==token] N = len(chars) for i in range( len(chars) ): out[inds[i]] = chars[N-i-1] return string.join(out, "") template = "00#00:00+0" chars = ['1', '2', '3', '4', '5', '6', '7'] for i in range( len(chars)) : print rsub(template, chars[0:i+1]) HTH, JDH From c at coryadams.com Tue Jul 16 17:46:55 2002 From: c at coryadams.com (CA) Date: Tue, 16 Jul 2002 15:46:55 -0600 Subject: Writing a secure web client? Message-ID: <3D34944F.DE1F2C5C@coryadams.com> I am trying to write a web client in python that first authenticates to a secure url, then posts to a form using the secure session cookie. The problem that I am having is follows: I can post to the secure form and get the session cookie back into a Cookie.SmartCookie. How do I use this cookie to subsequently post to a form using that session id? For example: http://domain.com/restricted/login.cgi Post here, get cookie http://domain.com/restricted/stuff/dosomething.cgi Now post to this form, or others below /restricted Any help would be greatly appreciated. Thanks, CA From max at alcyone.com Tue Jul 23 16:35:47 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 23 Jul 2002 13:35:47 -0700 Subject: ANN: empy 1.0 -- Embed Python in template text as markup Message-ID: <3D3DBE23.4E164323@alcyone.com> Summary empy (formerly Munch) is a system for embedding Python expressions and statements in template text (or any other unexecuted content); it takes source files, processes them, and produces output. These are done via expansions, which are snippets of Python code delimited by character sequences involving a special prefix (by default the at sign, '@'), and are substituted in the output with the return value (for expressions) or with any in-Python printing to stdout that takes place (for both expressions and statements). If the value of an evaluated expression is None, nothing is expanded (that is, it acts like the interactive Python interpreter). Textual data not explicitly delimited in this way is sent unaffected to the output file, allowing Python to be used in effect as a markup language. Explicit expansion, or inclusion of other files to be expanded, is possible. Also supported are m4-style diversions, where output can be systematically deferred and recalled. Expressions are embedded in text with the '@(...)' notation; as a shortcut, simple variables and expressions can be abbreviated as '@variable', '@object.attribute', '@array' [index], '@function(arguments)', or variations. Full-fledged statements are embedded with '@{...}'. A '@' followed by a whitespace character (including a newline) expands to nothing, allowing line continuations. Comments are indicated with '@#' and consume the rest of the line, including the trailing newline. A '@@' sequence expands to a single literal at sign. Getting the software The software is available in a tarball here: http://www.alcyone.com/pyos/empy/empy-1.0.tar.gz. The official URL for this Web site is http://www.alcyone.com/pyos/empy/. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From cliechti at gmx.net Tue Jul 23 13:42:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 19:42:11 +0200 Subject: how to count lines in a file ? References: Message-ID: "Shagshag13" wrote in news:ahk3la$tf3bh$1 at ID- 146704.news.dfncis.de: > here is a test in counting [6871785] lines from a file of > 1Go > > --- > lineCount = 0 > fhi = file(filename) > for line in xreadlines.xreadlines(fhi): note that a fileobject has an xreadlines method. no need to use the module > lineCount += 1 > > return lineCount > > [Eof processing] : 00:01:22 > --- > lines = 0: > for line in file(filename): > lines += 1 > > [Eof processing] : 00:01:22 it's not a coincidence that the times are equal as iterating through a file with "for line in file()" is just a shortcut for "for line in file().xreadlines()" > --- > lineCount = 0 > fp = open(filename) > it = iter(fp) > try: > while it.next(): > lineCount += 1 > except StopIteration: > pass > > return lineCount > > [Eof processing] : 00:01:42 as I just meantioned in an other message, that's just handcoding of "for line in file()" and ignoring the "line" variable. it is slower because the call to next is done in python, whereas the "for" solution does this internally (in C). all code you show is basicaly the same. the middle solution is the most readble in my opinion. chris -- Chris From martin at v.loewis.de Tue Jul 9 14:48:53 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Jul 2002 20:48:53 +0200 Subject: Multi language software development? References: <3D2B1E91.4070102@gmx.de> Message-ID: Ingo Linkweiler writes: > One way is to replace all strings by variables, and put the > variables in a module. Do you know other good ways to develop > software for more than one language and to translate existing > software? I recommend to use the gettext module. Regards, Martin From jknapka at earthlink.net Tue Jul 9 16:31:40 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 09 Jul 2002 20:31:40 GMT Subject: 8 Queens Problem References: Message-ID: <3D2B479D.40513CF4@earthlink.net> Simon.Foster at smiths-aerospace.com wrote: > > Just For Fun! > > I've been working on a solution to the eigth queens puzzle. > Here is my attempt. There's a solution in Scheme in SICP > which takes only 13 lines. Can anyone come up with a shorter > solution in Python, without any of the obvious silliness? Sure :-) from operator import add size=8 def attacks((r1,c1),(r2,c2)): return ((r1,c1) != (r2,c2)) and ((r1==r2) or (abs(r1-r2)==abs(c1-c2))) def check(n): qpos = map(lambda c: ((n/(size**c))%size,c),range(size)) return reduce(add,[reduce(add,[attacks(qpos[q],qpos[o]) for o in range(size)]) for q in range(size)]) for n in xrange(size**size): if not check(n): print "Solution:",map(lambda c: ((n/(size**c))%size,c),range(size)) It gives you the coordinates of the queens' board positions, and finds all solutions by exhaustive search. It isn't exactly fast, though. Set size=4 to solve the 4-queens problem before you die. It exchanges obvious silliness for obscure silliness. I'm sure Alex can improve this lots. Cheers, -- Joe From lac at strakt.com Fri Jul 5 15:18:10 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 05 Jul 2002 21:18:10 +0200 Subject: adding methods on the fly In-Reply-To: Message from Alex Martelli of "Fri, 05 Jul 2002 17:02:05 GMT." References: Message-ID: <200207051918.g65JIALM018771@ratthing-b246.strakt.com> > For an example, see > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 > (or, better, the expanded and clarified version in the printed > Python Cookbook, ed. Martelli and Ascher, but that's only due out > in 3 weeks, so, meanwhile, the original online version will do:-). > > > Alex Hmmm, how much work will there be to make the on-line version compatible with the book? Is that the intention? Laura From Gabe.Newcomb at noetix.com Fri Jul 26 17:54:09 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Fri, 26 Jul 2002 14:54:09 -0700 Subject: PythonWin ODBC: DSN-less connecting string Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F615D@NOXMAIL.noetixad.com> I'm unable to find the right combination of options to build a DSN-less connection string with which I can connect to a database using the odbc module. Has anybody out there found the right way to do this? From neal at metaslash.com Thu Jul 11 22:36:49 2002 From: neal at metaslash.com (Neal Norwitz) Date: Fri, 12 Jul 2002 02:36:49 GMT Subject: compiler package References: Message-ID: On Mon, 08 Jul 2002 15:11:16 -0400, Thomas Heller wrote: > Has anyone used the compiler package to compile Python source code to > other languages? Is there anything to get started? The work Jeremy Hylton has been doing on a new compiler might be able to help. Check out the sandbox or the current CVS using the ast tag. The sandbox can be viewed here: http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/nondist/sandbox/ast/ >From CVS, the path is: python/nondist/sandbox/ast Neal From fperez528 at yahoo.com Fri Jul 19 14:00:55 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 19 Jul 2002 12:00:55 -0600 Subject: Renting CPU time for a Python script References: <25c15ddd.0207190852.2aecc26c@posting.google.com> Message-ID: Zachary Bortolot wrote: > Hello Everyone, > > I am a graduate student conducting research on using computer vision > techniques to process digital air photos. As part of my research I am > using a genetic optimization routine that I wrote in Python to find > values for several key parameters. Unfortunately the genetic > algorithm is quite CPU intensive, and each run requires anywhere from > five to twelve days to complete on a 450MHz Pentium II. This is > problematic since I have to run the program in a computing lab that is > frequently used for teaching, which means that I am often unable to > complete my runs. I would like to know if anyone has any suggestions > on where I might go to rent CPU time that is Python and PIL friendly > (the university I am at does have an AIX-based mainframe, but Python > is not installed and users are only given 600k of disk space). Speed > is not a major issue for me and the program does not use a lot of > memory or disk space. However, stability is a definite must. Thanks > in advance for any advice or suggestions! 5 to 12 days is a lot. Have you profiled this thing to find the bottlenecks? At that point a few weeks spent on writing the time-critical parts in C would be well spent time, I think. On the other hand if you've already optimized this to death and 5 to 12 days is the best you can get, good luck. At any rate, any algorithm that takes that long to run should incorporate checkpointing and restarting capabilities. That way if a machine crashes or your lab stops your runs, you only lose a few hours of cpu time. If you can save the state of the code in an object, you can even (using pickle) very easily move a job from one machine to another in mid-run. The stability of your environment should be a non-issue in terms of the survival of your runs. So I'd recommend: 1- code in automatic checkpointing and self-restarting abilities. It's fairly easy to do, and saves a lot of headaches. 2- profile your code. See if there are bottlenecks in python left. Without seeing your code I can't say, but if you have numerical bottlenecks, Numeric might help. If not, look at weave (scipy.org). It's often enough and faster than writing a full blown extension by hand. Pyrex is another option. Finally writing the extension yourself isn't really that difficult, SWIG is pretty good (weave can also help there quite a bit). 3- Once your code is optimized in C and self-restarting, you can distribute runs over that lab without any problem. Just have your jobs get their state from a server on the network so they can migrate automatically, and you should be able to 'fire and forget'. With a central job manager keeping track of what's been done, you can just set runs for a month and collect the results at the end. Cheers, f. From danieleburrow at yahoo.com Fri Jul 19 13:58:57 2002 From: danieleburrow at yahoo.com (Daniel E. Burrow) Date: 19 Jul 2002 10:58:57 -0700 Subject: Internet Explorer Automation Object Crossframe Element Troubles References: <7xn0sobjg8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xn0sobjg8.fsf at ruckus.brouhaha.com>... > danieleburrow at yahoo.com (Daniel E. Burrow) writes: > > I am able to fire cross-frame elements now but doing so in the manner > > shown in the *** ClickCrossFrameElement *** method below troubles me > > greatly: ... > > What is troubling you? Greetings! I did not understand why I had to specify "Document" and then "document". I now understand that I am gaining access to the full DOM by the first "Document" and then access to the "document" collection by the second "document". My method now looks as follows: def ClickCrossFrameElement(self, i_FrameId, s_ElementNameOrId): o_IE_Dom = self.o_IE.Document o_IE_Dom.frames[i_FrameId].document.all(s_ElementNameOrId).click() Your reply is most welcome. Mr. Hammond deserves heralded accolades for what he has given and continues to give to the Python world. Joyfully, Daniel From graham at effectif.com Sat Jul 6 12:27:23 2002 From: graham at effectif.com (Graham Ashton) Date: Sat, 06 Jul 2002 17:27:23 +0100 Subject: Understanding properties Message-ID: I clearly don't get it. I just tried a simple test: class MyObject: def __init__(self): self.__size = 0 def getSize(self): print "getSize() called" return self.__size def setSize(self, s): print "setSize(%s) called" % size self.__size = s size = property(getSize, setSize, None, 'Size of instance') if __name__ == '__main__': o = MyObject() size = o.size print "original size:", size o.size = 10 size = o.size print "new size:", size When I run it I get: % python MyStuff.py getSize() called original size: 0 new size: 10 I was expecting to see several calls to getSize() and a call to setSize(), but I think when I do "o.size = 10" the setSize() method (as set by the property) isn't kicking in. What am I missing? Thanks. -- Graham From whisper at oz.net Wed Jul 10 15:23:14 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 12:23:14 -0700 Subject: os.path and Windows UNC paths In-Reply-To: <9ecef7534b.tim@worthy.demon.co.uk> Message-ID: > As an aside; > > using os.path.isdir(r'\\server\share\') results in a complaint of > invalid token - I thought the r prefix meant use raw string, so why the > error ? the trailing \ is escaping the ending ' of the r'...' string. I just ran across the caution about having odd numbers of \ at the end of an r'...' string last evening. HTH, Dave LeBlanc Seattle, WA USA From rob Sat Jul 20 13:28:08 2002 From: rob (Rob Andrews) Date: Sat, 20 Jul 2002 17:28:08 GMT Subject: Python 2.3 References: Message-ID: > True Division? Darn it, i'm used to false division! Where is "to __past__ > deport ..."? ;-) > Perhaps that sort of thing is intended for the next release. Try: from __future__ import past # snicker Rob Andrews http://uselesspython.com From wjdandreta at worldnet.att.net Fri Jul 26 10:26:15 2002 From: wjdandreta at worldnet.att.net (Bill Dandreta) Date: Fri, 26 Jul 2002 14:26:15 GMT Subject: Best way to populate a wxListCtrl widget from mysql References: <75f0ku48rojqeqo7bs5il2df1vf55bg5pb@4ax.com> Message-ID: <3d415a50.3394307@netnews.worldnet.att.net> Hi Arneau, >What is the best way to populate a wxListCtrl from a Mysql query (may >return more that one result). I would then Like to select one or more >from the displayed results and perform another action on them. Any >help so that I don't waste alot of time going in the wrong direction. Let me preface my remarks by saying that I am a newbie with wxPython. I am using Boa Constructor to help me build apps and learn. I just did what you are trying to do with a wxGrid instead of a wxListCtrl. Here are some code snippets to look at: --SORT THE ROWS FROM QUERY-- self.rows=list(cursor.fetchall()) self.rows.sort(lambda x,y:cmp(x[3],y[3])) --DISPLAY ROWS UPTO A MAXIMUM OF 10-- for i in range(0,10): if i>lastrownum: self.grid1.SetCellValue(i, 0, '') self.grid1.SetCellValue(i, 1, '') self.grid1.SetCellValue(i, 2, '') self.grid1.SetCellValue(i, 3, '') else: j=i+self.lastrowdisplayed+1 mfr = self.getmfr(self.rows[j][0]) self.grid1.SetCellValue(i, 0, self.rows[j][0] + '-' + \ self.rows[j][1]) self.grid1.SetCellValue(i, 1, mfr) self.grid1.SetCellValue(i, 2, self.rows[j][3]) self.grid1.SetCellValue(i, 3, self.rows[j][4]) --EVENT HANDLER FOR LEFT CLICK ON GRIDCELL-- def OnCellLeftClick(self, event): self.showprices(event.GetRow()) I have not even looked at the wxListCtrl yet so I don't know if it is a better choice. Bill From jonathan at onegoodidea.com Wed Jul 10 08:28:37 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 10 Jul 2002 13:28:37 +0100 Subject: sorting many arrays from one... References: <%KCW8.60416$vm5.2194409@news2.tin.it> <3D2B0973.B553A25F@info.unicaen.fr> <15FW8.61099$vm5.2221340@news2.tin.it> <3D2C0117.89BCDC43@info.unicaen.fr> Message-ID: On 10/7/2002 11:38, in article l8UW8.47032$n4.11332104 at newsc.telia.net, "Fredrik Lundh" wrote: > Jerzy Karczmarczuk wrote: > >> Shall I repeat it once more? I think that the call overhead should be >> perhaps better optimised, and if it seems difficult, I would like to >> know why. > > you have the full source code, like everyone else. I suggest > starting in the docompare() function in Objects/listobject.c... > > if you find some small change that would cause a major speedup, > try it out, and post the patch if it seems to work. if you suggest > that we throw away what we have and start over from scratch, > please bring lots of food and money to the party... Out of curiosity I took a look at the code and I could only think of one optimisation: Index: listobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v retrieving revision 2.114 diff -r2.114 listobject.c 775c775 < args = Py_BuildValue("(OO)", x, y); --- > args = PyTuple_New(2); 777a778,781 > PyTuple_SetItem(args, 0, x); > Py_INCREF(x); > PyTuple_SetItem(args, 1, y); > Py_INCREF(y); This takes the difference between '.sort()' and '.sort(cmp)' for a list of integers down from 6.5x slower to 4.5x slower on my machine (300,000 element list). But the improvement is fairly marginal in my book since, unless your comparison function is a C function, invoking the bytecode interpreter makes it at least 10x slower (12x slower without the above change). Beyond that I couldn't see much in the way of obvious changes that could be made. It just fundamentally takes a non-zero amount of time to make a PyObject_Call and if you make 5 million of them in rapid succession then it adds up. Jonathan From peter at engcorp.com Mon Jul 8 19:48:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 19:48:56 -0400 Subject: private References: Message-ID: <3D2A24E8.AD74E2F5@engcorp.com> Matt Gerrans wrote: > > > Ok, here's a challenge for you... Write a C++ program with private data > > members, then find at least two trivial ways of circumventing it. > > And when you've completed this exercise in C++, try it in Java. ;-) Isn't the access information like "private" and "protected" just included as flag bits in the .class file? That would make it pretty easy to change... -Peter From bhan at andrew.cmu.edu Wed Jul 31 23:59:47 2002 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Wed, 31 Jul 2002 23:59:47 -0400 Subject: copy.deepcopy(): is it bug or intended behavior? In-Reply-To: References: Message-ID: <200207312359.47726.bhan@andrew.cmu.edu> Curiously if I added __deepcopy__ to class Bar (replace Bar with the following class def): class Bar (list): def __deepcopy__ (self,memo): obj=Bar() memo[id(self)]=obj for e in self: obj.append(copy.deepcopy(e,memo)) for k,v in self.__dict__.iteritems(): obj.__dict__[k]=copy.deepcopy(v,memo) return obj then the result is correct: [[1]] 135743596 [[2]] 135787484 ---------------------------------------------------------------------- [[1]] 135760188 [[2]] 135626380 Ben On Wednesday 31 July 2002 07:59 pm, you wrote: > This is an abstract of the actual code: > > --- cut here --- > import copy > > class Foo: > def clone (self): > return copy.deepcopy(self) > > class Bar (list): > pass > > class Const: > def __init__ (self, data): > self.data=data > def __repr__ (self): > return str(self.data) > > n1=Foo() > n1.t=[] > c=Bar() > c.append(Const('1')) > n1.t.append(c) > > n2=Foo() > n2.t=[] > c=Bar() > c.append(Const('2')) > n2.t.append(c) > > g=Foo() > g.hd=[] > g.hd.append(n1) > g.hd.append(n2) > > print g.hd[0].t,id(g.hd[0].t) > print g.hd[1].t,id(g.hd[1].t) > > print > '----------------------------------------------------------------------' > > h=g.clone() > > print h.hd[0].t,id(h.hd[0].t) > print h.hd[1].t,id(h.hd[1].t) > > --- cut here --- > > > Running on Python 2.2.1 gave the following output: > > [[1]] 135743596 > [[2]] 135759124 > ---------------------------------------------------------------------- > [[1]] 135505252 > [[1]] 135793916 > > > But the last line should have "[[2]]...". Am I missing something here? > > Thanks, > > Ben From joost_jacob at hotmail.com Fri Jul 26 17:27:25 2002 From: joost_jacob at hotmail.com (J.Jacob) Date: 26 Jul 2002 14:27:25 -0700 Subject: turtle module information Message-ID: <13285ea2.0207261327.2827b3a6@posting.google.com> The turtle module is very nice. I would like to know if there is any more information about the turtle module available? Of course there is the turtle.py file in C:\Python*\Lib\tk* but I am also interested in things like who wrote it and design decisions. Is it possible to change the font used by turtle.(Raw_Pen).write() ? From erkyrath at eblong.com Wed Jul 10 11:36:38 2002 From: erkyrath at eblong.com (Andrew Plotkin) Date: Wed, 10 Jul 2002 15:36:38 +0000 (UTC) Subject: Z-machine/Infocom interpreter in Python? References: <3D2BE29E.4C49B91C@alcyone.com> Message-ID: In rec.arts.int-fiction, Erik Max Francis wrote: > Anyone know of a Python library for interpreting Infocom Z-machine > games, up to at least z5 (or whichever the version is _before_ the one > that had support for graphics and sound, I have no need for that)? There was a Perl Z-code interpreter. I don't see it on the Archive, but do a web search under "Rezrov". I believe it's written to be a normal application, not a chat plug-in, but converting it might be easier than converting a C application. I don't recall a Python interpreter. I'm in favor of one, though. :) Then there's Floyd, the bot who hangs out on IFMud and does more or less this job. I'm not sure what he's written in. I suspect pipes and hackery are involved. > I'm looking for something that can be hooked into chat systems so that > people can send it messages (as commands) and get back the results. I > can't recall whether the status line in Z needs to be treated specially > or not. Z5 and Z8 are what you're looking for. Z6 was the graphics-supporting version. (Z8 is not graphical; it's a minor variant of Z5 with a different memory map, so most interpreters that support 5 also support 8.) The status line would have to be dealt with specially. The simplest plan is to have the system intercept a particular command ("$STATUS" maybe) and dump the status window. --Z "And Aholibamah bare Jeush, and Jaalam, and Korah: these were the borogoves..." * * Make your vote count. Get your vote counted. From aleax at aleax.it Wed Jul 24 11:56:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 15:56:28 GMT Subject: xml processing : too slow... References: Message-ID: Shagshag13 wrote: ... > yes, but i use minidom on a small amount of data at once because i do > something like : > > f = file(filename) > while 1: > line = f.readline() > if line.find(' xmlLine = parseString(line) > # do some processing to flatten xml > # write to output file > else: > # write to output file > > and yes i use it to do for well-formedness So you need EACH separate line to be a well-formed XML document in its own right, or else include no closing-tag? I'm confused. This is so far from XML that you MAY be better off doing your own homebrewed parsing, depending on what other extra constraints you may count on wrt normal XML. Alex From maxm at mxm.dk Tue Jul 2 02:03:02 2002 From: maxm at mxm.dk (Max M) Date: Tue, 02 Jul 2002 08:03:02 +0200 Subject: [NEWBIE]-Object referencing?? References: Message-ID: <3D214216.8000008@mxm.dk> Alistair Campbell wrote: > I assign data from a file so the data that goes into the alcohol method > needs to be converted from string. You should probably use int() then:: def alcohol(self): return ((int(self.hydro_init)-int(self.hydro_final))*0.00036251)*10 > The problem is that when I try to reference an instantiation of the Brew() > class, i.e; > > current_brew=Brew() > > I can get all the other data items but a call to; > > current_brew.alcohol > > returns > > This is because you do not call the method, but you just reference it. To call it you need to add perenthesis:: current_brew.alcohol() Unlike VB you must state explicitly that you want to call a function/method. You can pass a funcion like any other object in Python. You could even do:: get_alcohol = current_brew.alcohol get_alcohol() regards Max M From graumann at clyde.caltech.edu Fri Jul 19 11:58:44 2002 From: graumann at clyde.caltech.edu (Johannes Graumann) Date: 19 Jul 2002 15:58:44 GMT Subject: NEW TO THIS: Assigning values to strings in list? Message-ID: Hello, As stated in the subject, I'm new to this - but I think with this question I might be already headed for my first good burn ;0) Basicely I have two lists, one containing the future string-names and one containing the values I want to give them. The order is identical in both. Right now I'm solving this by a dictionary, but I would really prefer to have straight strings as a result of my operation. Can anybody please tell me how to go about this and/or why I totally shouldn't do this? Thanks, Joh -- From peter at engcorp.com Wed Jul 31 08:21:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 31 Jul 2002 08:21:21 -0400 Subject: How do you import a module with "." in its filename? References: Message-ID: <3D47D641.E9CF0589@engcorp.com> Duncan Booth wrote: > > "Keith Dart" wrote in > news:xsP19.36095$Zw6.135530681 at newssvr21.news.prodigy.com: > > > But.... why bother? Why not just rename the original modules to > > a_test.py, etc.? That's what I do. > > Well, the OP said: > > For both practical and political reasons, renaming a.test.py to a_test.py > > is not an option. > > I'm not entirely sure I believe there are practical reasons, but the > politics may well be insurmountable. I have to say if I worked in a place where renaming files became a loaded political issue, I would be leaving in a hurry. Like, the next day! That's insane. -Peter From elf at drizzle.com Mon Jul 8 20:13:57 2002 From: elf at drizzle.com (Elf M. Sternberg) Date: Mon, 8 Jul 2002 17:13:57 -0700 Subject: Python extensions deep in a heirarchy? Message-ID: I want to have a namespace with python 'C' extensions deeper into the heirarchy than just one directory. For example: foo/logging/mylogging.so __init__.py __init__.py __init__.py But for some reason I can't seem to get python to recognize the extension when it's this deep. Are there any examples where folks have mananged to make this work? It's driving me nuts. What would I put into "InitModule"? foo.logging.mylogging or just mylogging? How would I find it once I'd used it? Any help will be greatly appreciated! Elf -- Elf M. Sternberg http://www.drizzle.com/~elf/ (under construction) From andrewm at object-craft.com.au Wed Jul 17 02:33:53 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 17 Jul 2002 16:33:53 +1000 Subject: simultaneous iteration of lists In-Reply-To: Your message of "Thu, 18 Jul 2002 02:24:46 +1000." <20020718022446.A728@dave@jessica.ucc.usyd.edu.au> Message-ID: <20020717063353.F405738F61@coffee.object-craft.com.au> >The syntax that is in the back of my brain looks something like > >for i,j in list1,list2: > print i > print j Try this: for i, j in zip(list1, list2): print i, j -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From gerhard.haering at gmx.de Sat Jul 20 11:02:15 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Jul 2002 15:02:15 GMT Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <1027175934.94979.0@iris.uk.clara.net> Message-ID: Gerhard H?ring wrote in comp.lang.python: > Richard Townsend wrote in comp.lang.python: >> "Rhymes" wrote: >>> >>> When Python 2.3 will be released? >> >> Also, is there likely to be a 2.2.2 ? > > Yes. > > Btw. to look what the Python developers are up to, you can read the > python-dev archives (http://mail.python.org/pipermail/python-dev/). Actually, there is a nicer searchable interface for the Python lists at ActiveState. Here for python-dev: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-dev Just don't try to enter "2.2.2" ;-) (I already reported this bug in their search code to ActiveState). Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From petitmermet at mat.ethz.ch Tue Jul 30 05:19:05 2002 From: petitmermet at mat.ethz.ch (Marc Petitmermet) Date: Tue, 30 Jul 2002 11:19:05 +0200 Subject: python 2.1.3 with tkinter support on Solaris 9 Message-ID: I still cannot compile python 2.1.3 with tkinter support on Solaris 9. I have configured the environmental paths LD_LIBRARY_PATH, LD_RUN_PATH, the Modules/Setup file and even adjusted the /var/ld/ld.config with crle to include the libraries of tcl and tk libraries. The problem ist that setup.py still complains that it cannot find libtk8.3.so although the it is located in /p1/local/tcltk/tk-8.3.4 as configure Modules/Setup (see below). Can anybody tell me what I'm doing wrong? Thanks in advance. Regards, Marc ------------ gcc -o python \ Modules/python.o \ libpython2.1.a -lpthread -lsocket -lnsl -ldl -lthread -L/usr/local/ssl/lib -lssl -lcrypto -lnsl -L/p1/local/tcltk/tcl-8.3.4/lib -L/p1/local/tcltk/tk-8.3.4/lib -ltk8.3 -ltcl8.3 -L/usr/X11R6/lib -L/usr/openwin/lib -lX11 -lm PYTHONPATH= ./python ./setup.py build ld.so.1: ./python: fatal: libtk8.3.so: open failed: No such file or directory Killed From dreed at capital.edu Thu Jul 18 13:52:21 2002 From: dreed at capital.edu (Dave Reed) Date: Thu, 18 Jul 2002 13:52:21 -0400 Subject: How to set tempfile.tmpdir? In-Reply-To: (message from Andres Corrada-Emmanuel on Thu, 18 Jul 2002 11:44:01 -0400 (EDT)) References: Message-ID: <200207181752.g6IHqLZ07190@localhost.localdomain> > From: Andres Corrada-Emmanuel > > Hi, > > I'm trying to use tempfile to generate a temporary filename in the > directory of my chossing. I thought that this would work: > > import tempfile > > tempfile.tmpdir = '/my/path' > temp_name = tempfile.mktemp() > > However, it doesn't. I'm working on SunOS and temp_name always comes back > with /tmp/some_unique_identifier. > > What am I doing wrong? You're missing an e tempfile.tempdir='/my/path' Dave From russblau at hotmail.com Mon Jul 8 14:59:09 2002 From: russblau at hotmail.com (Russell Blau) Date: Mon, 8 Jul 2002 14:59:09 -0400 Subject: Why isn't this a bug? References: Message-ID: "Jonathan Hogg" wrote in message news:B94F68F5.D936%jonathan at onegoodidea.com... > On 7/7/2002 21:12, in article aga7af$jsvv9$1 at ID-76829.news.dfncis.de, > "Russell Blau" wrote: > > [...] > > Of course, if someone would like to explain why something so simple and > > intuitive is a "bad idea," please enlighten me. ;-) > > I think the problem is that you're considering an implicit behaviour to be a > feature. The rough meaning of 'str' and 'repr' is: > > repr - return a string representation of an object (ideally such that > the string can be 'eval'ed to re-produce the object) > > str - convert an object into a string > > For numbers, these two behaviours are easily defined. But for tuples and > lists there is no obvious behaviour for 'str'. What does it mean to turn a > tuple or a list into a string? In the absence of a defined behaviour, the > interpreter falls back on just returning 'repr' of the object. Well, technically you're right. The documentation just says that "str(object)" will return a printable string representing "object". It does that, so it's not a bug. However, the language does define two different functions (str and repr) for representing objects as strings. There presumably is a reason for having two different functions and two potentially different representations of the same object. Given that, why shouldn't the representations of lists, tuples, and dicts recognize this distinction? It would seem more logical, and more understandable to newbies, if "repr(sequence)" recursively called "repr()" on its elements [which it does], and "str(sequence)" recursively called "str()" on its elements [which it doesn't]. However, I'll agree that this is more a matter of "taste" than of right vs. wrong. > It's best not to rely on implicit conversions. Point taken. -- I don't actually have a hotmail account; but I do have one on excite.com if you really want to get in touch with me. From marklists at mceahern.com Fri Jul 26 08:46:38 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 26 Jul 2002 07:46:38 -0500 Subject: str() inconsistency In-Reply-To: Message-ID: [Mike Rovner] > Why it's not a bug: > > >>> 4.4 > 4.4000000000000004 > >>> `4.4` > '4.4000000000000004' > >>> str(4.4) > '4.4' > >>> str([4.4]) > '[4.4000000000000004]' > > IMHO, str() shall call str, not repr on complex objects. Apparently, this topic comes up from time to time. I was trying to find the most recent post from Tim Peters on this (sometime in the last two weeks, I believe). It may be somewhere in the results of this search: http://groups.google.com/groups?as_q=str%20repr%20list%20bug&as_ugroup=comp. lang.python I did find this one from October 2000: http://groups.google.com/groups?selm=mailman.971929189.1785.python-list%40py thon.org as well as Guido's post on this topic from November 1999: http://groups.google.com/groups?selm=5lln8ht38a.fsf%40eric.cnri.reston.va.us // mark From coventry at removethisandallhyphens-o-n-e.net Mon Jul 1 12:11:06 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Mon, 01 Jul 2002 12:11:06 -0400 Subject: old thread: SSL support for socket module for server sockets References: Message-ID: <3D207F1A.8080003@removethisandallhyphens-o-n-e.net> >>Yes, there are alternative SSL modules, but unless their authors step >>forward and contribute them, it is just as if they would not exist. >> > > I'm pretty sure that's what I did from the very start ;) Pretty soon I > will release version 0.5 of pyOpenSSL, with both new features and bufixes. I think he means "contribute them to core python" ;) Many users, like myself, have probably wanted to do SSL stuff - but many of them probably haven't posted on comp.lang.python to find out what was up, and gave up after many google searches returned nothing of usefulness... Not being in the standard library really takes away from the userbase... *shrug* -c From aleax at aleax.it Fri Jul 5 10:49:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 14:49:36 GMT Subject: Sorting a dictionary by value References: <3D2533F2.1040908@mxm.dk> Message-ID: <4miV8.46478$vm5.1667675@news2.tin.it> Max M wrote: > Roy Culley wrote: >> I'm sorry if this is a novice question but I have searched google >> and the python FAQ and haven't found an answer. >> >> I have a large dictionary where I want to sort and print based >> on the largest values in a dictionary and not the keys. >> >> Now in perl you can do: >> >> @Keys = sort { $Hash{$b} <=> $Hash{$a} } keys %Hash; >> >> Is there any such magic for python? > > # the basic sort > sortedList = [(key, theDict[key]) for key in theDict.keys()] > sortedList.sort() This sort by key, not by value. And if that's what you want, sortedList = theDict.items() is a faster and more compact way to perform the first of these two statements. To sort by value, largest-first, as it appears Roy Culley is asking, you need something like: histogram = [ (value, key) for key, value in theDict.iteritems() ] histogram.sort() histogram.reverse() Alex From claird at starbase.neosoft.com Tue Jul 23 08:54:13 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 23 Jul 2002 07:54:13 -0500 Subject: Python UDDI implementation References: <3D3C104D.1EDB2D48@xrce.xerox.com> <915a998f.0207220933.44a332ef@posting.google.com> <3D3D071F.BADCBD13@xrce.xerox.com> Message-ID: <6E449FA9D58D737A.5DF5F4A9FA118F2D.539821FD244E28D6@lp.airnews.net> In article <3D3D071F.BADCBD13 at xrce.xerox.com>, David Levy wrote: >Thanks >I know, this library was released last week >However, it is just an interface, not the repository itself ! >There are few ones available : jUDDI, .net, IBM's one, but no one in >Python or else I think ... > >I need the server side ;) . . . Yet another Java-based one (Tomcat, in fact) appears at . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From aahz at pythoncraft.com Sun Jul 28 14:38:51 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Jul 2002 14:38:51 -0400 Subject: Programming/Life ratio (was Re: __call__ bad style?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: In article , Tim Hammerquist wrote: >Aahz graced us by uttering: >> >> On the gripping hand, I never really thought of myself as a programmer >> until I learned Python. > >Never did JCL, and never considered myself a programmer till I got I >hands on one of the earliest releases of Borland C++. Python came >several years later, and I didn't pick it up until the late 1990's, so >you all have a good head start of me in that vein. =) Heh. I didn't start learning Python until, um, I guess it was 1999. As the motto goes, though, "Python: it fits your brain". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From paustin at eos.ubc.ca Sun Jul 21 12:46:59 2002 From: paustin at eos.ubc.ca (Philip Austin) Date: 21 Jul 2002 09:46:59 -0700 Subject: netCDF in 2.2 References: <57fe7929.0207180347.fe71ecc@posting.google.com> Message-ID: wadebk at nswc.navy.mil (Brian) writes: > > > > I'm a relative newbie in Python and I can't get netCDF to work under > > > > 2.2 on Windows. I found a .pyd file that makes it work under 2.1 > > > > (scientific_netcdf.pyd), but it doesn't work under 2.2. Does anyone > > > > have the equivalent version of this file or another easy solution? > > > Looks like Les Schaffer has built one at: http://basic.netmeg.net/godzilla/ Regards, Phil Austin From thefleau at softhome.net Sat Jul 13 14:46:16 2002 From: thefleau at softhome.net (Colin Barschel) Date: Sat, 13 Jul 2002 20:46:16 +0200 Subject: Convert to Python and compile to executable Message-ID: <3D307578.9080307@softhome.net> Hi I have to convert a medium (small) sized project (<20'000 lines) written mostly with shell scripts (bourne and Perl). One of the reason is that the project has to be distributed as a closed source package for testing in different companies. I?m very interested to learn Python, and would like to know if there is a possibility to compile Python code so that I do not have to give the source code away. Basically creating an executable where you can?t see the source. The software is running on Solaris, Linux and FBSD. Many thanks Ciao Colin From tim.one at comcast.net Sun Jul 21 16:26:46 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 21 Jul 2002 16:26:46 -0400 Subject: maximum recursion depth In-Reply-To: <_Ls_8.8858$_C2.708155@newsread2.prod.itd.earthlink.net> Message-ID: [Paul, recursing very deeply] > unfortunately it is not just memory... > it will (did) crash when the stack size is full, which is only a > fraction of the total memory space... right? The size of the stack you get depends on your operating system, and perhaps also your platform C runtime implementation -- it's not Python's decision. If you tell us which OS you're using, someone may be able to tell you how to tell your OS that you want a larger stack. If you're using threads too, life can get more complicated in a hurry, because most OS thread implementations give threads relatively tiny stacks by default. > python used less than 6MByte (less than 1% of total) when it > crashed with a much higher limit set for the recursion depth. > It took an awful lot of processing time as well... Have to rethink my > strategy here. Function calls in Python aren't cheap either. Keeping a stack or queue of "work to do" in an iterative algorithm ("a loop") is often much faster. From gherman at nospam.com Fri Jul 19 07:09:04 2002 From: gherman at nospam.com (Dinu Gherman) Date: Fri, 19 Jul 2002 13:09:04 +0200 Subject: ANN: Pycotin 0.1, a Python Cocoa Test Interface for PyUnit Message-ID: <20020719131144181+0200@news.t-online.de> Hi, for those who care, I've just released "Pycotin", a native Cocoa GUI to PyUnit testing on OS X. It's been just born, but looks very promising. Please find the code plus two screenshots in my Starship Python cabin: http://python.net/~gherman/#Pycotin Regards, Dinu PS: From the README: Pycotin 0.1 Pycotin (Python Cocoa Test Interface) is a Cocoa GUI to Steve Purcell's PyUnit test framework (1) on Mac OS X. For now, its user interface is very much designed after the existing Tkinter one (2), but that might slightly change again. Pycotin was developped from its author's personal frust- ration with running (or rather not running) Tkinter on Mac OS X as the only existing GUI for PyUnit. While it might well be possible to make Tkinter run on this plat- form, it was probably easier to write this little tool... Basically, with Pycotin you can "open" Python files (with extension ".py") and execute testsuites created in these files with the "unittest" module of the Python 2.0 stan- dard library. Right now Pycotin trys to import a function named "suite()" or "makeSuite()" from an opened Python module which it assumes to build and return a testsuite. This can clearly be made much smarter, but also depends on your habits as testsuite designer. The test files in samples/ were shamelessly copied from Steve Purcell's own original test cases for PyUnit 1.4.1 (just skipping the Tkinter ones for obvious reasons). I added only one new file, "listtestsfail.py" which shows a failing test, too. Pycotin is in early alpha phase! Be not surprised to see some buglets when dealing with paths containing blanks! (1) http://pyunit.sourceforge.net/ (2) http://pyunit.sourceforge.net/screenshot.gif From cliechti at gmx.net Mon Jul 8 14:59:08 2002 From: cliechti at gmx.net (Chris Liechti) Date: 8 Jul 2002 20:59:08 +0200 Subject: Numarray vs Numpy References: <080720021452508286%pecora@anvil.nrl.navy.mil> Message-ID: Lou Pecora wrote in news:080720021452508286%pecora at anvil.nrl.navy.mil: > In article , Fernando P?rez > wrote: > >> numarray is a rewrite of numpy. As such it will address some flaws of >> numpy's design which have been understood over the last few years of >> its extensive use in science. But beware that in order to do that, >> numarray's designers will be forced into breaking compatibility with >> numpy. So while _most_ numpy code will work with numarray, some >> critical things will not. >> > Are these compatible with the Numeric module? yes, as numpy _IS_ Numeric or vice-versa .... one is the name of the distribution the other the name of the package when you use it. chris -- Chris From tg5027 at citlink.net Wed Jul 24 00:46:15 2002 From: tg5027 at citlink.net (terry) Date: Wed, 24 Jul 2002 00:46:15 -0400 Subject: Numeric data question Message-ID: I'm a Python newby, but I have read several books, documentation, and email list archives, and I have not found a direct reference to how money calculations can be handled in Python. Specifically, I'ld like to use a Postgres (or any database) numeric data column that represents money with 'normal' Python math operators. I am *very* aware of the floating point problems, and know that I must avoid even using floating point for accounting applications. Would someone kindly either give me a short explaination or point me toward an information source. Thanks in advance, terry From jonathan at onegoodidea.com Tue Jul 30 15:20:22 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 20:20:22 +0100 Subject: global interpreter lock not working as it should References: Message-ID: On 30/7/2002 18:09, in article mailman.1028048987.3059.python-list at python.org, "anton wilson" wrote: > What's the purpose of releasing an reaquiring the lock if no other threads > can run? It's easy to say that one can't assume about the order of running on > different platforms as a scapegoat, but the main problem is that the GIL is > NOT implemented properly with pthreads. So nearly every system that uses > pthreads will show this kind of queue behaviour. I have a feeling that there > is a hidden race condition between when the thread wakes up the other thread > and tries to reaquire the lock. It really should be fixed, or else what's the > point of threads? Threads are for concurrency! I think the main problem is that you're trying to do something with Python threads that they just weren't designed for: CPU intensive work. Even if you "fix" Python to force a re-schedule, the GIL means you still only have one thread executing at a time and get NO CONCURRENCY. If you have a multiple-CPU machine and a kernel-level thread implementation and a multi-threaded CPU-intensive application, then the only way you're going to get true concurrency is to do the hard work in a C extension with the GIL released. Python threads just aren't any good for parallelism. They're mainly useful as a communication abstraction. You can browse the archives of this group for many (many) discussions on "fixing" the GIL, but you aren't going to get a solution. [and certainly not by assuming the Python developers are too lazy or stupid to have thought of this before and demanding some kind of action.] -no-after-you-ly y'rs, Jonathan From syver-en+usenet at online.no Fri Jul 19 21:36:04 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sat, 20 Jul 2002 01:36:04 GMT Subject: HTML DOM parser? References: <7xwursj0a4.fsf@ruckus.brouhaha.com> <3D373D7C.2237E7A3@engcorp.com> <7xvg7ck6dq.fsf@ruckus.brouhaha.com> <3D3817E8.13203964@engcorp.com> Message-ID: Peter Hansen writes: > "Daniel E. Burrow" wrote: > > > > My present task requires the automation of IE. After much prayer, I > > found that the "dom = ie.Document" assignment IS case sensitive. The > > > lower case form of "ie.document" just would not work for my > > ActiveState ActivePython 2.2.1 distribution. > > That's odd. I have never had to worry about case in almost any > aspect of IE automation, especially this one. > > Does anyone with greater knowledge of the guts of this stuff > have any input on why Daniel would have to worry about case > while I do not? My guess: He has been running makepy on the MSHTML library, you haven't. Many COM components doesn't care about casing (to please VB users), the makepy generated wrappers obviously care (as Python is case-sensitive with respect to identifiers) -- Vennlig hilsen Syver Enstad From ianb at colorstudy.com Wed Jul 31 12:22:44 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 31 Jul 2002 11:22:44 -0500 Subject: Let's Talk About Lambda Functions! In-Reply-To: References: Message-ID: <1028132565.578.3616.camel@lothlorien.colorstudy.net> On Wed, 2002-07-31 at 08:35, John Roth wrote: > The issue I was addressing was putting an anonymous function > (or method) in an expression, without any fancy conditions. In other > words, putting it where you would normally want to - with lots > of other code within a class. I wasn't addressing a corner condition. > > When you're writing a method in a class, and you want to > create an anonymous function within the code of that method, > how do you tell the compiler that you want a method instead? > That is the question. There's no way that I know of, but that shouldn't be a big deal. Typically you'll have to use nested scopes (to get self bound implicitly in the lambda), or pass self in as a default parameter (e.g., lambda x, self=self: ...) Ian From just at xs4all.nl Fri Jul 5 05:51:56 2002 From: just at xs4all.nl (Just) Date: Fri, 05 Jul 2002 11:51:56 +0200 Subject: Why self? References: Message-ID: In article , jolsen at mailme.dk (Jesper Olsen) wrote: > Why is it necessary to use a "self" argument to class methods in python? > > To me it seems a bit like doing object oriented programming in C... > > Why not make it implicit like "this" in C++? > > I do not find it usefull that I can give it my own name. > > So, is it just legacy or is there a reason for this convention? http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.007.htp Just From h_j_fong at hotmail.com Sun Jul 28 22:10:33 2002 From: h_j_fong at hotmail.com (Chris) Date: Sun, 28 Jul 2002 22:10:33 -0400 Subject: wxRadioButtons logic (2 Qs) References: <1d2e2585.0207280850.95fe6a0@posting.google.com> Message-ID: <1n89kug8bhq0isbl7v96fh8sb2bnao91mv@4ax.com> Found my answer to Q1: " wxRB_GROUP Marks the beginning of a new group of radio buttons. " Still searching for Q2 on dynamically changing window as user inputs radiobuttons. You can imagine a silly game where the top radio button says "Choose me" and when you choose it, its text disappears and the bottom botton says "No, silly, I said choose ME." This would only work in a world of talking buttons of course, but you get the idea. I'm looking into the wxRadioButton.create() maybe, to overwrite. If only there were a wxRadioButton.SetText() similar to the SetValue() member. Chris From aleax at aleax.it Wed Jul 17 04:17:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 17 Jul 2002 08:17:36 GMT Subject: Webware 0.7/Singleton pattern References: Message-ID: Ian Bicking wrote: ... >> You may be serving hits in different processes -- that depends in >> part on how you're using Webware... it can be installed to work >> on top of CGI, and CGI by definition uses a new process each time. > > Even when using the CGI adapter with Webware, you still only have one > process. The CGI program starts, and then connects to the persistent > Webware AppServer. (Unless you are using OneShot, which can introduce > all sorts of problems like this, since it does start new processes) Right! I *WAS* confusing OneShot with CGI-connecting-to-AppServer -- thanks for pointing out the difference. Alex From jblazi at hotmail.com Sat Jul 13 07:08:22 2002 From: jblazi at hotmail.com (JB) Date: Sat, 13 Jul 2002 13:08:22 +0200 Subject: Moving list entries from one list to another Message-ID: <3d30085b_9@news.newsgroups.com> I have two lists and . The entries of these lists have the format (id,rest), where is a natural number. The list are sorted, the key is . I should like to write a funtion move: def move(f): The argument is a predicate: f: {set of entries of list1} --> {true, false} Now all elements of list1, for which returns true, should be moved to list2. It is very important, that remains sorted, that is, the entries from should be inserted to the right positions in . When is defined by n := max(len(list1),len(list2)), then should work in O(n) time. Any hints of how to do this (as fast as possible)? TIA, -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From goodger at users.sourceforge.net Sat Jul 27 10:35:47 2002 From: goodger at users.sourceforge.net (David Goodger) Date: Sat, 27 Jul 2002 14:35:47 GMT Subject: Two dimensional regexp matching? In-Reply-To: <3D4285A3.80407@tiscali.co.uk> References: <3D4285A3.80407@tiscali.co.uk> Message-ID: Regular expressions can do multi-line searches. Just include "\n" in your expression and set the re.MULTILINE flag. However, such regexps can become very large and difficult to manage. You may be better off doing the search a different way. You may want to split your data into lists and search programmatically. You may want to look into a state machine approach; my statemachine.py (from http://docutils.sf.net/docutils/statemachine.py) may be useful. Some questions to ask yourself: Will you be doing one-off searches (reading the file each time you do a search), or multiple searches (with the file in memory)? How dynamic are your search terms (do you repeat the same search, or is each search different)? -- David Goodger Open-source projects: - Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) - The Go Tools Project: http://gotools.sourceforge.net/ From jimmy at retzlaff.com Sun Jul 28 06:54:18 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 28 Jul 2002 03:54:18 -0700 Subject: PythonWin ODBC: DSN-less connecting string Message-ID: Mark Hammond wrote: > Jimmy Retzlaff wrote: >> The current odbc module in win32all doesn't support DSN-less >> connections. A while back I submitted a patch to Mark Hammond to add >> support for this - hopefully it'll make it into the next release of >> win32all. > > Sorry :) I just checked that change in - thanks! If you could check > the CVS version I would appreciate it. The CVS copy and my copy of odbc.cpp compare exactly (other than white space). Thanks Mark! Jimmy From dfackrell at DELETETHIS.linuxmail.org Tue Jul 16 15:14:44 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Tue, 16 Jul 2002 13:14:44 -0600 Subject: Making code faster References: Message-ID: <3d3470a4$1_2@hpb10302.boi.hp.com> "Larry" wrote in message news:cXZY8.29277> > What's a profiler...and how is it used to see where the time is going? > > Larry Larry, Section 10 in the Library Reference appears to cover it. http://www.python.org/doc/current/lib/profile.html If you're in a hurry, you can skip into 10.3, which jumps right into the usage. -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From andreas at kostyrka.priv.at Wed Jul 24 10:38:49 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 24 Jul 2002 16:38:49 +0200 Subject: TypeError: unbound method...expected one instance, got another In-Reply-To: References: Message-ID: <1027094968.7791.101.camel@vaio2> Am Fre, 2002-07-19 um 01.21 schrieb David: > I have created a hierarchy of classes, and I am receiving an error that I > have not been able to figure out. The error message (in Python 2.2) is: > "TypeError: unbound method __init__() must be called with Super instance as > first argument (got Sub instance instead)". > > My situation is that I have three classes in a hierarchy, with the Super > living in a different module than the Mid and the Sub, as follows: > > module1.class Super: > def __init__(self): > self.a = 'string1' > > module2.class Mid(module1.Super): > def __init__(self): > self.b = 'string2' > module1.Super.__init__(self) > > module2.class Sub(Mid): > def __init__(self): > self.c = 'string3' > Mid.__init__(self) What are the exact error messages. Exceptions in Python provide always a backtrace of the execution flow. You also do not make clear how you are trying to use your modules. Additionally the above pseudo code is obviously not the exact source. Best regards, Andreas From raims at dot.com Thu Jul 18 17:47:43 2002 From: raims at dot.com (Rhymes) Date: Thu, 18 Jul 2002 23:47:43 +0200 Subject: Tkinter vs. wxPython References: Message-ID: <5ndejukvjps3ekjn0793rnftasp1odu798@4ax.com> On Thu, 18 Jul 2002 14:19:57 -0700, "Gabe Newcomb" wrote: >Ack! > I've been trying to get into wxPython, but I'm finding the lack >of documentation difficult. There's some, and I'm very grateful for >everybody who's contributed it, but I'm somebody who really likes having >a decent reference and more examples. > >My question is this: is there any compelling reason I shouldn't just go >with Tkinter instead? I work (for now) exclusively on Win32 boxes, by >the way. I suggest you to search on google.com old threads about that :) However, I think wxPython's apps have a better look-and-feel than Tkinter's...but the main drawback (of wxPython) is that Tkinter is the _default_ GUI in Python's official release -- Rhymes rhymes at myself.com " ride or die " From dlashar at sprynet.com Thu Jul 18 19:21:27 2002 From: dlashar at sprynet.com (David) Date: Thu, 18 Jul 2002 19:21:27 -0400 Subject: TypeError: unbound method...expected one instance, got another Message-ID: I have created a hierarchy of classes, and I am receiving an error that I have not been able to figure out. The error message (in Python 2.2) is: "TypeError: unbound method __init__() must be called with Super instance as first argument (got Sub instance instead)". My situation is that I have three classes in a hierarchy, with the Super living in a different module than the Mid and the Sub, as follows: module1.class Super: def __init__(self): self.a = 'string1' module2.class Mid(module1.Super): def __init__(self): self.b = 'string2' module1.Super.__init__(self) module2.class Sub(Mid): def __init__(self): self.c = 'string3' Mid.__init__(self) The curious thing to me (a newbie) is that sometimes instantiation of Sub() works and sometimes it doesn't, depending on how I attempt it. If I am at the interactive prompt, instantiation works (except in a special case, which I'll come to). In other words, if I am at the interactive prompt, I am able to create an instance of Sub() that includes the 'a' attribute from Super. If, however, I try to create the instance in a script, I encounter the TypeError when I run the script. If, after encountering the TypeError, I return to the interactive prompt and again try to create an instance of Sub, I again encounter the TypError (this is the special case). I continue to get the error until such time as I reload module2, after which I am back where I started, i.e., able to create an instance of Sub from the interactive prompt but not from my script. I feel like I'm misunderstanding something... but can't figure out what it is. Any insight or help would be appreciated. Thanks, David From shalehperry at attbi.com Tue Jul 23 12:35:48 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 09:35:48 -0700 (PDT) Subject: how to count lines in a file ? In-Reply-To: Message-ID: On 23-Jul-2002 Shagshag13 wrote: > hello, > > i need to count lines in a file (that i *can't* keep in memory, so can't use > readlines()) > by now i use this : > --- > import os > > BUFFER_SIZE = 10000 > > def lineCount(filename, bufferSize = BUFFER_SIZE): > > do = 'wc ' + filename > p = os.popen(do, 'r') > line = p.read() > p.close() > read() copies the whole chunk into memory as well so you might as well use readlines(). otherwise just use a standard loop and counter. From theller at python.net Mon Jul 8 15:11:16 2002 From: theller at python.net (Thomas Heller) Date: Mon, 8 Jul 2002 21:11:16 +0200 Subject: compiler package Message-ID: Has anyone used the compiler package to compile Python source code to other languages? Is there anything to get started? Thomas From yduppen at xs4all.nl Tue Jul 23 09:59:37 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Tue, 23 Jul 2002 15:59:37 +0200 Subject: print fileinput, and screen ? References: Message-ID: <3d3d614d$0$94907$e4fe514c@dreader3.news.xs4all.nl> > and as i do some other printing to stdout (print script times, counts, > etc.) i'm wondering if that couldn't conflict with "print" for > fileinput ? If your stdout is redirected, you can always reach the original stdout file-like object with sys.__stdout__ Example: ### Redirecting stdout: >>> import sys >>> f = open("/tmp/example", "w") >>> sys.stdout = f ### Printing to the redirected stdout: >>> print "Hello World" >>> sys.stdout.write("Hello World\n") ### Printing to the real stdout: >>> sys.__stdout__.write("Hello World\n") Hello World ### Resetting stdout >>> sys.stdout = sys.__stdout__ >>> print "Hello World" Hello World ## Closing f and inspecting it from the shell >>> f.close() >>> ^D $ cat /tmp/example Hello World Hello World However, since sys.__stdout__ is a file-like object, you MUST add all end-of-lines yourself, since print won't do that. YDD -- .sigmentation Fault From shalehperry at attbi.com Thu Jul 25 12:07:22 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 25 Jul 2002 09:07:22 -0700 (PDT) Subject: Speed up Python by up to 5% ? In-Reply-To: <15680.7634.425684.630761@12-248-11-90.client.attbi.com> Message-ID: > > About a year ago I wrote an XML-RPC server to which people could post opcode > frequency info (and retrieve it by version), but nobody bit on the idea. > Here's the entire client-side code necessary to register this info: > so we add the code below to any python apps we write and you get data based on our runtime usage? From pyth at devel.trillke.net Mon Jul 22 17:04:08 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 22 Jul 2002 23:04:08 +0200 Subject: can i make a p2p application in python? In-Reply-To: ; from eugene1977@hotmail.com on Sun, Jul 21, 2002 at 09:35:49PM -0500 References: Message-ID: <20020722230407.D10625@prim.han.de> eugene kim wrote: > i don't even know what bootstrapping is.. Bootstrapping in is the process of bringing a system to its working state. With P2P-networks bootstrapping is difficult. You usually don't want a central point of control (or failure) but how do pop into into a network that is constantly changing? E.g. one of the problems of Gnutella was 'bootstrapping' into the virtual network. First, people had to get working IP-addresses by word-of-mouth. Then gnutella nodes started using 'hostcaches' which automated the task of finding initial hosts. Due to the design of the 'hostcache' the network slowly morphed into a centralistic structure. This didn't work reasonably with millions of nodes. > can u recommend a good book to read? i am currently reading "Peer to Peer" published by O'Reilly. It has interesting articles from several programmers including from freenet, gnutella, napster, jabber, Red Rover. It's all more about concepts but also offers helpful technical details. Depending on your background you might be able to extract useful information and code from 'circle' and the related 'chord' project. have fun, holger From whisper at oz.net Sun Jul 7 14:53:56 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 7 Jul 2002 11:53:56 -0700 Subject: how to disable maximize button? In-Reply-To: Message-ID: IIRC, Tk itself has the capability to trap the quit button on the window, and that _should_ be the same mechanism to catch a click on any of the window "system" buttons. (This pertains to MS-Windows.) In general terms, for MS-Windows, you have to set a handler to capture the WM_SYSCOMMAND message and the wparam arg will have the type of action (minimize, maximize, quit etc.) that's being passed. Tk has a means to set a handler for what it calls protocol events, but after reading the Tk code itself, it only seems to work with WM_DELETE_WINDOW - which curiously, isn't a standard MS-Windows event name! I tried setting an event handler for WM_SYSCOMMAND in Tkinter, but it never fired (also, there seems to be no way to get args passed with the event). David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Cameron Laird > Sent: Sunday, July 07, 2002 5:32 > To: python-list at python.org > Subject: Re: how to disable maximize button? > > > In article , > Alex Martelli wrote: > >jubafre at zipmail.com.br wrote: > > > >> how i can disable de maximise button in tkinter, i don?t want the user > >> modific the size of the window, i want a real size of window, > how can i do > >> it??? > > > >You can remove all decorations: > > > >import Tkinter > >root = Tkinter.Tk() > >root.overrideredirect(1) > > > >Apart from this, you may choose to fix the size: > > > >import Tkinter > >root = Tkinter.Tk() > >root.resizable(0,0) > > > > > >I know of no way to affect the maximize button ONLY, without also > >affecting other ways to resize the window, but then from your post's > >text I don't see why you should ONLY want to affect said button. > > > > > >Alex > > > > > > It is possible, though. That is, I believe, without making > the time to verify this myself, that there's an effective way > to achieve this under crucial window managers. > > You're right, Alex, that overrideredirect achieves what makes > sense in this area. However, as I believe you know, many > vertical applications Windows hosts are configured with maximize > and remove-window buttons disabled, leaving only iconify. Clients > expect to see this, whatever we think of its (ir)rationality. Al- > though Tkinter proper doesn't provide a means to achieve this, > there are win32 calls accessible through *that* module that > make it happen. > > I've forgotten what they are. If I were going to pursue this, > I'd check with operating-system experts for the correct lower- > level calls. > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://starbase.neosoft.com/~claird/home.html > -- > http://mail.python.org/mailman/listinfo/python-list From mis6 at pitt.edu Thu Jul 25 10:31:51 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 25 Jul 2002 07:31:51 -0700 Subject: how to count lines in a file ? References: <200207251015.40671.rjones@ekit-inc.com> Message-ID: <2259b0e2.0207250631.1e093e64@posting.google.com> Can somebody provide a simple example where the idiom file(name,'w').write(something) fails, in the sense that the file is not closed or something is not written ? I tried to hang the program with a memory overload file(name,'w').write(something) for i in range(2*10**8): pass (this doesn't crash my machine but the CTRL-C doesn't work and I have to kill the precess by hand) but still at the end something is written in the file name. How safe is Python implicit file closing ? In which practical situations can fail and how dangerous can be ? -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/ From marklists at mceahern.com Mon Jul 15 08:41:25 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 15 Jul 2002 07:41:25 -0500 Subject: objects in a list ... In-Reply-To: Message-ID: > I want to create many Objects of a class designed by my own and > these objects should be > stored/append in/on a list. Is this possible and how can I > realize it? Thanx & Sorry for my bas > englisch :-) class Foo: """An empty class.""" pass # Create a list. foos = [] # Create some Foo instances and append them to the list. for x in range(10): f = Foo() foos.append(f) // m - From python at dohao.org Mon Jul 8 00:10:11 2002 From: python at dohao.org (Wenshan Du) Date: 7 Jul 2002 21:10:11 -0700 Subject: Chinese language support of Python? References: Message-ID: hi, I think this problem is simple. Try MBCSP 1.0 http://www.dohao.org/python/mbcsp or visit http://www.dohao.org/python From mikeb at mitre.org Wed Jul 10 12:27:09 2002 From: mikeb at mitre.org (Mike Brenner) Date: Wed, 10 Jul 2002 12:27:09 -0400 Subject: COCOMO - appropriate for languages like Python? Message-ID: <3D2C605D.82FB3008@mitre.org> > From a management standpoint ... strive to hire the very best people and to break projects into moderate sized, easily handled chunks. > From a schedule estimation standpoint, LOC (however you choose to count them) appears to be a pretty good estimator to use for a fixed staff and fixed project sizes. How the prediction varies as you change staff or project sizes is something you'll have to measure or guess at yourself. IMO, the following measurements apply to most Python efforts more than lines of code: - Most software has achieved the status of "maintenance" rather than "development". Thus, millions of lines of code might require, say, a one-line change. Some of those one-line changes take a month of research and testing, while others take a few seconds. The lines of code changed (and the lines of code in the whole project) only correlate to new code, not to code under maintenance. - Software Maintenance time primarily increases as backlog increases (e.g. programmer overtime which the company intends to not pay, other work awaiting action, inadequate functional testing, deferred regression testing which detects reappearance of prior bugs, incomplete impact analysis of past and present changes, incorrect documentation, and the age of parallel development paths). For example, parallel development paths that last more than a few days (fractured baselines) start to take on lives of their own, and become more expensive to merge into a single "golden" baseline as they age. - Software Maintenance time decreases as the technology factor (the part of the COCOMO model that applies to software maintenance rather than to new development) increase. Thus, to save time, get better tools for: comparison, visualization, cross-referencing, text pattern search, automatic testing, slicing, and other tools to assist in determining the impact of changes. Also, use an interpreted language like Python with good debugging, tracing, and other tools. Measure the number of seconds it takes to find the line of code that caused a problem (something that gets harder when you add wxWindows, threads, servlets, graphics, COM objects, operating system calls, web services, soaps, and additional levels of interpretation to the software). - Software Maintenance time increases with the number of data integrity problems possible in the languages and tools used (coding bugs, data design flaws, data flaws, network design flaws, rifts, and sabotage). Coding bugs include off-by-one errors, aliasing, global variables, hanging pointers, out-of-range errors, missing actions, extra actions, global typing violations (even in interpreted languages), and memory leakage. Data design flaws include failure to trigger an action (e.g. busting a referential integrity constraint), implementing a many-to-many relationship inefficiently, mismatching keys, inappropriate level of normalization, performing a wrong action, or incomplete design. Data flaws include conversion round-offs or other loss of precision, incorrect origin or units of measure, inaccurate numbers, inappropriate null data, obsolete data, out of range errors, two-digit years, and local type mismatches. Network design flaws include bandwidth too low (errors or nois! e), bottlenecks, inadequate error detection/notification/correction, speed mismatch, missing packets, power failures, race conditions such as deadlocks, insufficient redundancy, loss of resolution, simultaneous modifications, and slow response time. Rifts are another name for the backlogs above which were called out separately because of their large effect on time. Sabotage (tampering with the data, trojan horses, viruses, authentication where none is needed, weak authentication where authentication is actually needed, worms, failure of CM to preserve the parts, management destroying service requests which were completed or cancelling to remove the evidence, and lack of backups). - Software Maintenance time positively correlates to the amount of time that maintenance organization last maintained that type of code (after subtracting the time it takes to open up the configuration, which relates to how long since a project last opened that code). - Software Maintenance time negatively correlates with syntactic standards. For example, a rule like "indent each level 3 spaces" slows down software maintenance and development in two ways. First, humans (like programmers, reviewers, and quality assurance auditors) will tend to spend time enforcing and carrying out such a rule, because of their ego-needs for control; people should only impose such a rule by providing a tool to enforce the rule automatically. Second, such rules limit the visualization possibilities -- for example, someone might discover a bug more quickly by viewing the code with several different indentations. - When management decides to use a metric, and the programmers become aware of that metric, then the programmers take whatever action required to make that metric reach 100%. For example, if management pays the programmers by the line of code, the lines of code will increase. - When management (personal, government, corporate, academic) requests non-applicable metrics like lines of code (a metric which makes sense only at development time) or McCabe Cyclomatic Complexity (a metric which makes sense only at testing time since it counts test paths and dings programmers for good stuff like nested SWITCH/CASE statements and BREAKs) to describe maintenance effort, consider get rid of that entire levelly management. - Without an accepted standard definition of "lines of code", one cannot know whether to count every line in every IMPORTed module, or just those the INVOKED lines, or just those lines that do the invoking. For example, do we count every line in the python runtime module STRING.PY or just the lines in STRING.PY that our modules call, or just the lines in our module that call STRING.PY? These different counting strategies differ by orders of magnitude. Mike Brenner From boud at valdyas.org Fri Jul 26 05:25:30 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Fri, 26 Jul 2002 11:25:30 +0200 Subject: Python, QT, PyQt in Windows References: Message-ID: <3d4115c6$0$31242$e4fe514c@dreader1.news.xs4all.nl> Pablo wrote: > Hi, there. > I am totally new in Python world(I started learning it from last > weekend). I download the evaluation Python2.2 from Python.org. I > download QT and PyQt, too. Now, my question is: how do I do Python > program with QT or PyQt? In Python2.2, I have the IDLE, where I can do > python program. But, in QT, the QT designer is for C++, in PyQt, there > is no working environment at all. What do I need in order to take > advantage of QT or PyQt when using Python? 1. Windows 2. Python 3. qt non-commercial edition (download at trolltech) 4. PyQt binaries for windows (download at riverbank) 5. Any editor -- I'd advice Scintilla. You design your screens with Qt Designer (included with qt), compile your screens with pyuic (included with PyQt, start from a dos box), and edit your code with the editor. You might want to take a look at BlackAdder, which includes everything you need in one convenient package, is not terribly expensive, and really should move out of beta soon... Originally, my book (pub. jan. 2002) was intended to coincide with the release of BlackAdder 1.0 (may 2001). > I saw a on-line book http://www.opendocs.org/pyqt/, but that is for > Linux. I cannot follow the example in that book. Please, somebody who > has the experience with Python, QT, PyQt in windows, tell me what I am > supposed to do so that I can call the QT from Python. Well, I spent quite a lot of time installing Windows, Qt-non-commercial, BlackAdder and PyQt to test that out. The on-line version doesn't include the screenshots (don't know why, though), so you'd better get the paper version. I do spend a chapter giving the exact answers to your questions above. -- Boudewijn Rempt | http://www.valdyas.org From andymac at bullseye.apana.org.au Thu Jul 11 06:51:26 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 11 Jul 2002 21:51:26 +1100 (edt) Subject: Using Python for processing of large datasets (convincing managment) In-Reply-To: Message-ID: On Tue, 9 Jul 2002, Alex Martelli wrote: > Wrong. Very wrong. If you can afford Oracle, you can afford to > hire (or at least regularly retain a freelance) expert help to > tune it, keep it tuned, make it perform to its potential. {lots snipped} The justification for Oracle is that there's a lot of people on tap for problem solving. The bit that bites, as you note, is that you _need_ those people on tap for Oracle to be useful. Having been involved with Ingres for a while, its easy to see the management types get itchy that there weren't that many Ingres people about. The fact that the installation was pretty much self tuning and the Ingres specialists weren't needed very much was lost on the PHBs. The real problem with Ingres was that CA hardly bothered to really make much of it. That just made the Oracle decision a no-brainer for the PHBs. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From SSchukat at dspace.de Thu Jul 18 05:33:45 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Thu, 18 Jul 2002 10:33:45 +0100 Subject: Newbie : Processes management under W2K Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B22E@PDC-DSPACE> Search for "killProcName.py" in the install tree of the win32all package from Mark Hammond: e.g.: F:\Python22\Lib\site-packages\win32\scripts\killProcName.py That should do it. Stefan -----Original Message----- From: msachet at hotmail.com [mailto:msachet at hotmail.com] Sent: Thursday, July 18, 2002 8:53 AM To: python-list at python.org Subject: Newbie : Processes management under W2K Hi everybody, in order to kill a specific app, i'd like to know how to get the list of all processes currently running under Win2000 with name, pid, etc.. thanks in advance ! Marc -- http://mail.python.org/mailman/listinfo/python-list From brueckd at tbye.com Wed Jul 17 11:13:06 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 17 Jul 2002 08:13:06 -0700 (PDT) Subject: HTTP_USER_AGENT Parsing In-Reply-To: <3d33d24d$1@pull.gecm.com> Message-ID: On Tue, 16 Jul 2002, Olly Smith wrote: > > > I'm a bit of a newbie to Python, and in my quest to generate nice HTML > > > content, I need a way to work out what browsers clients are using from > their > > > HTTP_USER_AGENT strings. > > > > > > Any pointers? [snip] > Ta, I'll check that out. This bit of code I'm working on has to produce a > 'nice' interface, but part of the spec says it must work with NS4 correctly > .. and we all know NS4 is a PITA ;) Ugh, I feel your pain! I once worked on a project that had the same requirement, and after wasting way too much time on NS4 compatibility we as a team revolted and got the requirement dropped. :) Anyway, if you only have to differentiate between NS4 and "everything else" (ie - you have the HTML you'll generate normally and then some different stuff iff the browser is NS4) then you can probably get by with something simpler than parsing the entire user agent string - just do some substring searches. You'll want to verify this yourself with a decent set of browsers, but something like this would work: (assume UA = the user agent string) UA = UA.lower() if UA.find('mozilla/4.0') != -1 and UA.find('opera') == -1 and UA.find('msie') == -1 and UA.find('konq') == -1: # Probably Netscape 4 else: # Probably not Netscape 4 This is much shorter than actually parsing the user agent string, and just about as accurate (besides, you can't feel TOO much sympathy for somebody who is using a non-NS4 browser that reports itself as NS4! :) ). -Dave From aleax at aleax.it Wed Jul 24 12:03:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 16:03:17 GMT Subject: error code References: <3d3ec90c$0$28132$afc38c87@news.easynet.fr> Message-ID: <9dA%8.112517$Jj7.2658228@news1.tin.it> ferreira jorge wrote: > In your example you write the Exception code . > > for example : > try : > server = smtplib.SMTP('XXXXXXX') > except : > print "error : %s --> %s " % ( sys.exc_value , sys.exc_type) > > If I put a bad host , I have the error : "error : host not found --> > socket.error" > > I suppose that the error "host not found" have a caracteristic number . > how can I get it ? Don't use except without arguments, it's almost never best. >>> import smtplib, socket >>> try: server=smtplib.SMTP('XXXXXX') ... except socket.error, err: pass ... >>> err >>> dir(err) ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] >>> err.args (-2, 'Name or service not known') >>> In lieu of the 'pass' put any processing you may desire on err.args. Alex From whisper at oz.net Fri Jul 5 22:28:52 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 5 Jul 2002 19:28:52 -0700 Subject: Why self? In-Reply-To: Message-ID: Yeah, some people need training wheels - others don't. Alas, some people get dependent on their training wheels. Funnily enough, all the actual young kids who where taught Smalltalk never seemed to miss not having to use self for everything. It's too bad that people who don't need crutches or who have outgrown them are stuck with this misfeature. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Courageous > Sent: Friday, July 05, 2002 19:00 > To: python-list at python.org > Subject: Re: Why self? > > > > >Did you know that for larger projects people like to use "this->name" > >or prefix the member variables with 'm_' to introduce expliciteness > >into c++? > > Indeed, explicit self in Python solves the age old question: > "what should I call my method arguments for data that stands > for member attributes"? Ala, > > class C: > > i = 0 > > def setit ( self, i ): > > self.i = i > > In other environments, you're stuck doing things like: > > m_i = i; > > or... > > i = i_arg; > > ... a clear sign of a struggle to resolve mishandled ambiguity. > > So, the question should be, why on earth _confuse_ everything with > implicit this? > > It really doesn't help. > > C// > > -- > http://mail.python.org/mailman/listinfo/python-list From heikowu at ceosg.de Tue Jul 30 12:28:28 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 30 Jul 2002 18:28:28 +0200 Subject: Instant Messenger In-Reply-To: References: Message-ID: <1028046509.2947.5736.camel@d168.stw.stud.uni-saarland.de> Hi Chris! On Tue, 2002-07-30 at 03:17, Chris wrote: > Questions: > Once the server has validated the username and password, I want to store the > socket that I used to recv() the username and password so that I can send > messages to it later (i.e. when another user logs on). Also, I want to be > able to keep a list of all the users logged in, which I guess is one in the > same with the last sentence. Is any of this possible without threading? Humm... Why not choose a different scheme? Instead of sending out messages using the open sockets, why not have the server only care for storing the messages, and the clients doing a continuous poll? In my oppinion 15 seconds would be way enough... That way you don't have to deal with many different connections on the one computer, but instead you can serve out pages in an RPC-like fashion. (I presume this works much more easily...) And, one more added benefit: if you e.g. use XML-RPC to do the queries, then you can also stream all messages through a web-proxy easily, without having to change the protocol (like ICQ over Proxy, etc. have to). If you're interested, I can send you my base-implementation of an XML-RPC server which works multi-threaded, including code to do multi-threaded database connection sharing. The server is based on a module architecture, where modules do all the work that you actually want to serve via RPC. btw: I'm using the server as a backend for a web-application doing pretty much the same thing that you want to do... ;) Just my 5 cents... :) Heiko W. From huaiyu at gauss.almadan.ibm.com Thu Jul 11 14:22:04 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 11 Jul 2002 18:22:04 +0000 (UTC) Subject: Why self? References: Message-ID: David LeBlanc wrote: >Louis; > >I think he was proposing an idea. I don't believe you can import from self, >and i'm almost positive that "to ... export" isn't part of Python. That's right. And the solutions given by Fernando and Alex are good to use. Sometimes I wish that some of Python's namespace facilities could be more generally available (as opposed to specialized for modules and packages). Huaiyu From gleki at gol.ge Mon Jul 1 06:59:58 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 01 Jul 2002 12:59:58 +0200 Subject: QT->XML->Pmw->GUI References: <3D203078.577C501E@gol.ge> <3d2032f8$0$94904$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <3D20362D.49EF1495@gol.ge> PyQT, as well as wxPython are both nice, but Tk+Pmw remain de facto standard... Boudewijn Rempt wrote: > Giorgi Lekishvili wrote: > > > Hi all! > > > > As we surely know, an excellent GUI builder, QT designer primarily > > produces XML-based UI file. > > > > My question is: > > > > -Is there any available script in Python transforming the .ui file in > > Tk+Pmw based .py file? And if not, what do you think, would it be > > meaningful to make such a script? E.g., sort of uip compiler along with > > the uic compiler... > > > > It wouldn't be really useful, unless you can find an accurate replacement > for all the Qt widgets, This doesn't seem a big problem. > and could find a way to translate the included > signal/slot connections to something Tkinter could use That would be really uneasy... > . And with the current > version, you can even include Python code in the ui files, if you want to. > > There's, of course, already pyuic, which generates Python code that uses > PyQt... > Thank you for the answer. Giorgi > -- > Boudewijn Rempt | http://www.valdyas.org From fredrik at pythonware.com Mon Jul 22 11:26:17 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Jul 2002 15:26:17 GMT Subject: SOAP.py and complex types References: <3D3BDD02.3997B185@xrce.xerox.com> Message-ID: David Levy wrote: > I am using Python to call Web Services, with SOAP.py (0.9.7) library > However I can't figure how to use it when input messages requires user > defined types like the one for the new Amazon web service : > http://soap.amazon.com/schemas/AmazonWebServices.wsdl > > does anyone know how to do it ? dunno, but it looks like mark pilgrim might have figured it out: http://diveintomark.org/projects/#pyamazon From cliechti at gmx.net Fri Jul 19 14:30:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 19 Jul 2002 20:30:09 +0200 Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: Johannes Graumann wrote in news:ah9kgo$5k9 at gap.cco.caltech.edu: > Chris Liechti wrote: >> Johannes Graumann wrote in >>>>names = ["one","two","three"] >>>>values = [ 1,2,3] > --> DO SOMETHING HERE >>>>print one > 1 my tip: don't pollute the global namespace. if you do it with a class it's easier anyway: >>> class Lexikon: ... def __init__(self, values): ... self.__dict__.update(values) ... >>> l = Lexikon(dict(zip(names,values))) >>> l.one 1 chris -- Chris From tjreedy at udel.edu Thu Jul 4 10:15:28 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Jul 2002 14:15:28 GMT Subject: REPEAT... UNTIL ? References: Message-ID: <4MYU8.272370$_j6.13358536@bin3.nnrp.aus1.giganews.com> "Ville Vainio" wrote in message news:ad496f8.0207040602.3670c1c1 at posting.google.com... > Strangely enough, while 1 - loop is quite often the most intuitive way > to do things, yet it's (implicitly) frowned upon in many programming > language cultures. When I first learned Python, I found it somewhat grating, but I have since learned to think of 'while 1' as a spelling for 'loop' and 'if break' as a corresponding spelling for 'while not ' (and vice versa for 'not' reversed). TJR From erict at millfilm.co.uk Mon Jul 22 08:26:56 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Mon, 22 Jul 2002 13:26:56 +0100 Subject: xmlrpclib question Message-ID: <3D3BFA10.92E38B5B@millfilm.co.uk> I posted this question earlier but I am still confuse about what I am doing wrong. Why, in the class 'clientRootTask' just taking out the 'if' statement will make it work: . . if serverp: serverp.SendTask(msg) .. produce the error: raise apply(Fault, (), self._stack[0]) xmlrpclib.Fault: When: . . serverp.SendTask(msg) .. will work just fine. run the server: python ServerCode.py from python: >>> from tempClient import * >>> a = clientRootTask("junk") >>> a.checking() 3 files involved: dataAppTemp.py : some contant (you can set your local IP ) ServerCode.py : minimun rcpserver code tempClient.py : 2 classes defined - clientRootTask : a client - taskServer : an instnnce class for the server ALL THE CODE INVOLVED dataAppTemp.py: ##### PROTOCOL CLIENT/SERVER KEYUSER = "USER" KEYSHOW = "SHOW" KEYSHOT = "SHOT" KEYCONTENT = "CONTENT" OK = "OK" CANCEL = "CANCEL" #### SERVER_IP_ADDR = "10.16.3.132" SERVER_PORT = 8000 ServerCode.py: ################################ ################################ import sys import os import time import socket import SimpleXMLRPCServer import string ##### import dataAppTemp import tempClient ############ ## Task Handler ############ class taskRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): def _dispatch( self, method, params ): ip, port = self.client_address print "in dispatch",ip return SimpleXMLRPCServer.SimpleXMLRPCRequestHandler._dispatch(self, method, params) ######## if __name__== "__main__": server = SimpleXMLRPCServer.SimpleXMLRPCServer ((dataAppTemp.SERVER_IP_ADDR, dataAppTemp.SERVER_PORT), taskRequestHandler) server.register_instance(tempClient.taskServer(server)) server.serve_forever() In tempClient.py ################################ ################################ import os import xmlrpclib import types ##### import dataAppTemp ################################ class clientRootTask: ################## def __init__(self,aname): self.name = aname ################## def getConnection(self): print "try to connect to the server" server = None try: server = xmlrpclib.ServerProxy( "http://%s:%d" % (dataAppTemp.SERVER_IP_ADDR, dataAppTemp.SERVER_PORT)) print "Connected to the server..." except: print "Cannot connect" server = None return server ################## def checking(self): import string msg = {} msg[dataAppTemp.KEYSHOW]= "MYSHOW" msg[dataAppTemp.KEYSHOT]= "MYSHOT" if os.environ.has_key('USER'): msg[dataAppTemp.KEYUSER] = os.environ['USER'] print msg serverp = self.getConnection() print "SERVER PROXY %s" % serverp if serverp: serverp.SendTask(msg) return 1 #################################################### ### taskServer #################################################### class taskServer: ################## def __init__(self,server): print "IN INIT SERVER TASK" self.server = server ################## def SendTask(self,msg): print "getting message" if type(msg) != types.DictType: print "Wrong type of msg" return dataAppTemp.CANCEL if msg.has_key(dataAppTemp.KEYSHOW): print "Show",msg[dataAppTemp.KEYSHOW] if msg.has_key(dataAppTemp.KEYSHOT): print "Shot",msg[dataAppTemp.KEYSHOT] if msg.has_key(dataAppTemp.KEYUSER): print "From user",msg[dataAppTemp.KEYUSER] return dataAppTemp.OK From imbosol at vt.edu Tue Jul 30 15:25:15 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 30 Jul 2002 15:25:15 -0400 Subject: lexing nested parenthesis References: Message-ID: Fran?ois Pinard wrote: > [Kristian Ovaska] > >> The language category you're dealing with is called context-free grammars. >> It's more expressive than regular languages, and it can parse any >> programming language. > > Any? :-) > > I would not go that far. There are strange beasts out there. Like, for example, C. Expressions can parse differently depending on whether a symbol has been typedefed or not. -- CARL BANKS http://www.aerojockey.com From tdelaney at avaya.com Thu Jul 11 00:26:25 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 11 Jul 2002 14:26:25 +1000 Subject: COCOMO - appropriate for languages like Python? Message-ID: > From: James J. Besemer [mailto:jb at cascade-sys.com] > > To my mind, this is simply saying the average cost per new > LOC is rather high in these circumstances and also the > standard deviation also is high. IIRC, COCOMO has a way to > take this into account. How does it deal with negative LOC? There are many cases where I consider myself much more productive if I can *reduce* the code base. Tim Delaney From skip at pobox.com Sat Jul 27 00:56:00 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Jul 2002 23:56:00 -0500 Subject: how to count lines in a file ? In-Reply-To: References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> Message-ID: <15682.10208.325890.497677@12-248-11-90.client.attbi.com> >> Not quite. Any cycle containing an object with a __del__ method will >> be skipped and left to languish in memory-limbo forever. >> Steve> You mean the garbage collector doesn't *collect* data that Steve> appears in cycles? That's not my understanding (which doesn't Steve> nevessarily mean it's dissonant with reality). No, just those cycles where at least one of the involved objects contains a __del__ method. In those situations, it's the programmer's responsibility to break the cycle. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From ls2311 at netcom.com Mon Jul 8 21:58:08 2002 From: ls2311 at netcom.com (Lowel Stern) Date: Mon, 08 Jul 2002 18:58:08 -0700 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> Message-ID: <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> On Mon, 08 Jul 2002 21:07:21 -0400, Peter Hansen wrote: >Lowel Stern wrote: >> >> fp = os.popen('prog "stern:STWA" 1234') >> >> the above works fine. The quotes must be as shown they may not be >> changed. The problem is I need to be able to change programatically >> the section "stren:STWA" and the 1234 section I have not figured a way >> to do the substitution yet any ideas. > >Do you know about the % operator? > Yes I do. >>>> 'prog "%s" %s' % ('stern:STWA', 1234) >'prog "stern:STWA" 1234' >>>> userpass = 'phansen:secret' >>>> port = 567 >>>> 'prog "%s" %s' % (userpass, port) >'prog "phansen:secret" 567' You will find that if you use the %s with the popen command you get an error: TypeError: unsupported operand type(s) for %: 'file' and 'str' > >Does that help any? > >-Peter Still looking for a solution Lowel From BPettersen at NAREX.com Wed Jul 10 15:37:48 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 10 Jul 2002 13:37:48 -0600 Subject: Win32 Registry Manipulation w/PythonWin? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158F29@admin56.narex.com> > Matthias Huening wrote: > > Tim Daneliuk wrote in > > news:qmqgga.g31.ln at eskimo.tundraware.com: > > > > > >>Does some kind soul out there happen to have a pointer to a > >>tutorial/examples on fiddling with the Win32 registry from PythonWin? Here's a small example we're using internally to add an entry to a machine's path variable (without security patches applied, you can do this from any machine on your network, so consider yourself warned :-) -- bjorn import _winreg def addPathEntry(entry, machine=None): HKLM = _winreg.ConnectRegistry(machine, _winreg.HKEY_LOCAL_MACHINE) SYSTEM = _winreg.OpenKey(HKLM, 'SYSTEM') CurrentControlSet = _winreg.OpenKey(SYSTEM, 'CurrentControlSet') Control = _winreg.OpenKey(CurrentControlSet, 'Control') SessionManager = _winreg.OpenKey(Control, 'Session Manager') Environment = _winreg.OpenKey(SessionManager, 'Environment') path, type = _winreg.QueryValueEx(Environment, 'Path') pathlist = path.split(';') if entry not in pathlist: pathlist.insert(0, entry) path = ';'.join(pathlist) EnvironmentWrite = _winreg.OpenKey(SessionManager, 'Environment', 0, _winreg.KEY_SET_VALUE) _winreg.SetValueEx(EnvironmentWrite, 'Path', 0, _winreg.REG_EXPAND_SZ, path) _winreg.CloseKey(EnvironmentWrite) _winreg.CloseKey(Environment) _winreg.CloseKey(SessionManager) _winreg.CloseKey(Control) _winreg.CloseKey(CurrentControlSet) _winreg.CloseKey(SYSTEM) _winreg.CloseKey(HKLM) From eric.brunel at pragmadev.com Thu Jul 25 10:23:27 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 25 Jul 2002 14:23:27 +0000 Subject: how to get a return value from an exception ? References: Message-ID: Shagshag13 wrote: > hello, > > i need to raise an exception which "carry" some data... i think that it's > something like : > > class MyException(Exception): > > def __init__(self, *args): > Exception.__init__(self, args) > >>>> raise MyException('one', 2, 'three') > Traceback (most recent call last): > File "", line 1, in ? > raise MyException('one', 2, 'three') > MyException: ('one', 2, 'three') > > but them how to access to 'one', 2, and 'three' ? Just do the following: class MyException(Exception): def __init__(self, arg1, arg2): Exception.__init__(self) self.arg1 = arg1 self.arg2 = arg2 try: raise MyException('one', 2) except MyException, ex: print ex.arg1, ex.arg2 > it's ok if i do it like in "dive in python" > >>>> class MyError(Exception): > def __init__(self, value): > self.value = value > def __str__(self): > return `self.value` > > but here what does the `` stand for ? It's an equivalent for repr(...): it converts its argument to its "canonical" string representation. I don't know the original intent of this code, but I suppose it was just to actually see what was the value and its type when the exception ends up in a traceback. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From david.evans at ittransition.co.uk Sun Jul 14 11:07:21 2002 From: david.evans at ittransition.co.uk (david evans) Date: Sun, 14 Jul 2002 16:07:21 +0100 Subject: Is there a Python text-editor suitable to embed in a VB app (newbie question) Message-ID: <1026659235.9237.0.nnrp-10.3e314eb6@news.demon.co.uk> I'm very new to Python (nearly 10 day experience now) but thanks to "Python Programming on Win32" I've been able to construct a VB prototype, ODBC based development tool with a Python "scripting" cabability. My script editor is really sad though. It's simply a MS text box. Is there a way that I can embed the Pythonwin editor (or similar, existing, language-aware editor) into a VB project? Any suggestions or pointers (other than write it all in Python -- I'm not good enough to do that) will be gratefully received. Thanks in advance David Evans From fperez528 at yahoo.com Mon Jul 8 14:51:47 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 08 Jul 2002 12:51:47 -0600 Subject: structs in python References: <20020706231200.A25295@arizona.localdomain> <7xbs9i91h3.fsf@ruckus.brouhaha.com> <20020708192934.7d16b9c4.christophe.delord@free.fr> Message-ID: Christophe Delord wrote: > > The dict can be the __dict__ attribute of a particular class : > > > class Record: > > def __init__(self, **kw): > self.__dict__.update(kw); > > p = Record(x=10, y=11, color='blue') > > print p.x such a class can then be conveniently updated later with the following: def with(object, **args): """Set multiple attributes for an object, similar to Pascal's with. Example: with(jim, born = 1960, haircolour = 'Brown', eyecolour = 'Green') Credit: Greg Ewing, in http://mail.python.org/pipermail/python-list/2001-May/040703.html""" object.__dict__.update(args) If you want a full-blown class which implements struct-like functionality with both dictionary-type (s['blah']) and struct-type (s.blah) access for its data members, you can use my Struct.py from: http://windom.colorado.edu/~fperez/python/misc/Struct.py An html syntax-highligted version is at: http://windom.colorado.edu/~fperez/python/misc/Struct.py.html Having both kinds of access allows explicit named acess: s['blah'] == s.blah but also access by variable: x='blah' s[x] == s['blah'] Obviously, any '.' access is explicit by name always. Besides allowing both types of access (dict and struct), it has all the behavior of a dict (keys, values, items, update, get, setdefault, etc) plus a fancy 'merge' method which is a flexible version of update. It allows you to update a Struct with fine control over what to do when collisions are found (update simply overwrites old data, not always what you want). This makes it very useful for keeping configuration information which needs to be updated in various forms, for example. I've successfully used this class in several projects, and it's extremely convenient. Note however that it was coded for convenience, not speed. If you use it and find any bugs in it, please let me know. Note that it requires the following function from a module I have around called genutils. You can simply paste the following in Struct.py and remove the import line: def list2dict2(lst,default=''): """Takes a list and turns it into a dict. Much slower than list2dict, but more versatile. This version can take lists with sublists of arbitrary length (including sclars).""" dic = {} for elem in lst: if type(elem) in (types.ListType,types.TupleType): size = len(elem) if size == 0: pass elif size == 1: dic[elem] = default else: k,v = elem[0], elem[1:] if len(v) == 1: v = v[0] dic[k] = v else: dic[elem] = default return dic From jwbaxter at spamcop.net Wed Jul 31 23:57:04 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Wed, 31 Jul 2002 20:57:04 -0700 Subject: How to find out if february has 29 or 28 days ? References: Message-ID: In article , Eric Brunel wrote: > A year is a leap year if it can be divided by 4, except if it can be > divided by 100, where it's a leap year only if it can be divided by 400. It > sounds awful to compute, but in Python, it's actually quite simple: With ongoing discussion of a potential y4k exception exception exception (not leap year) to adjust just a bit more finely. For most purposes, we have time to deal with that one. --John From davidw at uq.net.au Fri Jul 12 05:34:07 2002 From: davidw at uq.net.au (David Wright) Date: Fri, 12 Jul 2002 19:34:07 +1000 Subject: Guido van Rossum Tutorial - .PDF or other format? References: Message-ID: Wow...!! Thanks for that. So much to read and so little time :) -- David Wright ~~~~~~~~~~~~~~~~~~~~~~~~~~ Education is not the filling of a vessel, but the kindling of a flame." - Socrates ~~~~~~~~~~~~~~~~~~~~~~~~~~ From duncan-news at grisby.org Wed Jul 3 12:02:18 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 03 Jul 2002 16:02:18 GMT Subject: Thread safetyness in Python References: Message-ID: In article , Jeff Epler wrote: >On Wed, Jul 03, 2002 at 02:12:39PM +0000, Gerhard Haering wrote: >> John Goerzen wrote: >> > 1. In C, a++ would be atomic because CPUs have an atomic increment >> > operation, in most cases. >> >> What about SMP systems? > >Being one instruction is not enough to be atomic in SMP systems. For Even if the architecture had a reliable atomic increment instruction, there's no guarantee that the compiler would use it. It's entirely likely that the optimiser would generate code to do the increment in a register, and write it back to memory much later. None of this is relevant to Python, of course... Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From gerhard.haering at gmx.de Tue Jul 9 23:13:34 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 10 Jul 2002 05:13:34 +0200 Subject: How to grab a part of web page? In-Reply-To: <3D2B6810.13895.8A3A7A@localhost> References: <3D2B6810.13895.8A3A7A@localhost> Message-ID: <20020710031333.GB1965@lilith.my-fqdn.de> * A [2002-07-09 22:47 +0200]: > Hi, > Is it possible to download only a part of web page? Yes, but the file-like objects returned by python's urllib don't support seek(), yet. > [...] Is it possible to use httplib or necessary socket module? httplib is quite possible, and what the section that this example prints, explains how it works: from httplib import HTTPConnection conn = HTTPConnection("www.ietf.org:80") # Bytes form 100 onward #conn.request("GET", "/rfc/rfc2616.txt", headers={"Range": "bytes=100-"}) # The RFC section describing the Range header conn.request("GET", "/rfc/rfc2616.txt", headers={"Range": "bytes=336069-341643"}) # Last 100 bytes #conn.request("GET", "/rfc/rfc2616.txt", headers={"Range": "bytes=-100"}) resp = conn.getresponse() print resp.read() Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.7 ?C Wind: 2.1 m/s From aleax at aleax.it Wed Jul 10 03:25:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 07:25:23 GMT Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207091153.7b2484be@posting.google.com> Message-ID: Terry Reedy wrote: ... > PS. The notion that competitor would try to attack product by > attacking invisible-to-user implementation language strikes me as > bizarre. Reeks of desperation. It does in fact happen quite often -- a technology used in the making of a product is targeted for 'for' or 'against' marketing, rather than user-visible aspects of the product. It's in particular quite prevalent in software. I recall a competitor, back when I was with think3, who made a great splash about how they had converted their PDM product from C++ to Java -- then, a couple years later, another great splash about how good it was that they had converted from Java to C++. Our salespeople did not have a particularly hard time with that -- just showing prospects the competitor's press cuttings from the _two_ conversions side by side made for a guaranteed barrel of laughs and spontaneous customer quips about looking forward to yet another round in a couple more years about another conversion back to java. But that was a _particularly_ clueless case, of course. The overall idea is not deeply different from detergent commercials of the '50s "now with new miracle ingredient XK7!". In theory the customer couldn't care less about XK7 -- but it's hoped he or she will take it as a proxy for this now being a better detergent. I don't think detergents &c are marketed that way any more -- if anything you're likely to see something about "all-organic, natural" etc -- but many other products still are... Alex From emile at fenx.com Tue Jul 2 08:33:58 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Jul 2002 12:33:58 GMT Subject: Simple Conceptual Pickling problems References: <3d217732$0$4276$afc38c87@news.easynet.co.uk> <3d2194c1$0$4280$afc38c87@news.easynet.co.uk> Message-ID: chris lyon > So , if I understand you, Because I ran the original code using the > Pythonwin environment, I produced the objects in module __main__ NOT in the > module I though they were being created in ( in my case a module called > octavia which contains the class Programmes). > > When I then ran with my test module, which imported octavia, The Unpickle > process believed it was trying to unpickle objects defined in __main__ NOT It's not so much the process as the contents of the pickle that determines that. > from within octavia ? You got it. > > So should I then have a module 'above' my octavia module which will import > octavia for it to work? > Either that, or let octavia always run as main, or move your test code into octavia, or import your testcode into octavia. ;-) -- Emile van Sebille emile at fenx.com --------- From dhananjay at aworkflow.com Thu Jul 25 03:50:09 2002 From: dhananjay at aworkflow.com (dhananjay) Date: Thu, 25 Jul 2002 13:20:09 +0530 Subject: VERY URGENT : Python 2.2 Installation on Solaris 2.5 Message-ID: <002801c233af$f239c1c0$8f00a8c0@scanner> Can you send us the Python 2.2 package for installation on Solaris 2.5. We could not install from Python binary file. From the www.sunfreeware.com site we see that Python 2.1.1 package is available only for Solaris 7. Can this Python 2.1.1(for Solaris 7) package be installed on Solaris 2.5? Please let us know. This information is urgently required. At present we have Python 1.5.2 installed from Python1.5.2 package. Thanks, In Anticipation of an early reply. Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From nadavh at envision.co.il Wed Jul 10 05:42:40 2002 From: nadavh at envision.co.il (Nadav Horesh) Date: Wed, 10 Jul 2002 11:42:40 +0200 Subject: leastSquaresFit Message-ID: <3D2C0190.5060307@envision.co.il> This least-squares fitting code runs without an error under python 2.1 and 2.2 with Numpy 21.0 and Scientific python 2.2. Although python 1.5.2 is good piece of work, I see no reason for those who do numerical analysis not to proceed to ver 2.2. I also advice you to try scipy --- it is much more professional then ScientificPython. Nadav. From bebert at worldonline.dk Sun Jul 7 17:47:45 2002 From: bebert at worldonline.dk (Bjarke Dahl Ebert) Date: Sun, 7 Jul 2002 23:47:45 +0200 Subject: is this a bug? References: <1026076470.877638@master.nyc.kbcfp.com> Message-ID: "Alex Martelli" wrote in message news:Ai2W8.52808$vm5.1964179 at news2.tin.it... > It's a bug in your code. (x) is not a tuple, whatever x If x is a tuple, then so is (x) ;-) Bjarke From smulloni at bracknell.smullyan.org Tue Jul 2 14:00:04 2002 From: smulloni at bracknell.smullyan.org (Jacob Smullyan) Date: 2 Jul 2002 14:00:04 -0400 Subject: Preforked server in Python References: <3D1EB82C.1000501@awal.net.sa> Message-ID: Take a look at SkunkWeb's ProcessMgr, which is deliberately very simple: "http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/skunkweb/"\ "skunkweb/pylibs/ProcessMgr/" In article <3D1EB82C.1000501 at awal.net.sa>, rayed wrote: > Hi, > > I am looking for module similar to SocketServer that prefork chlidren > instead of forking on each request. > > Thanks in advance > > - rayed > From gerhard.haering at gmx.de Thu Jul 18 13:24:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 19:24:19 +0200 Subject: [Announce] Gnosis (XML) Utils 1.0.3 In-Reply-To: References: <1026992252.2034.4.camel@fnsnb40> Message-ID: <20020718172419.GB2112@lilith.my-fqdn.de> * David Mertz, Ph.D. [2002-07-18 13:08 -0400]: > It may be obtained at: > http://gnosis.cx/download/Gnosis_Utils-1.0.3.tar.gz 404 > The current release is always available as: > http://gnosis.cx/download/Gnosis_Utils-current.tar.gz 404 Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cliechti at gmx.net Wed Jul 24 12:33:35 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 18:33:35 +0200 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> Message-ID: "Jay O'Connor" wrote in news:20020724.064941.722308542.1589 at cybermesa.com: > A while back, as part of a code sample I submitted for a job, I developed > a basic framework for distributed Python. This is a tool that allows one > Python application to communicate with another, whether on the same > machine or on remote machine(s) > > Being that it was just a sample, I never fully fleshed it out. I've been > contemplating developing it further but first I was wondering if such a > tool would be of interest to anyone else http://pyro.sf.net was not yet mentioned :-) chris -- Chris From pablo17 at hispavista.com Fri Jul 26 10:07:12 2002 From: pablo17 at hispavista.com (Pablo) Date: 26 Jul 2002 07:07:12 -0700 Subject: Python, QT, PyQt in Windows References: <3d4115c6$0$31242$e4fe514c@dreader1.news.xs4all.nl> Message-ID: Hello, Phil, and Boudewijn Thanks a lot for the warm help. I will take another try following your suggestions. Thanks again. From aleax at aleax.it Sun Jul 14 16:35:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 14 Jul 2002 20:35:10 GMT Subject: List to STR to List References: Message-ID: <2glY8.79177$vm5.2885629@news2.tin.it> Larry wrote: > I can convert a list to a string as follows: > > List1 = [1,2,3] > String1 = str(L1) > > Is there now a way to convert my String1 variable back into a list??? There are several ways, but probably the most reasonable one is: import rexec alist = rexec.RExec().r_eval(String1) All those 'r' stand for Restricted -- you want Restricted execution (evaluation, in this case) to make sure no disaster can happen, just in case the string may have been hacked by some clever fellow. If you must perform many such evaluations, it's speedier to: import rexec rr = rexec.RExec() alist1 = rr.r_eval(String1) alist2 = rr.r_eval(String2) alist3 = rr.r_eval(String3) i.e., instantiate rr once then use it over and over. If you are ABSOLUTELY sure nobody can POSSIBLY have tampered with String1 in ANY way, shape, or form, there may be slightly handier ways to proceed. But since such absolute certainty is rare, and unfounded some of the time it's present, I suggest you stick to this approach. Alex From aleax at aleax.it Fri Jul 12 04:01:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 08:01:36 GMT Subject: Python to XML to Python conversion References: <3D2E1793.8030600@jerf.org> Message-ID: Jeremy Bowers wrote: ... > the choice of *last* resort, when you absolutely *need* easy parsing in > multiple languages or environments and can't get it any other way. It is I think this assertion, as it stands, is untenable. There just about IS *some* other way -- e.g., inventing your own little language for data description and writing from scratch the needed parsers in all languages and environments of interest. Are you SERIOUSLY claiming that such reiterated reinventions of the wheel -- which were a good part of the data interchange "state of the art" before XML appeared -- should be used in preference to XML?! Similar comments apply to most traditional ways of data interchange in heterogeneous environments -- overextensions of simplistic formats such as CSV, empirically-determined parsing and heuristics for unspecified and underspecified proprietary and human-oriented formats, rigid and unportable binaries. XML is generally preferable to any of these traditional kludges, even though one or more of them most often IS available and thus breaks your dubious criterion of "can't get it in any other way". Apparently, the ridiculous over-hype that has greeted XML in parts of the media (including much non-technical media) is triggering an allergic reaction of similarly-ridiculous hostility. On one side we see abuses such as XML files used where (e.g.) relational DB's would be the obvious solution, on the other, broadsides such as this one definitely appears to be. Fortunately, there's a lot of us engineers in the middle, applying skeptical, field-tested "filters" to media hype AND other overbroad tirades. XML is often a good choice for heterogeneous-environment data interchange -- far from being "the choice of *last* resort" for such tasks, it's generally a good default choice unless some obviously better alternative is evident. For tasks that are borderline cases of "heterogeneous data interchange", such as storing and retrieving (or communicating) data among a set of programs that aren't really all that heterogeneous, XML should still be considered when ability to examine and potentially tweak the stored data with other programs is of interest, and the costs wrt proprietary or language-specific formats (in terms of time and/or space) aren't out of line with the potential benefits. Alex From jonathan at onegoodidea.com Fri Jul 12 09:44:10 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 12 Jul 2002 14:44:10 +0100 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: On 12/7/2002 9:37, in article HzwX8.71016$vm5.2601431 at news2.tin.it, "Alex Martelli" wrote: > Jonathan Hogg wrote: > ... >> I'm not sure it is possible to "overuse" XML. > > It is -- easily. My pet peeve is the idea of using XML files for > tasks that obviously need a real database, preferably a relational one. > > I think some people never really GOT relational databases, no matter > that they've been around for decades and are so widespread, and they're > now turning to *overusing* XML to cover up for that:-). OK, I'll narrow my earlier statement to: I'm not sure, when discussing file formats for off-line structured data, that it is possible to "overuse" XML. Clearly when the data has to be accessed on-line (by this I mean that the file is left open and used throughout the lifetime of the application) a database makes much more sense. I was assuming my statement would be read within the context of the thread (Pickling data). >> If you need to read and >> write structured data, why bother coming up with your own format? (see: >> the entire contents of /etc) Or why use something that is proprietary to a >> particular language or system? (see: Pickle) > > Speed, size, and convenience are possible reasons. If the structure > is highly repetitious, and the amount of data is very large, then > repeating the tags identically a zillion times can impose substantial > overhead of space and time. [...] I like to consider these as special cases where I have no choice but to use a compact file format. Even there, if space is the issue (rather than time), running the file through a good compressor/decompressor as it is written/read is likely to result in much better savings than trying to think of a super-compact binary layout. > The need to search "random-access" wise, or "keyed"-wise, is often > an excellent reason to avoid a format that requires reading though > all of a file to get at a particular piece of data. dbm variants, > shelve, and relational databases, can be huge wins here (compared to > XML, pickle, or any other choice requiring whole-file reloading). As above, a specialised database will always make more sense here. Though arguably, for small quantities of data that can be slurped completely into memory, it may not make any difference. Also, XML databases can be used and make a lot of sense if the data can be arbitrarily structured. People are often very poor at designing relational schemas. > While XML is reasonably human-editable, there may well be formats > that are more convenient than it for this purpose, avoiding the > need of special-purpose XML-oriented editors and allowing the use > of any good old text editor with maximal ease. This is a good > reason to keep a human-editable configuration file in non-XML > form, in my opinion. I just don't think that this argument is strong. XML is readable enough and most decent editors will provide at least rudimentary syntax highlighting for XML. With the addition of DTDs or Schemas it is easy for a generic XML editor to validate the format of the file - very useful for complex configuration files. I think the most value in using XML comes in the associated standards such as XSLT, XPointer, XPath, etc. Consider a recent question on obtaining a list of nameservers on a machine. The answer on UNIX was variously given as: "read /etc/resolv.conf pulling out the lines beginning with 'nameserver' and grabbing the part after that". Consider if resolv.conf used XML - perhaps something looking like: python.org 123.45.67.89 87.65.43.21 You might say that this is verbose and monstrous, but it's readable and fairly obvious in meaning. However, going back to the question, we can now reference the information required using a simple XPath query: >>> from xml.dom.minidom import parse >>> from xml.xpath import Evaluate >>> >>> config = parse( 'resolve-config.xml' ) >>> query = '/resolve-config/nameservers/nameserver/text()' >>> for node in Evaluate( query, config ): ... print node.nodeValue ... 123.45.67.89 87.65.43.21 Now someone can follow up to this post with a similarly small program that would have pulled the information out of the normal resolve.conf file faster, but this is probably the simplest format of any configuration file used in a UNIX system. Try getting anything useful out of an Apache config file. If Apache used XML, then I could write an XPath query that would pull out the document root of a particular virtual server with a single query something like: //virtual[normalize-space(server-name)='www.python.org']/document-root A good XML editor would be able to point out errors in my configuration file as I make them, and I could write an XSLT transformer to convert the configuration file into a nice XHTML document, or more importantly use an XSLT transformer to *create* the configuration file from XML website specifications conveniently stored in a central XML configuration database. > Let's try to avoid pro-XML hype in an attempt to counter the > anti-XML hype that's suddenly burst on this group...:-) Agreed :-) But on the other hand, I don't think this is hype. This is stuff I have to deal with all the time. My life would be about an order of magnitude easier if everything used XML for configuration and interchange. And the great thing? It's already happening, and I already see things being made easier for me. Jonathan From emile at fenx.com Thu Jul 4 12:43:25 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 16:43:25 GMT Subject: Thanks ... and how to express them. References: <3d2479ba$0$24410$afc38c87@news.easynet.co.uk> Message-ID: chris lyon > Just a question of etiquete. > I have recieved beneficial help form individuals do I thank on the list or > not? > Simple off list emails are nice... ;-) -- Emile van Sebille emile at fenx.com --------- From russellcecala at netscape.net Mon Jul 22 17:43:58 2002 From: russellcecala at netscape.net (Russell Cecala) Date: 22 Jul 2002 14:43:58 -0700 Subject: Python and weave Message-ID: <14d3c801.0207221343.4d1ea260@posting.google.com> Hi, I am trying to install weave in a cygwin Windows XP environment. I have and require at least two different versions of gcc. The problem is that when I execute >>> import weave >>> weave.test() I get many error because weave (or maybe python) picked up the wrong version of gcc to use. How can I specify which gcc to use when I execute ... >>> weave.test() ...? Thanks From tjreedy at udel.edu Wed Jul 24 20:20:58 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Jul 2002 00:20:58 GMT Subject: A better self References: Message-ID: "Michael Chermside" wrote in message news:mailman.1027533340.29544.python-list at python.org... > # A program to sort lines. Takes, as command-line argument, a ... > But all of these are dwarfed (for large file sizes... let's say 1 GB of > text) by the fact that you are running a REALLY FAST sort algorithm. Few of us appreciate the days that Tim Peters spent writing a portable sort program that is significantly better than standard quicksort for several classes of input (such as a sorted list with new items appended to the end). He is currently working on another that may be even better. (Three horn toots for Tim.) > Of course, you could code the same sort algorithm in C yourself. Hmm. How many of us have both the skill and patience to develop and test such a delicate and complex algorithm tweaked for various special cases -- and apparently release it bug free (Tim says there has never been a report of the current sort malfunctioning). > for that matter, you could copy the sort algorithm (written in C) from > the C source to Python (Python's liscense allows that!). But you > wouldn't. Really... you wouldn't. Only if really forced to by a crazy employer. >(notice how I never had to stop to think about memory allocation or max line lengths?). Yes -- or number of lines. Merely writing the generic C equivalent of lines = file('datalines.txt').readlines() is a bit of a headache. Nice posting. Terry J. Reedy From aleax at aleax.it Sun Jul 7 07:48:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 11:48:55 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> Message-ID: Thomas Jensen wrote: ... > I was planning on spawning one single-threaded XMLRPC-server per CPU per > machine and then having a control process on one of the machines with a > thread per process. These threads would fetch unit numbers from a Queue > object and call the XMLRPC server using xmlrpclib. > > Am I correct in beliving that this would utilize all CPUs? (Windows > issues aside). Yes, but xmlrpclib may not yield the best performance -- since performance appears to be key for you, you may want to look at other distributed computing solutions, such as pyro (pyro.sourceforge.net). Alex From jdhunter at ace.bsd.uchicago.edu Mon Jul 29 11:27:44 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 29 Jul 2002 10:27:44 -0500 Subject: Prob installing Python 2.2.1 on Redhat 7.0 In-Reply-To: <3D455B90.4A3FBF16@monaco377.com> =?iso-8859-1?q?(S=E9bastien?= Cottalorda's message of "Mon, 29 Jul 2002 17:13:21 +0200") References: <3D455B90.4A3FBF16@monaco377.com> Message-ID: >>>>> "S?bastien" == S?bastien Cottalorda writes: S?bastien> LONG_BIT definition appears wrong groups.google.com is your friend. Search for LONG_BIT definition appears wrong John Hunter From shalehperry at attbi.com Sat Jul 27 13:46:05 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 27 Jul 2002 10:46:05 -0700 (PDT) Subject: Two RE proposals In-Reply-To: Message-ID: > > If you're the owner of the re module and are willing to provide mentoring, > I'm willing to add these. > that would be Fredrik Lundh. From aleax at aleax.it Thu Jul 25 04:52:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 08:52:53 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: Fredrik Lundh wrote: > Alex Martelli wrote: > >> BTW, GvR claimed (less than a month ago on the python-dev list) >> that having an integer argument to readlines was a design error. > > except that he was talking about "readline", not "readlines". Sorry, you're right. The argumernt to readlines was not discussed. > (does anyone here even know that readline takes an optional > integer argument, and what it does? ;-) I would hope so, given that http://www.python.org/doc/current/lib/bltin-file-objects.html documents it so clearly. Basically: all of read, readline, readlines methods take an optional integer argument "maximum number of bytes to read". HOWEVER, according to the docs, read and readline HAVE to respect that argument and are never allowed to return more than N bytes when called with an argument of N. readlines, OTOH, takes its argument as just a hint and is explicitly documented as being perfectly well allowed to ignore it completely if impossible or inefficient to implement, round it up when convenient, whatever. f.readline(N) may return a partial, incomplete line if that's the best it can do without exceedinng N bytes. Docs for f.readlines(N) are not quite as clear on this point, but it seems that readlines is NOT allowed to return incomplete lines -- rather it should return more than N bytes (as it's explicitly allowed to) if needed. That's definitely what the current implementation does. Module xreadlines (and thus f.xreadlines, which is explicitly documented as being equivalent to a call to xreadlines.xreadlines(f)) uses f.readlines(N) (both by the docs, and by the implementation). Alex From jonathan at onegoodidea.com Wed Jul 31 18:26:25 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 31 Jul 2002 23:26:25 +0100 Subject: C++/Python version problems? References: <3D484ACD.7030503@nonesuch.com> Message-ID: On 31/7/2002 21:38, in article 3D484ACD.7030503 at nonesuch.com, "David Smith" wrote: > I'm running Python 2.2.1 under Linux, and successfully interfaced my C++ > procedures into Python. Then I got more aggressive with the templates, and > g++2.95 wouldn't compile it. So I got g++ 3.0, and it compiles -- I used > distutils/setup.py to make the shared object file. But, now when I try to > import my module, I get the error message: > > ImportError: ./cfuncs.so: undefined symbol: __gxx_personality_v0 > > Does this maybe have to do with Python being compiled under an older g++, or > being linked with an older library? Any suggestions as to what I should do? Didn't the C++ ABI change substantially from 2.95 to 3.x? I think the easiest way to answer your question would be to go back and recompile Python with g++ 3.0 and see what happens ;-) Jonathan From jack_diederich at email.com Mon Jul 29 12:44:54 2002 From: jack_diederich at email.com (Jack Diederich) Date: Mon, 29 Jul 2002 11:44:54 -0500 Subject: sort() comparison lambda for floats/longs Message-ID: <20020729164454.13371.qmail@email.com> I had to sort a list of list of floats (Nx2 array) but I couldn't find a comparison function that would take a little error delta to do the std C-style comparison if (a + delta > b && a - delta < b) { printf("Yeah, a == b"); } here is a lambda I am using in a list.sort() delta_cmp = lambda a,b,delta=0.00001: int((((a+delta) > b and (a-delta) < b) and '0') or (a > b and 1) or (a < b and -1) ) The int() is needed to turn the '0' from true into zero It uses the side effects of 'or' and 'and' to return 0/1/-1 I need the delta because I'm also sorting on the second column, which could be an int or string, or anything. If it was just a single list of floats then a compare without a delta would work because all the nearly-equal values would still be next to each other. to sort this ll = [[1.0, 'A'], [2.0, 'B']] I would do ll.sort(lambda a,b: delta_cmp(a[0],b[0]) or cmp(a[1], b[1])) Is there a better way to do this in python? thanks in advance, -jackdied -- __________________________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup Get 4 DVDs for $.49 cents! plus shipping & processing. Click to join. http://adfarm.mediaplex.com/ad/ck/990-1736-3566-59 From peter at engcorp.com Mon Jul 22 19:29:27 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 19:29:27 -0400 Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3ACE59.1060004@lmco.com> <3D3AEDD6.78B39D70@engcorp.com> <3D3C42AD.8050005@sschwarzer.net> Message-ID: <3D3C9557.35F9A1BD@engcorp.com> Stefan Schwarzer wrote: > > Hello Peter > > Peter Hansen wrote: > > When you create an object ("instantiate a class") you > > must bind it to a name ("assign it to a variable"). If > > What about > > L = [1, [2, 3]] > > ? The object [2, 3] can be accessed but it doesn't have a name. Yes, but as always please keep the context of the original question in mind. Such nuances are not, in this case, relevant to the OP's question, and I was trying to give him a simple, useful answer. -Peter From mwh at python.net Tue Jul 2 07:19:10 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Jul 2002 11:19:10 GMT Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> Message-ID: Norman Shelley writes: > Fredrik Lundh wrote: > > > ... > > If I were to add a dozen (or so) patterns to the (S)RE module, > > what should I pick? What patterns do you find yourself using > > over and over again? > > All kinds of numerics, e.g. scientific (1e-6, 2e6, ...) and engineering (1u, > 2M and/or 2MEG, ...) notation. > > Python identifiers as previously mentioned. Well, *they're* already in the tokenize module. Cheers, M. -- That's why the smartest companies use Common Lisp, but lie about it so all their competitors think Lisp is slow and C++ is fast. (This rumor has, however, gotten a little out of hand. :) -- Erik Naggum, comp.lang.lisp From jb at hotmail.com Wed Jul 24 03:30:58 2002 From: jb at hotmail.com (JB) Date: Wed, 24 Jul 2002 09:30:58 +0200 Subject: Regular expressions? Message-ID: <3d3e55dd_3@news.newsgroups.com> I am working on an offline newsreader (with very limited capabilities). I think the only way I can reckognize e multi part message is that in the header something like '(1/12)', which I call multi part indicator, is included in the subject line. Now I have seen that sometimes they use '[1/12]' and sometimes this indicator is not at the end of the subject line but somewhere in the middle of the line. (The number of bytes in the message could follow the multi part indicator). So I have to find the indicator in a line. Should I apply regular expressions to solve this problem? -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From pecora at anvil.nrl.navy.mil Tue Jul 23 15:29:08 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 23 Jul 2002 15:29:08 -0400 Subject: Overhead for local assignments (was: A better self) References: <230720021211008411%pecora@anvil.nrl.navy.mil> Message-ID: <230720021529080579%pecora@anvil.nrl.navy.mil> In article , Kerim Borchaev wrote: > It feels like a general advice. > "lots of class function" - it lets everyone decide the meaning of > "lots" for himself; or how should I treat "to just calculate a > formula" - is it for any code that involves "the math"? Yes, but it's for assigning local variables to avoid using self. That's it. If you have other ways you might do it, please test those and post the results. > So I'd give another general advice: > > - Make the code as clean as possible(using functions, methods - all > the best of the language ) BEFORE you discover that it works too slow. > > - And only whan you're absolutely sure(the tests show) that > it's slow for your needs - think about optimization. > > - Then profile test cases of interest to find out which pieces of code are > worth optimizing to get a valuable speedup. > > - Then optimize. ...or not yet? > > Best regards, > Kerim mailto:warkid at storm.ru All good advice, but I don't have the time to do all that. It was meant to be a quick test in response to some suggestions on the "Best self." thread that some of the code people were suggesting should be tried out. Some other quick tests by others appear on that thread. I think what I got was informative since I've seen code and suggestions just like what I offered. You may disagree. Maybe I should put disclaimers in it. Well, live and learn. Thanks. -- Lou Pecora - My views are my own. From aleax at aleax.it Thu Jul 25 10:06:14 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 14:06:14 GMT Subject: xml processing : too slow... References: Message-ID: Shagshag13 wrote: > i think i still miss something as i get : > >>>> line = 'this is an example of the kind of >>>> line that i > could have and that i must check (could also contain 0-9, $ and > punctuations)...' This line, by itself, is not a well formed XML document. > this time line is really representative of the kind of suff i had > (sentences with tag) (i had written a wrapper to handle this with > find('<'), find('>'), and i check well formedness by using a stack...) > > but i would really understand why it doesn't work ! I would suggest you study some XML. A well formed XML document has, among its requirements, a single top-level element that envelops all other elements and textual content. The above example line does not meet this specification. That's part of the reason I keep asking you for *SPECS* rather than the *EXAMPLES* you keep giving. Anyway, from the above line you can obtain a well-formed XML document by wrapping it all in start and end tags for a fictitious XML toplevel element, e.g.: p.parse('%s' % line, 1) should be satisfactory for checking this kind of "sort of well-formedness", unless there are yet more specs as yet unexpressed. Not sure how you intend to check well-formedness by just finding open and closed triangular brackets and a stack. How would that help you diagnosed e.g. of course not as not being well formed? This is not well formed because it lacks quotes around an attribute's value. Or: &either now THIS is not well formed because reference '&either' is not terminated with a semicolon. Etc, etc. expat, of course, has no trouble diagnosing any of these. If there are yet more kinds of non-well-formedness that you need to tolerate, besides the lack of a single top-level element, then of course you should not use an XML parser, since your needs become very far from XML's specifications. But _we_ can't know, unless you DO tell us the specs. Alex From chris_ciotti at attbi.com Thu Jul 25 10:49:24 2002 From: chris_ciotti at attbi.com (chris ciotti) Date: 25 Jul 2002 07:49:24 -0700 Subject: Refer to function name (newbie ques) Message-ID: <805bee23.0207250649.5a4d89d0@posting.google.com> Hi - Is there a way to get the name of the running function? In a script I'm doing some error checking and I want to be able to name the function that screws up. Something like: def foo(): #stuff here if stuff != bar: outfile.write("Mismatch in function %s\n" % (refer to foo() here) Sorry if this is really obvious. Thanks. -- chris From markus.vonehr at ipm.fhg.de Thu Jul 4 10:45:05 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 04 Jul 2002 16:45:05 +0200 Subject: sending a file through sockets References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> Message-ID: <3D245F70.567DC86F@ipm.fhg.de> Why not use ftp? "Guyon Mor?e" schrieb: > Who knows how to send and receive a file(binary data) through sockets? > > thanx, > Guyon From jacek.generowicz at cern.ch Thu Jul 25 03:21:34 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 Jul 2002 09:21:34 +0200 Subject: boost: return pointer to base class Message-ID: Hi, This question has been unfielded on the Boost users list for a couple of days, so I thought I'd try my luck here. My requirements: 1) Expose a C++ class hierarchy to python (using Boost) 2) Allow all the exposed classes to be subclassed, with correct overriding of virtual fuctions 3) Expose a C++ function which returns a pointer to the base class. The problem: Trying 3) makes the compiler complain about lack of an appropriate (boost-generated) conversion funcion. My attempts at providing one by hand have failed (though I could do it before I added the callback classes required by point 2 above). Minimal example code: #include namespace python = boost::python; // A class hierarchy in C++ struct abstract { virtual ~abstract(); }; class concrete : public abstract {}; // Ensure correct python subclassing of the above. struct abstract_callback : public abstract { PyObject * self; abstract_callback(PyObject * Self) : abstract(), self(Self) {} }; struct concrete_callback : public concrete { PyObject * self; concrete_callback(PyObject * Self) : concrete(), self(Self) {} }; // A C++ function which returns a pointer to the base of the C++ // hierarchy abstract* rcbpta() { return new concrete; } BOOST_PYTHON_MODULE_INIT(abstract) { python::module_builder this_module("abstract"); python::class_builder abs_class(this_module, "abstract"); abs_class.def(python::constructor<>()); python::class_builder con_class(this_module, "concrete"); con_class.declare_base(abs_class); con_class.def(python::constructor<>()); // Exposing this function causes problems ! this_module.def(rcbpta, "problem"); } gcc 2.95.2 error message when compiling the above: /python/caller.hpp:430: instantiated from `boost::python::caller::call(abstract * (*)(), PyObject *, PyObject *)' /python/detail/functions.hpp:73: instantiated from `boost::python::detail::wrapped_function_pointer::do_call(PyObject *, PyObject *) const' /function/function_base.hpp:155: instantiated from here /python/detail/extension_class.hpp:388: no matching function for call to `py_extension_class_converters (boost::python::type)' /python/detail/extension_class.hpp:215: candidates are: class python_extension_class_converters py_extension_class_converters(boost::python::type) /python/detail/extension_class.hpp:215: class python_extension_class_converters py_extension_class_converters(boost::python::type) Any prods in the right direction would be appreciated. Thanks, From dougz at cs.washington.edu Tue Jul 2 22:42:21 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Wed, 3 Jul 2002 02:42:21 GMT Subject: Comments in pickles? References: Message-ID: Roy Smith wrote: : [...] I want to check those pickles into CVS. : Our usual practice is to imbed the CVS id string ($Id: ) in every : checked-in file as a comment. Is there any way to do that with a : pickle? Does a comment convention exist which cPickle.load() : understands? It seems that since a pickle might happen to contain spurious instances of the string "$Id:" (or one of the other things that CVS replaces), you would want to turn off CVS's keyword replacement for these files anyway. (*Especially* if you're writing binary pickles.) But if you're not going to do that, you could just adopt a convention where the first line of the file is a comment. To write one, you open a file, write the command, and then dump the pickle data. To read it back, open the file, read and discard one line, then do a pickle load on the rest of the file. dz From russellcecala at netscape.net Mon Jul 22 16:09:27 2002 From: russellcecala at netscape.net (Russell Cecala) Date: 22 Jul 2002 13:09:27 -0700 Subject: Python and weave question. Message-ID: <14d3c801.0207221209.197171b9@posting.google.com> Hi, I am new to Python and weave. Weave is suppose to supply Inline::C and Inline::C++ functionality. The question i have is that when I execute the Python commands like so ... >>> import weave >>> weave.test() ... it appears the test fail because either Python or weave are using the wrong gcc command. I have and need to keep several versions of gcc around so just removing the "wrong gcc" is not a solution. How can I get Python or weave to use a differenct gcc. I am using Cygwin on a Windows XP system. Thanks! From mgerrans at mindspring.com Sat Jul 6 15:37:07 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sat, 6 Jul 2002 12:37:07 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: > One of the next development tasks is rewriting the nightly processing > job which is having problems with our ~100mb database (it it written in > Borland C++, but absolutely not optimized for speed!). BCB is great -- and you can still use it for the performance-critical areas by creating COM Automation servers which are a snap to call from Python. One of the great things about Python is that it works well with C/C++ so that you can eat your cake and have it too. > The goals of the rewritten piece of software would be: > * Improved speed Python is not going to help in this area, unfortunately, unless you are talking about improved speed of development! ;-) > * Improved scalability - parallel processing on multiple machines/CPUs This might be more easily accomplished with Java, depending on exactly how you intend to implement it. Java is probably the best tool for distributed processing; in particular JINI is ideal for this kind of thing. > * Improved scalability - ability to handle greater databases (>1gb) This is probably more dependent on your design than the language or platform you choose. > * Ability to calculate only a subset of the data Also dependent more on your design. > Now, instead of rewriting the job in C++, I'd (of course) like to use Python. Naturally! > However the CEO (small company, told you :-), made a couple of somewhat > valid points against it. > 1) He was worried about getting a replacement devlopper in case I left. I don't think that is a problem at all, these days. I think Python developers are becoming pretty ubiquitous. On top of that, any experienced programmer can learn Python in a snap -- it is so engaging that it is fun and quick to learn. In fact, you can show him some Python and the equivalent C++ as a demonstration of how much simpler and elegant Python is. For instance, can you imagine writing a small program in C++ which will recurse directories doing a search-and-replace operation with regular expressions support? It is a big task in C++, but it is pretty trivial in Python. > 2) He said, "Name 3 companies using Python for key functions" I'd bet *every* company in the Fortune 500 uses Python for one thing or another, whether they know it or not. Many are probably using it for very important functions; they just don't advertise it. Why should they -- their business is not about explaining how they accomplish every task, it is about doing it. I have developed Python code for one of the largest of them that is very key to their business, but I doubt that the CEO would know of it or that the company would tout this fact -- what they care about is creating and selling thier products. > 3) He was worried about the stability/reliability of python in our > production environment (you know, 99.999 % and all that) As long as you are not using it for GUI development, in my experience, it is extremely solid. > I was hoping someone in this group could help with some really > compelling arguments, as I'd really to use Python for this job. I think the most compelling argument you can come up with is to write a demo in Python that works on a subset of the data, as you mentioned above. The speed with which you can develop and the quality of the code you develop will be the biggest selling factor. Be aware that your demo could also convince you that Python is not the right tool for the job as well. Python is a great tool, but it is not the best tool for *every* task. From jacek.generowicz at cern.ch Fri Jul 26 11:43:59 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 26 Jul 2002 17:43:59 +0200 Subject: boost: return pointer to base class References: Message-ID: John Hunter writes: > >>>>> "Jacek" == Jacek Generowicz writes: > > Jacek> 1) Expose a C++ class hierarchy to python (using Boost) > > Jacek> 2) Allow all the exposed classes to be subclassed, with > Jacek> correct overriding of virtual fuctions > > Jacek> 3) Expose a C++ function which returns a pointer to the > Jacek> base class. > > In general, returning passing raw pointer in boost::python is > problematic. Don't I know it! Unfortunately the signatures of the functions I am trying to expose are completery beyond by influence. > Have you read > http://www.boost.org/libs/python/doc/pointers.html? Of course :-) > I was able to compile your code by replacing the raw pointer return > with a shared pointer. Will this suit your needs? > > #include > > boost::shared_ptr rcbpta() { > return boost::shared_ptr(new concrete()); > } I can't touch rcbpta's real-world equivalents, but I should be able to use a wrapper: boost::shared_ptr rcbpta_W() { return boost::shared_ptr(rcbpta()); } I'd better add "study boost::shared_ptr" to my (rapidly lengthening) to-do list. Thanks very much, John ... this was really beginning to annoy me, and your suggestion looks very promising at the moment. From zopestoller at thomas-guettler.de Wed Jul 24 07:33:58 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 24 Jul 2002 13:33:58 +0200 Subject: visual basic 6 References: Message-ID: <3D3E90A6.5090008@thomas-guettler.de> Nick wrote: > Hi my name is Nicholas and I am using visual basic 6 at school but I am > have difficulty with understanding what my teachers is trying explaining > and I was wondering if you had any information like a beginners guides > that could help me. 1. Turn off HTML-Messages 2. Read the Python Tutorial 3. Install cygwin and xemacs thomas From edream at tds.net Wed Jul 10 09:54:53 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 10 Jul 2002 13:54:53 GMT Subject: newbie: binding args in callbacks Message-ID: <3D2C3CAB.BE7084F1@tds.net> This question was asked a while back, and I don't see it in the FAQ or in the archives... I would like to create a set of Tkinter callbacks that vary only in the bindings of a single argument. For example, I would like to do: for val in vals: b = Tk.Button(...,command=self.myCallback(val)) But this doesn't work: it executes callback, rather than returning the callback function with the second arg bound to val. I also tried: for val in vals: callback=lambda None:self.myCallback(x=val) b = Tk.Button(...,command=callback) But that doesn't quite work either. When the callback executes I get: TypeError: () takes exactly 1 argument (0 given) Can someone explain how to do this? Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From loewis at informatik.hu-berlin.de Wed Jul 31 10:59:40 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 31 Jul 2002 16:59:40 +0200 Subject: global interpreter lock not working as it should References: <200207302247.SAA21093@test-area.com> <20020730202014.A3224@unpythonic.net> Message-ID: anton wilson writes: > > Realtime? Really? So can you tell me what the upper-bound on the runtime > > of > > > > >>> x = 3 > > > > on the hardware you're targeting? [...] > Good question. You have any reasons why we should not use python? I can't comment on why you should or not should use Python, but it is clear that, without further constraints, the statement above has unclear performance characteristics. Specifically, if x already has a value assigned, that value is DECREFed. Depending on whether this was the last reference to x (which may be known not to happen), a deallocation of the old value of x may happen. If deallocation happens, time consumption depends on the type of the old value of x: If it is an instance object with an __del__ (which it may be guaranteed not to be), then this assignment can invoke arbitrary byte code. Furthermore, the assignment is really a dictionary write to some globals dictionary; the time consumption of this dictionary access depends on the number of entries in the dictionary so far (potentially; it usually is only one key compare). Regards, Martin From shalehperry at attbi.com Tue Jul 23 11:05:49 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 08:05:49 -0700 (PDT) Subject: Make me beautiful (code needs help) In-Reply-To: Message-ID: > > Here's my current code: > > for i in range(len(data["A"])): > try: > data["new"].append(data["A"][i] - data["A"][i-1]) > except OutOfBounds: > data["new"].append("?") > > Now, the other problem, is that in general, I want to fill data["new"] with > an arbitary function of the values in data["A"]. As a dumb example, I > might want to fill data["new"] with copies of the mean (average) of > data["A"]. So, in some cases, the new values are relative to the current > location (ie i and i-1) and in other they are absolute (ie all of them). > > I can certainly hack through this, but I'm looking for something pretty. I > know python is up to it. > why isn't data['new'][0] == 0? How can there be a difference between [0] and [-1]? def successive(the_list, place): if place == 0: return 0 return the_list[place] - the_list[place - 1] for i in range(1, len(data['A'])): data['new'].append(successive(data['A'], i)) From rpm at wag.caltech.edu Tue Jul 2 14:51:25 2002 From: rpm at wag.caltech.edu (Rick Muller) Date: Tue, 02 Jul 2002 11:51:25 -0700 Subject: Add parent directory to path? References: Message-ID: <3D21F62D.9050801@wag.caltech.edu> I often use the little hack import sys sys.path.append('..') to add the parent directory to the python path. It's nice, e.g., if I want to keep a directory below the program directory that contains test scripts, but still let them easily import the parent directory's modules. This hack worked on Unix and Windows/Cygwin, which up until recently were my only build targets. Now I just got a Apple OS X box, and I find that, despite the BSD heritage, this little hack no longer works. Is there a good platform-independent way of doing this? I figure that something like this should live in os.path, but I didn't find anything appropriate. Thanks in advance for any help anyone can offer. Rick From jepler at unpythonic.net Sun Jul 7 11:26:12 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 7 Jul 2002 10:26:12 -0500 Subject: newbie-question: more then one constructor in a python-class? In-Reply-To: <3D285A64.6000904@snafu.de> References: <3D285A64.6000904@snafu.de> Message-ID: <20020707102606.A5468@unpythonic.net> One pythonic way to do this is with default parameters: class MyClass: def __init__(self, param=None, param1=None): if param1 is None: if param is None: # 1arg case else: # 2arg case else: # 3arg case Jeff From peter at engcorp.com Wed Jul 31 19:40:40 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 31 Jul 2002 19:40:40 -0400 Subject: re.search question References: Message-ID: <3D487578.E311A186@engcorp.com> Sean 'Shaleh' Perry wrote: > > Why use a regex here? > > NOT_READY, READY = (0, 1) > > print '!' > for line in input: > if line == '!': > state = READY > elif line == 'end': > state = NOT_READY: > elif state == READY: > print line > print 'end' Maybe because it's simpler to write (if you know how) and therefore less bug prone? <1/2 wink> (Add "state = None" somewhere at the start of the above and you might be able to run it. Then you'll have to create a list, too, and append each line to it as you go, then return it all with a ''.join(thelist) before you accomplish the same as the regex Hans posted.) -Peter From jslowery at hotmail.com Sat Jul 6 01:25:41 2002 From: jslowery at hotmail.com (Jeremy S Lowery) Date: Sat, 6 Jul 2002 00:25:41 -0500 Subject: re module in restrictricted execution Message-ID: I've done a little customization on a subclass of RExec and have allowed the re module to be imported. I just wanted to drop a tip off that if you want RExec's to use the re module, you have to add hexversion to the ok sys names, like. class MyRExec(RExec): ok_builtin_modules = RExec.ok_builtin_modules + ('symbol', 'types', 'string', 're') ok_sys_names = RExec.ok_sys_names + ('hexversion',) Jeremy S Lowery From cliechti at gmx.net Fri Jul 26 06:55:42 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jul 2002 12:55:42 +0200 Subject: Just starting out References: <1763824.4DULROvNVE@CoReKill@localhost> Message-ID: Michael Hudson wrote in news:lk65z2kclf.fsf at pc150.maths.bris.ac.uk: > Alex Martelli writes: > >> Other smart editors such as SciTE (a tiny elegant wrapper on the >> Scintilla component that IDLE and others use) > > I thought IDLE used Tk's Text widget. i thought too, maybe he meant PythonWin of win32all, there it is Scintilla ... I'm using PythonWin to edit Python sources and SciTE for the rest. chris -- Chris From dlharris at mail.usyd.edu.au Wed Jul 17 12:24:46 2002 From: dlharris at mail.usyd.edu.au (Dave Harrison) Date: Thu, 18 Jul 2002 02:24:46 +1000 Subject: simultaneous iteration of lists Message-ID: <20020718022446.A728@dave@jessica.ucc.usyd.edu.au> Evenin' all, Looking for advice on simultaneous iteration of two lists. I have two lists of equal length (guaranteed) , and I want to iterated over both at the same time without having to write myself a little counter thingo cause it seems slightly unpythonic. Both lists are generated by seperate functions which get their input from seperate sources so using a dictionary isnt an option either. The syntax that is in the back of my brain looks something like for i,j in list1,list2: print i print j But this gives me the error : ValueError: unpack list of wrong size Anyone be of help ? Thanks Dave From haribeau at gmx.de Mon Jul 29 08:32:39 2002 From: haribeau at gmx.de (Clemens Hermann) Date: 29 Jul 2002 05:32:39 -0700 Subject: email auto-responder Message-ID: <6c492956.0207290432.4dcb7945@posting.google.com> Hi, is there any template available for an email auto-responder? I need it at the client-side so the envelope has gone yet before the mail reaches the auto-responder script (--> response to header-FROM). I am not necessarily looking for an out-of-the-box ready to run solution but as my efforts spread quite a bunch of bugs over time I would appreciate to be able to look at a working example. tia /ch From shaunschulze at yahoo.com Mon Jul 1 09:54:39 2002 From: shaunschulze at yahoo.com (Shaun Schulze) Date: Mon, 1 Jul 2002 06:54:39 -0700 (PDT) Subject: communicate with serial port (ttyS0) Message-ID: <20020701135439.19621.qmail@web20514.mail.yahoo.com> Hi I am running Debian/Linux kernel 2.4.17. I need to communicate between custom hardware and my python script via a serial port, eg. ttyS0, at 115.2kb/s. I would like to know how to receive and send data to and from the serial port. I would also like to know how to set the baud rate of the serial port to 115,2kb/s. If anyone has some examples it will also be much appreciated. Thank you Shaun __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From squelart at hotmail.nospam.com Wed Jul 17 22:40:32 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Thu, 18 Jul 2002 12:40:32 +1000 Subject: SSL support in 2.2.1/win Message-ID: <3d362ab9@duster.adelaide.on.net> Hi! I've downloaded and installed python 2.2.1 on my win2k machines, and tried my first program... And I was disappointed to see that SSL support is not enabled by default. That was embarassing since my colleague made a similar program in perl, which seems to support SSL by default. Any reason for not including SSL by default? Do I have to rebuild the world to get SSL? Will it be included in future versions? I'd just like to be able to give my little program to friends and tell them 'Just install python, then it will work'. Maybe I'm wrong or something, please point me in the right direction then! Cheers, Gerald. From shalehperry at attbi.com Tue Jul 30 13:36:14 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 30 Jul 2002 10:36:14 -0700 (PDT) Subject: Python equivalent to 'which'? In-Reply-To: <20020730132124.D7503@eecs.tufts.edu> Message-ID: On 30-Jul-2002 Michael Gilfix wrote: > Seems like that might make a good convenience function in the > os.path module. I'm sure many people have wanted such a function > if they're using python for pure scripting. Perhaps you should try > submitting a short patch...? Worst case, at least it'll get stored in > the system. > I wrote that in about a minute and a half. Note it has a large assumption that PATH is defined and it is separated by colons. This makes it only truly useful on a UNIX box. of course 'which' is a UNIXism as well. My point is, the python library is for the most part OS agnostic so I do not see this fitting in too well. From aleax at aleax.it Sun Jul 7 12:05:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 16:05:58 GMT Subject: newbie-question: more then one constructor in a python-class? References: <3D285A64.6000904@snafu.de> Message-ID: T. Kaufmann wrote: > Hi python-experts, > > is there a way to have more (then one) constructors in a python-class > (like in Java)? No, because the constructor is the one and only method named __init__, and a class can't have more than one method with a given name. However, you can obtain much the same effect with factory idioms. Remember, this is Python, a multi-paradigm language: you don't have to express *everything* as methods of some class or other, but rather you choose such expression only if and when you find it more clear and productive than alternatives. > I mean something like this in Java: > > > public class MyClass { > > public MyClass() { > ... do anything here > } > > public MyClass(String param) { > ... do anything here > } > > public MyClass(String param, StringBuffer param) { I don't think this is legal Java (two parameters with the same name), it's surely not legal Python, so I'll make believe the second one is named param2:-). > ... do anything here > } Most often, here, you would use arguments with default values: class MyClass: def __init__(self, param=None, param2=None): if param is None: assert param2 is None dowhatyoulikewithnoargs(self) elif param2 is None: dowhatyoulikewithonearg(self, param) else: dowhatyoulikewithtwoargs(self, param, param2) For more flexibility, however, in other cases you can arrange that client-code never instantiates the class by calling the class itself directly: rather, it calls factory functions, each of which initializes the instance differently. E.g.: class Feep(object): def __init__(self): raise RuntimeError, "don't build Feep instances directly!" def makeIntFeep(anint): result = Feep.__new__(Feep) result.anint = anint return result def makeStringFeep(astring): result = Feep.__new__(Feep) result.astring = astring return result x = makeIntFeep(23) print x.anint y = makeStringFeep('twenty-three') print y.astring etc, etc. This needs Python 2.2 (for the __new__ call) -- you can get the same effect in Python 2.1 but it needs a more roundabout approach, and there's really no reason to do things the 2.1 way -- 2.2 is better and gives you substantial advantages. It's very rare for the factory idioms to be actually required, but when you DO need total flexibility, factories of various kinds really let you have it (build objects of different types according to the supplied arguments, etc, etc) in ways that calling classes directly can never fully match. So, it's a good design pattern to have up your sleeve for those very rare cases in which you need it. Alex From logiplexsoftware at earthlink.net Wed Jul 3 14:19:19 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 11:19:19 -0700 Subject: GoTo considered missing In-Reply-To: <3D233D8C.2030104@onsitetech.com> References: <3D233D8C.2030104@onsitetech.com> Message-ID: <20020703111919.5c4c0e94.logiplexsoftware@earthlink.net> On 03 Jul 2002 18:09:14 GMT Robb Shecter wrote: > David LeBlanc wrote: > >...if you're writing python > > code that uses nested loops like that, it's possible you're not taking good > > advantage of Python's features. Care to share what you're working on?... > > I'd like to know too. I can't really think of an example where I'd need > a goto statement. Not in a program written from scratch, but the OP apparently is trying to port a C program line-for-line to Python (not the best approach, IMHO). Then again, I've never used a goto in C either... -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From loewis at informatik.hu-berlin.de Tue Jul 30 06:31:52 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2002 12:31:52 +0200 Subject: python 2.1.3 with tkinter support on Solaris 9 References: Message-ID: Marc Petitmermet writes: > I still cannot compile python 2.1.3 with tkinter support on Solaris 9. I > have configured the environmental paths LD_LIBRARY_PATH, LD_RUN_PATH, > the Modules/Setup file and even adjusted the /var/ld/ld.config with crle > to include the libraries of tcl and tk libraries. Maybe you have overdone that; please chose *one* of the strategies, not all of them. Just using LD_LIBRARY_PATH should be enough. What value are you using for that? > The problem ist that setup.py still complains that it cannot find > libtk8.3.so although the it is located in /p1/local/tcltk/tk-8.3.4 > as configure Modules/Setup (see below). Can anybody tell me what I'm > doing wrong? Since you did not tell us what you did (precisely), it is hard to tell what you did wrong. Perhaps you don't have a file named libtk8.3.so on your system, perhaps you can't execute it, perhaps it isn't the Tk shared library? Many things can have gone wrong. Regards, Martin From whisper at oz.net Mon Jul 29 22:02:27 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 29 Jul 2002 19:02:27 -0700 Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 In-Reply-To: <3D45E665.3C34CDF@alcyone.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Erik Max Francis > Sent: Monday, July 29, 2002 18:06 > To: python-list at python.org > Subject: Re: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 > > > Steve Drake wrote: > > > >>> xmlText=""" > > > > > > Text > > ^ > > """ > > Looks like a typo to me. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ Not to mention that a tag can't contain itself. It's not valid and may not be well-formed. Dave LeBlanc Seattle, WA USA From cliechti at gmx.net Fri Jul 26 19:47:21 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jul 2002 01:47:21 +0200 Subject: Slow program exit on Dec Alpha 4.1 OSF References: Message-ID: renez at lightcon.xs4all.nl wrote in news:ahsfsk$36a$1 at news1.xs4all.nl: > I'm trying to collect information from a cvs repository. > Basically I visit every RCS file in the repository > get tags:version with line=file.readline > and build up the following dictionaries > > File[FileId] = name > FileIndex[name] = (FileId , (branchetag (Bole, Bole)) ) > tag[name] = (tagid,counter) > tagindex[tagid] = name > filetag[FileId, tagid] = version > tagfile[tagid, FileId] = version do you store a reference to the file object in one of those variables? do you close the files after visiting them? ... > I cannot make head or tails out of this and probably most > of you also not out of this message ;-( too. maybe you could post some of the code or put it on a webpage, so that people can comment on it. chris -- Chris From mcfletch at rogers.com Wed Jul 24 12:28:49 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 24 Jul 2002 12:28:49 -0400 Subject: visual basic 6 References: <001301c23301$9fe3b740$0c00a8c0@Sanchez> Message-ID: <3D3ED5C1.8050900@rogers.com> Hi Nicholas, The Python web-site has a section devoted to new users of Python, which tries to point out useful documentation: http://www.python.org/doc/Newbies.html note that Python also comes with a tutorial geared for people already comfortable with computer programming. As for getting your development environment set up: Your best bet, given that you're likely on Windows at home, is to get the ActiveState Python distribution, which includes the PythonWin IDE. That's a fairly simple and reliable editor which is about as close to VB's text editor as I've seen for Python (it doesn't have a dialog editor, unfortunately, but to learn Python you'll likely be doing non-graphical things for a while). http://aspn.activestate.com/ASPN/Downloads/ActivePython/install_22 you'll probably want to start with Python 2.2 (see the right side of that page). If you've already downloaded "python.org"'s Python, you can just download PythonWin (and some other stuff, called win32all) at this page: http://starship.python.net/crew/mhammond/win32/Downloads.html make sure you get the release for the Python version you downloaded (i.e. 1.5.2, 2.0, 2.1 or 2.2). Hope this helps, Mike Nick wrote: > Hi my name is Nicholas and I am using visual basic 6 at school but I am > have difficulty with understanding what my teachers is trying explaining > and I was wondering if you had any information like a beginners guides > that could help me. > > > Thanks > Nicholas > Mclean nmclean at evokeit.com.au > _______________________________________ Mike C. Fletcher Why, yes, I am looking for a job... http://members.rogers.com/mcfletch/ From fredrik at pythonware.com Thu Jul 18 17:14:09 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Jul 2002 21:14:09 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: Christopher Browne wrote: > Python programmers should only feel guilty if they don't know > something about analagous things like TPG or YAPP or such. grow up, will you. From maxm at mxm.dk Wed Jul 24 04:56:45 2002 From: maxm at mxm.dk (Max M) Date: Wed, 24 Jul 2002 10:56:45 +0200 Subject: Python + Win32ALL + ASP = Problems accessing Request/Response/Session/Application objects References: <_ko%8.247434$iB1.13124073@bin4.nnrp.aus1.giganews.com> Message-ID: <3D3E6BCD.4010809@mxm.dk> Joe Salmeri wrote: > How are the ASP Request/Response/Session/Application objects accessed in a > module that is imported in an ASP file WITHOUT passing them in as paramaters > to each of the functions defined in that module? I have attempted to track > down the creation of those objects but have been unable to trace them to the > source of their creation. You would probably be better of in the long run if you used a facade to cover your code in. You would then only output finished html from the facade object. <% class PageFacade: def __init__(self, message='blah blah'): self.message = message def blah(self): return self.message def update(self, req): self.message = req.Form('message') # 'insert message into theTable ' f = PageFacade() save = Request.Form('save') if save: f.update(Request) %> here is some code that reads <%= f.blah()%> This has a lot of advantages. Especially if you are writing database driven websites. regards Max M From jdavis at empires.org Fri Jul 26 18:05:39 2002 From: jdavis at empires.org (Jeff Davis) Date: Fri, 26 Jul 2002 22:05:39 GMT Subject: performance problem in python 2.2 References: <7xznweurom.fsf@ruckus.brouhaha.com> Message-ID: Thanks very much for yor reply, now the python one works much better. However, there is still quite a discrepency between python and perl. Of course C is fastest. I listed the times of execution below. I feel much better about python now. Thanks again, Jeff =============c==================== jdavis at jeff:~/code/c$ time ./crunch 0.000271013814962212042265765621351647496339865028858184814453125000000000000 real 0m32.915s user 0m32.310s sys 0m0.030s =============perl================== jdavis at jeff:~$ time code/pl/crunch.pl 100000000 0.000271014079116894 real 2m12.835s user 2m8.400s sys 0m0.110s =============python================= jdavis at jeff:~$ time code/py/crunch.py 100000000 0.000271014073697 real 13m19.242s user 12m53.200s sys 0m2.420s Paul Rubin wrote: > Jeff Davis writes: >> c = long(sys.argv[1],10) >> >> for i in range(1,c): >> n = (n * (p-i)) / p >> print 1-n > > The problem is range(1,c) builds up a c-element list in memory. Use > xrange instead, which makes an object holding only the current > iteration value. > > For extra credit, solve the problem without a computer. E.g., suppose > you want to know the sum 1+2+3+...+999+1000. You can add it up with a > program or you can do it without a computer with a little cleverness. > > Solving your birthday paradox problem needs a little bit more math > than 1+2+3+...+1000, and the answer you get will be a close > approximation rather than exact, but with similar cleverness you > should be able to get a fairly simple formula. From mail at fredriks.org Thu Jul 25 22:38:00 2002 From: mail at fredriks.org (Fredrik Stenberg) Date: Fri, 26 Jul 2002 04:38:00 +0200 Subject: new module and class/type unification. Message-ID: Morning.. its 04:26 localtime so my intellect is not on top. Anyway.. I'm playing with the class/type unification and i don't understand why the following code doesn't work (2.2) import new new.instance(str,None) Traceback (most recent call last): File "", line 1, in ? TypeError: instance() argument 1 must be class, not type Is this is a bug? or am i missing the big picture in type/class unification and the new-module? /fredriks alias princeps... From pde at cs.mu.oz.au Mon Jul 1 05:13:43 2002 From: pde at cs.mu.oz.au (Peter Eckersley) Date: Mon, 1 Jul 2002 19:13:43 +1000 Subject: Partial Parsing of Python In-Reply-To: <20020701104513.E10625@prim.han.de> References: <20020629141507.GA6507@luminance.reworld.org> <20020630094833.B20310@prim.han.de> <20020701060124.GA9937@luminance.reworld.org> <20020701104513.E10625@prim.han.de> Message-ID: <20020701091343.GA31356@luminance.reworld.org> > But you certainly know that this isn't generally possible? Take > > somestrangefile.read(). > > for example. The next best bet (read: hack) is to fork off a process > which does the evaluation of an Subexpression. This way you'd catch > 90% of in-place modifications. Doesn't work for files. But then how > often are you doing dynamic network/file communication on the commandline? I think this case is really important if you're implementing a command shell; it may be less important if the progarm is only used as a coding environment. Lots of shell programs will do things like open("filename").read().find("blah") -- with lots of nice shorthand, of course :) > This might change once we have multiline editing. But one after three > others :-) -- Peter Eckersley Department of Computer Science & mailto:pde at cs.mu.oz.au IP Research Institute of Australia http://www.cs.mu.oz.au/~pde The University of Melbourne From pecora at anvil.nrl.navy.mil Fri Jul 19 10:21:13 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Fri, 19 Jul 2002 10:21:13 -0400 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <3D374109.1040202@mxm.dk> <3D3743A1.911F9687@alcyone.com> <3D37B6E2.1010403@mxm.dk> Message-ID: <190720021021133232%pecora@anvil.nrl.navy.mil> In article <3D37B6E2.1010403 at mxm.dk>, Max M wrote: > I forgot to add self as the prameter. So my example should have looked like: I do that a lot, too. Sometimes I get pissed at myself sometimes I get pissed at self. (Zen, again) But (and I love this about Python) the interpreter gracefully stops and says it doesn't recogize variables or functions (since the "self" is missing). I correct and in 10 sec am on my way again. -- Lou Pecora - My views are my own. From brian at sweetapp.com Mon Jul 8 14:13:05 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 8 Jul 2002 11:13:05 -0700 Subject: Why self? In-Reply-To: <3D29CE9D.4000802@onsitetech.com> Message-ID: <000b01c226ab$1b67b640$bd5d4540@Dell2> Robb wrote: > I completely agree, but I think the situation's even worse than you > described: A'typical' case of standard OO programming is made the most > tedious to write: References to instance variables from methods: > > self.__velocity = self.__factor1 * self.__factor2 > > etc. I find this totally unreadable (7 extra characters per referenced > instance variable). Two of those characters are your own fault (the underscores). I find this very readable (except for the names "factor1" and "factor2"): self.velocity = self.factor1 * self.factor2 Cheers, Brian From jdhunter at nitace.bsd.uchicago.edu Thu Jul 18 14:20:51 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 18 Jul 2002 13:20:51 -0500 Subject: How to set tempfile.tmpdir? References: Message-ID: >>>>> "Andres" == Andres Corrada-Emmanuel writes: Andres> Hi, I'm trying to use tempfile to generate a temporary Andres> filename in the directory of my chossing. I thought that Andres> this would work: You can set the environment variable TMPDIR John Hunter From whisper at oz.net Fri Jul 26 00:08:09 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 25 Jul 2002 21:08:09 -0700 Subject: PyXPCOM and SVG In-Reply-To: <3D40C815.7000605@skippinet.com.au> Message-ID: Are you overlooking the Mozilla active-x control - or is that gecko only? David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Mark Hammond > Sent: Thursday, July 25, 2002 20:55 > To: python-list at python.org > Subject: Re: PyXPCOM and SVG > > > Johann H?chtl wrote: > > > Well XUL is of course not my primer as i can always use the wxwindows > > widgets. But I thought about the ability to "remote control" mozilla > > (maybe gecko and the upcoming SVG features) and therefore I > need xpcom, or? > > There is currently no technique to remote control Mozilla. xpcom is > inprocess only. There is a bug to add some kind of RPC to xpcom, but I > don't think it is really being worked on. It should be possible to do > what you want via embedding though. > > Mark. > > -- > http://mail.python.org/mailman/listinfo/python-list From see_reply_address at something.invalid Wed Jul 10 00:37:26 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 10 Jul 2002 16:37:26 +1200 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> Message-ID: <3D2BBA06.4040808@something.invalid> Graham Fawcett wrote: > I suppose that one could add a distutils.command.pyrexc as a > subcommand of "build_ext" to handle the .pyx compilation. That way the > os.system() call in the build script could be avoided. I've never > written a distutils command, but perhaps I'll give that a try. I've been too busy fixing bugs to look into this myself, but that definitely seems to be the way to go. If anyone wants to have a go and contribute the result, it'll be much appreciated! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From ark at research.att.com Mon Jul 29 18:35:31 2002 From: ark at research.att.com (Andrew Koenig) Date: Mon, 29 Jul 2002 22:35:31 GMT Subject: pretty basic: get variable name from list of strings? References: Message-ID: chris> in the specific, chris> if I have a list chris> animals = ['horse_0', 'horse_1'] chris> horsenames = ['smokey', 'silver'] chris> how do assign variables with those strings as names? chris> ie, I want chris> horse_0 = "smokey" chris> horse_1= "silver" chris> but if I write animals[0] = "smokey", it replaces the value, it chris> doesn't assign it. What I want is like assign() or eval() in other chris> languages. chris> you can imagine i am trying to iterate over large indexes of chris> animals[i] = 'horse_' + str(i) chris> and then assign them from a value list The first question to answer is why you want to have a whole bunch of variable names instead of using a dict. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From jason at mastaler.com Wed Jul 17 22:33:24 2002 From: jason at mastaler.com (Jason R. Mastaler) Date: Wed, 17 Jul 2002 20:33:24 -0600 Subject: asyncore: limiting number of simultaneous connections? Message-ID: I'm building a server based on asynchat/asyncore. The documentation for these modules is sketchy at best, and I couldn't find an answer to this after browsing through the code. Is there an easy way to limit the number of simultaneous connections to such a server? My preliminary tests indicate that it will happily accept as many connections as the host system will allow, which is not good. I'd like to be able to specify a ceiling on this. -- (http://tmda.net/) From fakeaddress at nowhere.org Sun Jul 7 20:08:44 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 08 Jul 2002 00:08:44 GMT Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> <3d28bdb0.71631360@news.dsl.pipex.com> Message-ID: <3D28D80D.1010706@nowhere.org> Simon Foster wrote: | I see it, but I don't see why? What is the explanation for this? It | seems at odds with the documentation. You are right. The doc indicates the following should produce the same output: >>> print " hello there ".split() ['hello', 'there'] >>> print " hello there ".split(" ") ['', 'hello', 'there', ''] It looks like string.split() with no seperator does a string.strip() first. If that's not what you want, there's also re.split (with the string and separator args in the reverse order from string.split). To get a true split on whitespace: >>> import re >>> re.split(r"\s+", " hello \n\n\t there ") ['', 'hello', 'there', ''] --Bryan From gerhard.haering at gmx.de Tue Jul 9 06:48:11 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 12:48:11 +0200 Subject: pythoncom from jython In-Reply-To: <46585325.0207090228.7b5fc9e2@posting.google.com> References: <46585325.0207080040.1ac2fffd@posting.google.com> <46585325.0207090228.7b5fc9e2@posting.google.com> Message-ID: <20020709104811.GD1792@lilith.my-fqdn.de> * Daniel Pi?ol Laserna [2002-07-09 03:28 -0700]: > Gerhard H?ring wrote in message news:... > > * Daniel Pi?ol Laserna [2002-07-08 01:40 -0700]: > > > Is it possible to use pythoncom from jython? > > > > No. > > > > > Ideally, I'd like to build a com component in python (this works with > > > win32 extensions), and from there make calls to java classes (this > > > need jython). > > > > Do you really need to combine COM and Java? Use a COM <-> Java bridge, > > then. Googling with the keywords "java com bridge" finds you some > > alternatives. > Yes, but only Jintegra and TIBCO offer the bridge in the direction I > need it: A COM client using a java server. And they're not free. Such is life. There are people who actually want to get paid for having having to work at the C(++)-level with the terribleness of both Java and COM. http://java.sun.com/products/javabeans/software/bridge/ Early Access Program (if you're into Java, do yourself a favour and quickly register there): http://developer.java.sun.com/developer/earlyAccess/j2eecas/download-com-bridge.html They advertise this as a J2EE<->DCOM bridge, but it will likely have a real use, too =:-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From james.kew at btinternet.com Mon Jul 1 17:00:07 2002 From: james.kew at btinternet.com (James Kew) Date: Mon, 1 Jul 2002 22:00:07 +0100 Subject: private References: <3D1DE132.4A890D9D@engcorp.com> Message-ID: "Christopher A. Craig" wrote in message news:mailman.1025554562.6875.python-list at python.org... > "James Kew" writes: > > > Yes, of course one can circumvent private in C++. But for me the main value > > of the public and private specifiers is that they _document_ to the client > > of the class what it should access and what it should not. > > I would think docstrings, comments, and naming conventions sufficient > to provide a method for documenting what a class ought to be accessing. I think that's a journey I'm only just beginning. Is there any good newbie documentation for docstrings? After reading the Tutorial, Library Reference, and most of Dive Into Python as shipped with the ActiveState distribution they're still very much a mystery to me... James From tim at bladerman.com Sat Jul 27 15:15:00 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sat, 27 Jul 2002 19:15:00 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> <_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: Hi Here comes my reply to both Alex Martelli and Terry Reed. First I want to point out that I didn't start this discussion with the intention of discussing features of the language. I have about four months left of the time I intend to spend on the project so everything is not completely worked out yet. The features we are discussing now are just things that I took out of my head in a snap to make examples. Another issue is that I am not a Python master hacker, I have used maybe ten languages over the last couple of years and have only recently picked up Python (and love it ofcourse :-)). I do on the other hand belive I will be quite fluid in Python by christmas. Regarding this CBR mess. The asignment will be a special case, it will be call by value. a=2 b=a b=3 will leave the program in a state where a=2 and b=3 a and b can never point at the same place or at the same object. when it comes to calling functions it will look like this def setTo3(x): x=3 a=2 setTo3(a) this will leave the program with a being 3 This is not the comon way, I know that but I am inclined to say that it is "undoubtley" more intuitive. Remember that this is a language for complete beginners with no programming experience. Ofcourse this is just the simplest case possible and ther vill be issues further down the way but I intend to handle them later. right now I am getting to no the python interpreter, and its interaction with C and the IDE Maybe I have gotten the names wrong imutable/mutable/CBR/CBV etc etc. But my intentions are as outlined above. After I had written this mail actually thought that I had to add this on top: CBR is not a die hard feature that I must have if it gets a whole lot of work to fix it. But I would apreciate anny suggestions on how to make it with a limited amount of work. Alex martelli wrote >Don't confuse *mutating an object* with *reattaching a name to a >different object*. Completely different issues. That I understand but hadn't thought about it. What might be possible now when you point it out like that is that maybe I can use the current Python model untill I come to a return statement in a function. At that time I reattatch the internal object to the pointer/refference/name that I sent in. Clearly neither this is well thought over. I will come there in a month or so. >ones do such intrusions in their callers' namespaces. >From my point of view such intrusions is not a bad thing, this language is for beginners and not for critical aplications. If that is most intuitive and don't come with alot of problems it is also the best. From: "Terry Reedy" > In a real sense, Python does not have variables. It has objects, each > of which has 1 or more named or unnamed references thereunto. Okey this is what I have to work with then and from that modify the interpreter so the novice get the feeling that it works as I outlined above. Maybe I am working against the python modell I dont know that yet but I am confident I will know when the time comes. If that is the case I will either have to rethink my priorities or change Language to work with (change of language ofcourse get less likely the more time gets by and the more code I write). I might even throw in a preprocessor that changes the usercode into python right before it is ran. That ofcourse is not a good solution but I have t in mind. > do *you* think of as variables: objects, references, or names? Actually I couldnt care less, I am happy when I get to know how it is done in Python right now. I will change my mind to whatever is corret for this particular project. In the discussion so far I think I have had objects with one refference to them in mind so far. > x = 2 > ... > y = x > ... (many lines) > x = x*x > # what should now be the value of y? 2 or 4? > # immutability of ints guarantees 2, which is what most people expect It certainly is not what a novice expects. And therby not what will happen in this language. The line > y = x will only cause y to have a copy of the value that x had at the moment. > > When you want to make functions like inc(x) where inc is supposed to > > increase the value of x by one. How is that done in Python? > > You 'mutate' names most easily by rebinding them to a new value with > the binding (assignment) operator '=' as in 'x = x+1', 'x+=1', or even > x=inc(x)'. With work, you could make inc('x') work for global var x > by fiddling with the globals dict (but this cannot be done for local > function vars). Note that in C, you would also have to 'quote' x, > though with the '&' operator, as in inc(&x). That is the way I have to do it in C it works like a charm when you know it but it is not easy to figure out when you havn't programmed before. I don't argue with you here just... rambling actually :-) But what you say about x += 1 is interesting. the easy way to create such a thing (for the interpreter creator) would be to make a function called +=, make it infx and make it look like this. def +=(value, adder): infx' value=value+adder but that ofcourse is not the way it is done since that is not supported in Python. Instead it must be aspecial case of assignment and handled as an asignment by the interpreter instead of "yet another function" This I assume would make the interpreter bigger wich might not be a good thing. Again I am not arguing I am just facing facts and trying to see possibilities for me to solve my problem. Maybe I could make my assignments yet another special case (dont think so but maybe). > If you work with instead of fighting the Python data model, you can > probably do what you want without completely reworking the > interpreter. I will do my best to not fight Python. I am just one person and have a limitet time to finish this so I will not rework the interpreter. Up untill now I have designed the language the novice in the first room and hoe pythonm works in the second. BUt I guess I will have to change a few things to reduce the workload. Maybe this is one of the issues I must rethink. >From Alex Martelli >With your language, you will have to teach separately >two different semantics, one for assignment and a subtly >different ones for argument passing, making it harder for >beginners that a language where just one semantics exists. That is correct. I have to teach them that there is a diffreence betwen asignment and variable passing. The problem is that I think that is verry easy to understand and you dont. I call it a difference of opinoins not right or wrong. There will be two things to explain in both cases. I must explain that by assigning a a to b means that a gets a copy of the value in b You must explain that in a function when you try to asing a value to one of the parameters it won't effect the outside or that it is illegal. Tim Gahnstr?m From pyth at devel.trillke.net Tue Jul 23 04:47:10 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 23 Jul 2002 10:47:10 +0200 Subject: Callable modules? In-Reply-To: <7xr8hwnu3s.fsf@ruckus.brouhaha.com>; from phr-n2002b@NOSPAMnightsong.com.trillke.net on Sun, Jul 21, 2002 at 11:40:23PM -0700 References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: <20020723104710.F10625@prim.han.de> Paul Rubin wrote: > martin at v.loewis.de (Martin v. Loewis) writes: > > You can put a callable object in sys.modules. Module objects > > themselves are not callable. > > Is this documented somewhere? I don't see it in the obvious places. > > > > If there's not a way to do this already, maybe it's a reasonable > > > addition. > > > > Maybe not. Why do you need this? > > Just to not have to say "foo.foo()" or "from foo import foo". > > If the main purpose of the module is to provide one function, I think > it's cleaner to be able to import the module and call the function > without special tricks. Moreover, I often thought about integrating class and module types. I am not primarly concerned about making modules callable, although i might appreciate it. My use case is from somemodule.someclass import filter1 where 'filter1' would reference an unbound class-method. I need this for implementing a class which offers filter functions which can be applied either as obj.filter1(args) or filter1(obj, args) Of course, you can express the latter via someclass.filter1(obj, args) but i want to have filter1 (and 41 other filter methods) potentially directly in the namespace. I *know* that i can write filter1=someclass.filter1 filter2=someclass.filter2 ... but it's redundant and you have to repeat this scheme whereever you use 'somemodule'. That's ugly where in fact i just want to say from somemodule.filters import filter1,filter2, filter37 and someclass could inherit from 'filters', thus providing both invocation methods. I know that i can *hack* this to work by - doing new.module('somemodule.filters') in somemodule and adding the modules functions at runtime to someclass. - making up a package (with filters beeing in a different file) and adding the modules functions at runtime to someclass - some variant of this schema but actually, doing the above 'from ....someclass import filter1,...' seems much more expressive and doesn't involve any run-time hacks. I hope i made my point clear enough. Basically i'd like to generalize the namespace-injection methods 'import' and 'from'. This might involves extending the Module-type to work more like a "usual" class with __getattr__ and such. Probabally it only involves extending the import machinery. Unfortunately, i haven't found time to investigate the matter but maybe someone can point out that it's the path to all evil (read: wrong concept), anyway :-) slightly?-off-topic-ly yours, holger From mathias.palm at gmx.net Mon Jul 29 04:42:55 2002 From: mathias.palm at gmx.net (mathias palm) Date: Mon, 29 Jul 2002 10:42:55 +0200 Subject: default setting of unicode set Message-ID: <3D45000F.5040300@gmx.net> Hi, I am writing a program which is supposed to be international, meaning it works with different languages. Some languages like German or French use characters not part of the traditional ascii code. This can be circumvented by using unicode strings. It is possible to set a default unicode (set to ascii) in site.py. This is clearly a setting by site. For programs which my use different unicode charackter set it would be useful to have a per user or better still a per program setting. I did not find any possiblity to do this. The function, sys.setdefaultencoding() which sets the default unicode is even deleted in site.py. I found a possibility to do this on linux systems: I run the code with python -C code.py. This inhibits python from loading site.py. Later I import an own site.py with changed default encoding. I think this is not a good way. It is also put out of work to easy. I am sure there is a reason for this behaviour, I cant see it however. Can anybody explain or tell me where to read about it? Why not setting the default unicode in a file like .pythonrc? Is there a possibility to set a unicode default later on? I really dont want the users to get into the system and rewrite parts of python to take care of this problem, it might not even be possible on unix-like os. I also want users to start my program as straight forward as possible. The line #!/usr/bin/python -C (see above)is not a solution because it is to be circumvented to easily by say .. Thanks Mathias From aleax at aleax.it Sat Jul 6 16:56:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Jul 2002 20:56:58 GMT Subject: Understanding properties References: Message-ID: merman wrote: ... >> default a class is a "classic" one, implementing exactly the >> same semantics as in Python 2.1 and older, ensuring no major code >> breakage in porting from 2.1 to 2.2 but constraining the applicability >> of the new features to classic classes. > > Thanks Alex. > > The last part of your description is a little bit unclear for me - I'm a > newbie. > Perhaps I will understand it in one year ;-). And perhaps in a year classic classes will have little more than historical interest. So, I only left the last part, and I now try to clarify it. If it's still "a little bit unclear" for you, maybe you can at least tell me WHICH parts are unclear, so I enumerate things in reasonably small bytes in the following. In Python 2.2, there are two kinds of classes: classic and new-style. In Python 2.1, there was only one kind, equivalent to today's classic. The reason for continued existence of classic classes in Python 2.2 is backwards compatibility. Backwards compatibility means your existing code doesn't break just because you upgrade your Python to a new release. Python cares about backwards compatibility. There's a lot of Python code out there, not a little of it in applications that are crucial to the firms deploying them. For backwards compatibility, a class for which you don't say whether it's classic or new-style must be classic in Python 2.2. For backwards compatibility, a classic class in Python 2.2 must behave much as it did in 2.1. A program construct's "behavior" is also more specifically and precisely called its "semantics". The semantics of classic classes can't fully support properties without breaking backwards compatibility. Therefore, to use properties fully, in Python 2.2., you must ensure your classes are new-style. There are several ways to require that a class be new-style. If in the class body is the binding (assignment) statement: __metaclass__ = type the class is new-style. Otherwise, if the class inherit from a new-style class, it's also new-style. object, and all inheritable built-ins such as list, dict, etc, are new-style. A class without bases and without a __metaclass_ binding in the class body is new-style if, and only if, a __metaclass__ global variable is defined in the module when the class statement is executed, and its value is type. Inheriting from object is the simple and most common way to make a class new-style, though, as we've just seen, it's far from being the only one. OK -- that's a lot of stuff, so I'd better stop now. It is, I hope, at least clearer? Not quite sure why a beginner would worry about the last little detail of WHY a certain language construct is necessary (most beginners I've known just accept it as an article of faith, for most constructs), but clearly you do, since you've already posted more than once about this subject, and I hope the above does help. Alex From dsavitsk at e-coli.net Mon Jul 29 17:29:19 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 29 Jul 2002 21:29:19 GMT Subject: Win32 API question - Postmessage and Win2K lock window References: <4d3df955.0207291235.1a8916b@posting.google.com> Message-ID: I have found, I think, that when a service runs as a particular user, any applications launched by the service also run as that user. I use this so that when a service launches Word it uses my Normal.dot file. setting up a service to run as you to launch the defrag utility might work. of course, you can just use the scheduler to launch defrag... if you do need to send key strokes, you might try using PC Anywhere or its kin. "Mark Erikson" wrote in message news:4d3df955.0207291235.1a8916b at posting.google.com... > Hey, folks. I've got a problem regarding the PyCwnd.PostMessage() > function behind the Windows 2000 lock window. I know this is more of > an API question than a Python question, but figured it was worth > asking here just in case. > > Basics of the issue: > I'm trying to automatically launch the Windows 2000 Defrag utility. > While any user can launch it, the defrag function can only be > activated by an administrator. By getting the window handle and > creating a PyCwnd from the handle, I can do PostMessage() to the > window and send WM_KEYUP and WM_KEYDOWN messages. When run as an > administrator, I can successfully simulate the keystrokes needed to > start the defragmentation. However, this needs to be run on other > users computers, most likely during lunch. So, I've been working with > Win2K's "runas" utility. It requires that a password actually be > typed in, though no input is visible. Again, I can use PostMessage to > send simulated keystrokes to the Command Prompt window, runas > completes successfully, Defrag launches, and everybody's happy. The > problem comes when I try to deal with people using the CTRL-ALT-DEL > "Lock Window" function, which absorbs any standard keyboard input > (which is why I'm using WM_KEYUP/DOWN instead of a more standard > SendKeys type deal). If I'm just running Defrag, I can still > successfully use PostMessage() and activate it. *IF*, on the other > hand, I launch Runas behind the lock window, *I cannot send the > keystrokes*. > > I've looked at everything from using pipes to replace stdin to using > other Runas-type utilities (SU, sfImpersonator, etc) to using > WriteConsole() to too much other stuff to remember. Nothing I've > experimented with has seemed to work. > > So... does anyone have any ideas? I just need to be able to simulate > keystrokes for a password to a Command Prompt window for which I have > a handle, BEHIND the Win2K lock window. I'm open to any suggestions, > including stuff that I've looked at already (since it's quite possible > I missed something). > > Thanks in advance! > > Mark Erikson > > markulus00 'at' yahoo 'dot' com From cliechti at gmx.net Fri Jul 26 08:19:47 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jul 2002 14:19:47 +0200 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> <3D3EFC18.30705@ntlworld.nospam.com> <3D412292.1030608@ntlworld.nospam.com> <3D413883.4000004@ntlworld.nospam.com> Message-ID: "Keith S." wrote in news:3D413883.4000004 at ntlworld.nospam.com: > Chris Liechti wrote: > >> just return some real data, "print 'hello'\n" or so. >> and i think you can exit the interactive loop by raising an EOFError >> exception. > > Unfortunately returning any real data still loops. > I guess interact is not what I'm looking for, then. yes code.interact stays in the interactive loop until a sys.exit() of EOFError. > I want a C function (that is a Qt slot which responds > to a signal that the user has hit return in a QLineEdit > widget) to send a string to the Python interpreter > in much the same way as the interactive shell does, > with the interpreter waiting for more input if required. have a look at the python source of code.py and pycrust maybe idle and pythonwin too. the trick is to compile the input after each line and look if there is an error and on some errors, just continue to read. chris -- Chris From huaiyu at gauss.almadan.ibm.com Tue Jul 23 12:52:19 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 23 Jul 2002 16:52:19 +0000 (UTC) Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> Message-ID: Peter Hansen wrote: >Paul Rubin wrote: >> I've written several, there are several in the Python library, and >> remember that it's not necessary for the module to have a single >> function for a __call__ interface to be useful. __call__ makes sense >> if there's a most-important or most-frequently-used function in the >> module. It's ok if there are other functions too. > >Although you can do as you wish, of course, I want to chime in >with a "this is a really bad idea" and hope you don't follow through >on it. This is, even in the best case, going to make your code >less readable to anyone else. It is also likely to cause maintainability >problems because making the claim "but this module has only one function!" >almost certainly means it will not stay that way forever. Why is this so? Modules appear to be just singletons associated with files. Why making them more similar to other objects would make programs less readable? Maybe some examples of usage would help to clarify the issues. As a counterexample, I've been confused many times by 'from foo import foo', not knowing which foo is which. Huaiyu From h_schneider at marketmix.com Wed Jul 31 12:38:59 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Wed, 31 Jul 2002 18:38:59 +0200 Subject: win9x or WinNT References: <3D480EA9.9020807@thomas-guettler.de> Message-ID: import os if os.environ['os'] <> 'Windows_NT': migrate_to_linux = true Bye, Harald "Thomas Guettler" schrieb im Newsbeitrag news:3D480EA9.9020807 at thomas-guettler.de... > Hi! > > How can a python programm know if it > runs on win9x or on WinNT? > > sys.platform always returns win32. > > I need to handle some stuff different > if I am on win9x. > > thomas > From ianb at colorstudy.com Tue Jul 30 18:10:19 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 30 Jul 2002 17:10:19 -0500 Subject: A generic question: idiom for a paramterized base class? In-Reply-To: <3D47042E.33823879@irl.cri.nz> References: <3D47042E.33823879@irl.cri.nz> Message-ID: <1028067021.578.988.camel@lothlorien.colorstudy.net> On Tue, 2002-07-30 at 16:25, Blair Hall wrote: > ############ example.py ########### > class GenericBase(object): > def __iadd__(self,other): > return TAdd(self,other) # Problem!! > def __add__(self,r): > return GenericBase.__iadd__(self,r) > def __radd__(self,l): > return GenericBase.__iadd__(l,self) > > # One type of TAdd: > class TAdd(object,GenericBase): > def __init__(self,l,r): > print "TAdd instance" > > class TNode(object,GenericBase): > def __init__(self): > print "TNode instance" > ############################ > > >>> import example > >>> x = example.TNode() > TNode instance > >>> y = example.TNode() > TNode instance > >>> t = x + y > TAdd instance > > However, the first class, GenericBase, is actually one that I need to > reuse in a number > of different situations, each with different TAdd definitions! I'm unclear about what you want to do with this... but maybe something like this would work: class GenericBase(object): def __init__(self, addClass): self._addClass = addClass def __iadd__(self, other): return self._addClass(self, other) class GenericBaseBuilder: def __init__(self, addClass): self._addClass = addClass def __call__(self): return GenericBase(self._addClass) # then in example.py: class TAdd: pass GenericBase = GenericBaseBuilder(TAdd) That might do what you want. To me, though, the whole thing seems vague and maybe there's another approach that avoids some of these complexities. Cheers, Ian From smst at bigfoot.com Thu Jul 4 05:42:05 2002 From: smst at bigfoot.com (Steve Tregidgo) Date: 4 Jul 2002 02:42:05 -0700 Subject: How to represent the infinite ? References: <3d11ee9b$1@news.swissonline.ch> Message-ID: Cliff Wells wrote in message news:... > from __future__ import generators > > class Infinity(int): > def __init__(self): > int.__init__(self) > self.sign = 1 > > def __str__(self): > return "%sInfinity" % {-1: "-", 1: ""}[self.sign] > > def __repr__(self): > return "<%s>" % self [followed by many other good things] Nice implementation. May I suggest two small changes: def __init__(self, sign=1): int.__init__(self) self.sign = sign def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.sign) It's partially tested (my version of Python doesn't have generators... I really should get with the times); the point is that, assuming Infinity is available in the calling namespace, this will work: Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> from some_module import Infinity >>> i = Infinity() >>> repr(i) 'Infinity(1)' >>> j = eval(repr(i)) >>> j == i 1 >>> k = -eval(repr(i)) >>> k + i 0 >>> ^Z Quoting from the Python reference manual (section 3.3.1): > If at all possible, this should look like a valid Python expression > that could be used to recreate an object with the same value (given > an appropriate environment). I'd be interested to hear if these minor modifications work with the class proper; I had to remove the generator/yield lines, and the subclassing from int, to get it to run under 1.5.2 :-) Anyway, as I said: I like the class. just-wanted-to-join-in-ly y'rs, Steve -- Steve Tregidgo From aleax at aleax.it Mon Jul 8 09:03:40 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 13:03:40 GMT Subject: Memory ? References: Message-ID: Shagshag13 wrote: > > "Alex Martelli" > >> > That i can' t guess the size of my arrays (range from 0 to ???) >> >> Both the array.array type, and the vastly more powerful Numeric.array >> type from the Numeric extension package, are arrays that can grow and >> shrink. > > sorry to bother, i didn't find a way to append a numeric.array, should i > do this by using "concatenate" ? or do i miss the "correct efficient" way You can change an array's shape, including its size (product of all the items in the shape couple), by calling the resize method on the array -- but that's available only if there is no data-sharing between that array and any other. Don't be misled by the docstring of the resize method, which says the method "returns" the resized array -- it doesn't, it returns None, and it resizes the array in-place, filling it with default values if it grows. A typical example: >>> x = Numeric.array([0.5]*7) >>> y = Numeric.array([0.3]*7) >>> z = x * y >>> z.resize((10,)) >>> z array([ 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0. , 0. , 0. ]) >>> However, calling the resize _method_ raises an exception if the array is sharing data with any other array -- and, sometimes, just because Numeric can't be absolutely certain that such sharing is not taking place, and in doubt it chooses to guarantee correct semantics. Function Numeric.resize(somearray, newshape) returns a new copy (filling by replication, rather than by defaults) and thus is free from any such constraints. Function Numeric.concatenate, which you mention, also returns a new copy, and thus is similarly free from any worry. Of course, copying data can give performance problems if you have millions of items involved. However, don't think that the builtin Python lists would be necessarily free from such problems! A list typically overallocates so it has some free space available right at the end -- so it doesn't have to reallocate all the time if you just need to append a few items -- but that extra space is, of course, a bounded amount... it can't last forever:-). As you keep appending, you'll get (implicit) reallocations. lists can do those implicitly because they never allow data sharing between different list objects, of course. There are several strategies that can serve you well when you need to put together a potentially large array from an a-priori unknown number of smaller arrays. If feasible, collecting all the smaller arrays into a sequence (e.g. a list) and then joining (e.g. with Numeric.concatenate) only at the end, tends to be the best-performing way quite often. If you know a reasonable upper bound, you can overallocate yourself, and then you may be able to exploit Numeric.array's ability to share data among arrays to refer to sub-arrays, such as the one "built by the concatenations so far", quite cheaply. To clarify the latter strategy, an example: >>> large = Numeric.array(' '*1000) >>> sofar = large[0:0] >>> word='ciao'; large[len(sofar):len(sofar)+len(word)] = Numeric.array(word) >>> sofar = large[:len(sofar)+len(word)] >>> sofar array([c, i, a, o],'c') >>> word='zurp'; large[len(sofar):len(sofar)+len(word)] = Numeric.array(word) >>> sofar = large[:len(sofar)+len(word)] >>> sofar array([c, i, a, o, z, u, r, p],'c') >>> It's obviously quite easy to wrap up these idioms into a small utility class, if such "concatenations with frequent need for access to all the data concatenated up to now" are a recurring need in your code. Wrapping it up as a class is quite advisable because it lets you most easily experiment with drastically different strategies while letting all the client-code (your code that _uses_ this class) perfectly unchanged -- you can fix the interface, develop all the rest of your application based on whatever simple implementation of that interface first comes to mind, THEN go wild experimenting with alternative implementation strategies and time the results based on actual usage in your application (or some typical benchmark runs for it). Python is just great for this general approach at implementing applications and the primitives that the applications rely upon. Of course, once you do wrap it up as a class you can also deal with other issues, such as "what happens when one of my appends overflow the large-buffer so far allocated" (catch the error and reallocate a larger buffer -- scale buffer size up exponentially if you need to have constant amortized cost per appended item...), etc. Alex From rjones at ekit-inc.com Tue Jul 2 23:35:41 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Wed, 3 Jul 2002 13:35:41 +1000 Subject: Comments in pickles? In-Reply-To: References: Message-ID: <200207031335.41102.rjones@ekit-inc.com> On Wed, 3 Jul 2002 1:23 pm, Roy Smith wrote: > Tim Peters wrote: > >> Our usual practice is to imbed the CVS id string ($Id: ) in every > >> checked-in file as a comment. > > > > I encourage you to question that practice. > > This is getting a little off-topic, but why do you say that? It's the > most convenient way I know of to identify a file when you're looking at > it. Later in his reponse, Tim encourages you to store the information in something that isn't just turfed during parsing: a string. A good place to store that is in a string called "version" at the module toplevel. Another is just in the module docstring, if you don't need to access the version directly. Richard From theller at python.net Fri Jul 5 10:05:32 2002 From: theller at python.net (Thomas Heller) Date: Fri, 5 Jul 2002 16:05:32 +0200 Subject: metaclass & __slots__ References: Message-ID: "Holden Caulfield" wrote in message news:c2595393.0207050552.e5fd6b at posting.google.com... > Alex & John, > Thanks for good explanations and clarifications. This was just an > exercise to hurt my brain, I guess :) > But somehow I feel the addition of the "new" style classes and the > "automatic" call of "__new__" and "__init__" is really confusing. The > "__init__" seems redundant, since we actually have a true > "constructor". I guess, what I am trying to say is, with the scarce > documentation (and if you are lazy to browse through the source) it > seems like you need to know the distinction on what to override > (__new__ or __init__) for a class derived from a builtin. > There is quite some information about __new__ and __init__: http://www.python.org/2.2.1/descrintro.html#__new__ Thomas From sholden at holdenweb.com Fri Jul 26 10:13:49 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 26 Jul 2002 10:13:49 -0400 Subject: redirect to > and to console ? References: Message-ID: "Tim Hammerquist" wrote in message news:slrnak298k.e04.tim at vegeta.ath.cx... > Gerhard Haering graced us by uttering: > > "Shagshag13" wrote: > >> i use many python script like that : > >> ./myscript.py file_in > file_out > >> > >> i wish i would sometimes like to force output to be redirect to > >> console instead of file file_out, is there any way of doing that? > >> (for example to display errors message while file_in will contain > >> only data processed) [...] > > > > Unix and Windows consoles have two different output streams: the > > standard output one and the error stream. > > > > Standard output is accessible from Python as sys.stdout, the error > > stream as sys.stderr. > > > > To write to the error stream, either one of > > > > sys.stderr.write("foobar\n") > > > > and > > > > print>> sys.stderr, "foobar" > > One thing that concerns me is how well do the COMMAND.COM/CMD.EXE shells > handle redirection? I know that DOS used to support the standard '>' > redirection, but I don't remember any robust way of handling stderr on > the command line. > > Various *nix (and cygwin, yes) shells can use: > > $ command > file_out 2> file_err > > $ command > file_both 2>&1 > > $ command &> file_both > > ...and I think I heard CMD.EXE had slightly better support, but how does > Win32's native command line stream redirection really compare? > While I can't be definitive about htis (maybe Mark Hammond *could*), one thing it's always worth remebering is that certain Windoze command interpreters will fail to handle prog.py > output.txt when they *will* cirrectly handle python prog.py > output.txt I seem to remember this particular form of brain-death belongs to Windows NT 4.0 (why was there never an NT 4.anything else, I wonder), since "lesser" operating systems didn't even have the ability to associate the ".py" extension with the Ptyhon interpreter. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From aleax at aleax.it Fri Jul 26 08:09:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 12:09:45 GMT Subject: extract elements of n char from a list References: Message-ID: Shagshag13 wrote: > > "Shagshag13" a ?crit dans le message de news: > ahrchl$v4n9l$1 at ID-146704.news.dfncis.de... >> hello, >> >> i want to efficiently extract elements of n char from a list : >> >> n = 2 >> l = ['this', 'is', 'an', 'example'] >> nl = [] >> for i in l: >> if len(i) == n: >> nl.append(i) >> >> nl = ['is', 'an'] >> >> but i think that some clever guru could use a map() / reduce() or >> something like that to speed up the process (which is what i > really need...) > > well, i think that i could use : > > nl = [e for e in l if len(e) ==n] > > but is it efficient ? are they more efficient ways ? and when is it good > pythoner technique to use list comprehensions ? It's good Python technique to use list comprehensions when they're clear, concise, and readable (like here). It's even better Python technique to worry about efficiency LATER. "The root of all evil in programming is premature optimization" (Knuth). It's the best Python technique of all to learn to MEASURE rather than having to ASK. Set up a little benchmark script and use it. THEN you can ask here if the results aren't convincing to you (it's quite possible to get things wrong). Tim Peters' introduction to the Algorithms chapter of "Python Cookbook" (the printed edition that O'Reilly just launched) is invaluable in showing you exactly how to perform such little benchmarks for accuracy and solidity. Alex From maxm at mxm.dk Tue Jul 23 13:20:17 2002 From: maxm at mxm.dk (Max M) Date: Tue, 23 Jul 2002 19:20:17 +0200 Subject: format strings or page tempaltes References: Message-ID: <3D3D9051.5090202@mxm.dk> Jeff Davis wrote: > Is this possible with the string format syntax? If not, could someone > recommend a good template module or something similar? If you are doing OO programming you should know the adapter pattern which is especially usefull for this kind of work. Untested: you have an object: class Person: name = 'Douglas' age = 42 books = 'hhg2tu' and you want to create a view for this class in html. Then you should create an adapter/wrapper for this class that represents it as html: class HtmlViewAdapter: def __init__(self, obj): self._obj = obj def __getattr__(self): return getattr(self._obj) def __getitem__(self, key): itm = getattr(self, key) if callable(itm): itm = itm() return itm class PersonHtmlViewAdapter(HtmlViewAdapter): def name(self): return '%s' % self._obj.name def age(self): return '%.2i' % self._obj.age def __str__(self): # this is a neat trick! return 'name: %(name)s, age: %(age)s, books: %(book)s' % self And you can then use it like: person = Person() personHtmlView = PersonHtmlViewAdapter(person) print personHtmlView.name() >>> Douglas print "The Persons name is: %(name)s" % personHtmlView >>> The Persons name is: Douglas print 'famous book %(book)s' % personHtmlView >>> famous book hhg2tu print personHtmlView >>> name: Douglas, age: 42, book: hhg2tu' You can also put all kind of escaping methods into your HtmlViewAdapter, then you can make shure that all of your strings allways are escaped etc. I find that this is a really powerfull way of rendering html, and I don't really see the need for a templating language when using this pattern. regards Max M From phr-n2002b at NOSPAMnightsong.com Fri Jul 19 21:39:46 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 19 Jul 2002 18:39:46 -0700 Subject: text adventure game module for Python References: Message-ID: <7x1y9zmb31.fsf@ruckus.brouhaha.com> "Michael Bauers" writes: > If the user types in "drop rock", the interepreter will return a string like > 'player.drop(rock)' which is then 'exec'd. Note that interperter excepts > any string for object. Oh no! What happens if the user types drop rock);import os;os.system('rm\x20-rf\x20~') Do you exec it? Don't ever use exec on user input unless you really know what you're doing! From b.maryniuk at forbis.lt Tue Jul 9 05:53:15 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 11:53:15 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <3d2aafce$0$94901$e4fe514c@dreader3.news.xs4all.nl> References: <96c7f32.0207081518.52ea644a@posting.google.com> <3d2aafce$0$94901$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <200207091153.15904.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 11:39, Boudewijn Rempt wrote: > Er, yes. Somebody could: there's qtjava. May I ask You for link? I'm just curious: Java + QT + crossplatforming. Hmm... -- Sincerely yours, Bogdan M. Maryniuck In most countries selling harmful things like drugs is punishable. Then howcome people can sell Microsoft software and go unpunished? (By hasku at rost.abo.fi, Hasse Skrifvars) From -$P-W$- at verence.demon.co.uk Sat Jul 20 11:38:54 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 20 Jul 2002 16:38:54 +0100 Subject: text adventure game module for Python References: Message-ID: In article , Michael Bauers wrote: >I wrote a module that reads a file to create a parsing system, and then >provides an interpreter to invoke methods based on matching input against >the sentences in the file. > >e.g.'s > "drop" object, player.drop(obj) > "look", player.loc().look() > "north", player.loc().move_north(player) This sounds very like the system that the MOOP system uses. MOOP is a Python based MUD. From what I remember, it matches commands against methods on objects representing the player and things in the current room. There's not been much development on it lately from what I can see, but you might find it useful. http://moop.sf.net/ -- Paul Wright | http://pobox.com/~pw201 | From fredrik at pythonware.com Thu Jul 25 13:13:25 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Jul 2002 17:13:25 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: Alex Martelli wrote: > > (does anyone here even know that readline takes an optional > > integer argument, and what it does? ;-) > > I would hope so, given that > http://www.python.org/doc/current/lib/bltin-file-objects.html > documents it so clearly. does anyone here think that when I asked that question, I did that because I didn't know, and wanted someone to look it up for me? ;-) From sjoshi at ingr.com Wed Jul 31 09:45:46 2002 From: sjoshi at ingr.com (Sunit Joshi) Date: 31 Jul 2002 06:45:46 -0700 Subject: Good XML tools? References: Message-ID: <8f8ffe67.0207310545.19ba43ea@posting.google.com> I can never seem to get thru. after I key in the password. Their server always returns an errro code. Is there a way you can email me the zip files for parts 1->3 thanks Sunit sjoshi at ingr.com Doru-Catalin Togea wrote in message news:... > > Can you recommend any good XML packages for Python? I looked at the > > PyXML but it seems to be lacking proper documentation (=unusable). > > A short while ago, somebody posted the following links to online tutorials > for pyxml ++. I downloaded them (after a rather bothersome registration > and "type your password many times" procedure) and they seem to be both > acurrate and somewhat comprehensive. I did not read them thoroughly yet. > > > ------------------- > Python and XML development using the open source 4Suite toolkit > > 4Suite is an open source, comprehensive library and toolkit for XML > processing in Python. 4Suite implements various open standards related > to XML. This series of tutorials introduces 4Suite and gives practical > examples of XML development using 4Suite and Python. > > Part 1: PyXml > There are various DOM implementations, in varying computer languages. > Here, we will be introducing PyXml. This particular implementation is > written in Python. > > http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/28BEDEE3E7219EB386256AE300743B69 > ?Open&t=gr,lnxn28,p=PyXml > > > Part 2: 4XPath and 4XSLT > This tutorial introduces 4XPath and 4XSLT . If you plan to use Python > in association with XML processing, these are useful tools to get to > know. > > http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/BE1A7E60838F9F7686256AF400523C58 > ?Open&t=gr,lnxn28,p=4XPath4XSLT > > > Part 3: 4RDF > This tutorial will go into detail on RDF, with hands-on examples of > how to use the various RDF facilities available with Python. > > http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/8A1EA5A2CF4621C386256BBB006F4CEC > ?Open&t=gr,lnxn28,p=4RDF > ------------------- > > Catalin > > > <<<< ================================== >>>> > << We are what we repeatedly do. >> > << Excellence, therefore, is not an act >> > << but a habit. >> > <<<< ================================== >>>> From gerhard.haering at gmx.de Fri Jul 12 12:17:46 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 12 Jul 2002 16:17:46 GMT Subject: newbie question: getting rid of space in string :( References: Message-ID: In article Joseph Youssef wrote: > This is a multi-part message in MIME format. Please configure your news-/mailreader to send text _only_. > [...] > print "<" +color+ ">" +a+ "", > [...] > now this works just fine exept that space in between each block of text, The reason for this is that a print command ending in a comma implicitely adds a space character. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fredrik at pythonware.com Sat Jul 13 08:37:47 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 12:37:47 GMT Subject: switch recipe? References: Message-ID: Mark McEahern > The thread on zip suggests the term "lockstep iteration." I can't use map > or zip though because I have an unbounded iterator. Of course, I could > easily bound that to the length of the finite iterator. zip stops as soon as the first sequence runs out of items: class over_and_over_again: def __init__(self, seq): self.seq = seq self.len = len(seq) def __getitem__(self, index): return self.seq[index % self.len] print zip(range(12), over_and_over_again("spam")) prints [(0, 's'), (1, 'p'), (2, 'a'), (3, 'm'), (4, 's'), (5, 'p'), (6, 'a'), (7, 'm'), (8, 's'), (9, 'p'), (10, 'a'), (11, 'm')] From zildqk at yahoo.com Sat Jul 13 00:43:52 2002 From: zildqk at yahoo.com (zildqk at yahoo.com) Date: Sat, 13 Jul 2002 04:43:52 +0000 (UTC) Subject: Make the most of your PC 9852 Message-ID: http://ebook.best2web.com/ Free Download The Absolute Beginner's Guide to Starting a Web Site Totally Free Web Resources Unlimited Profits 7 Secrets To Unlimited Traffic Scientific Advertising How to Start Your Own Traffic Virus Marketing Warriors Tips eBookoMatic eBook Submitter The Best of Web Gold On Line Stealth Marketing and more http://ebook.best2web.com/ flfefekrlho From marklists at mceahern.com Mon Jul 15 15:31:21 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 15 Jul 2002 14:31:21 -0500 Subject: switch recipe? In-Reply-To: <02071309191001.10164@arthur> Message-ID: [Alex Martelli] > Right. So what about a direct implementation of what you just said? > > def weave(setn, setm): > n = len(setn) > m = len(setm) > if not n or not m: > raise ValueError, "Weaved sets cannot be empty" > yield setn[0], setm[0] > i = 1 > while i%n or i%m: > yield setn[i%n], setm[i%m] > i += 1 I like this. The 'or' in the while statment means this will loop until lcd(n, m)--easily fixed. I modified this slightly: def weave(setn, setm): """Return a generator that iterates over setn and setm until setn is exhausted. If setn is larger than setm, cycle over setm. """ m = len(setm) if not setn or not setm: raise ValueError, "Weaved sets cannot be empty" for i in range(len(setn)): yield setn[i], setm[i%m] This means you have to specify the alternator/cycler second--it doesn't treat the two sets as interchangeable. Slightly less general than the direction your solution points. // m - From remi at cherrypy.org Fri Jul 26 03:02:40 2002 From: remi at cherrypy.org (Remi Delon) Date: 26 Jul 2002 00:02:40 -0700 Subject: ANN: Free CherryPy hosting Message-ID: <585c0de9.0207252302.558a7953@posting.google.com> As of today, FreeCherryPy.org is pleased to offer free CherryPy hosting services. This offer is limited to non-commercial web sites. http://www.freecherrypy.org ------------------------------------------ About CherryPy: CherryPy is a Python-based tool for developing dynamic websites. It uses many powerful concepts together, which makes it unique in its approach to website development. CherryPy sits between an application server and a compiler. You write source files, compile them with CherryPy and CherryPy generates an executable containing everything to run the website (including an HTTP server). CherryPy has been used in production for more than 6 months are we are now releasing it to the public, under the GPL license. Key properties/features of CherryPy are: - Based exclusively on Python (runs everywhere Python runs) - Delivers fast, robust, and scalable websites - Uses OOP as well as AOP (Aspect Oriented Programming) concepts to develop websites - True separation of content and presentation - Simple but powerful templating language - "HTML editor safe" templating language (pages can go back and forth between developers and designers) - Powerful standard libraries to make your life easy Other properties/features are: - Can be linked to many databases (Oracle, Sybase, MySql, PostgreSql, ...) - Can run behind another webserver (Apache, ...) - Easy clustering and load-balancing set up for high-traffic websites Remi. http://www.cherrypy.org From rtaranto at interia.pl Fri Jul 26 11:49:52 2002 From: rtaranto at interia.pl (Roman Tarantowicz) Date: 26 Jul 2002 08:49:52 -0700 Subject: Derivative of string as a name of list or dictionary (or class?) Message-ID: <82fe0bb.0207260749.3059e20a@posting.google.com> I received string1, string2, ... etc from handle_data in MyParser(SGMLParser) I dont know how to create list or dictionary which name be derivative of the received string? I would like to have the following containers: Top_Category = [derivative_of_string1, derivative_of_string2, ...] Derivative _of_string1 = [derivative_of_another_string1, derivative_of_another_string2, ...] Derivative_of_another_string1 = {'id1': 'str1', 'id2' : 'str2', ...} Is this any direct method or I have to apply something complicated as a Factory Pattern (is it possible to automate producing new classes which names will be given during execution of program)? Any tips or direction in which my mind should be pushed I'll embrace wholeheartedly ;) From cja at dqs.nwt Tue Jul 30 18:36:52 2002 From: cja at dqs.nwt (CJ) Date: Tue, 30 Jul 2002 15:36:52 -0700 Subject: wxPython printing help References: Message-ID: iIs this even possible or am I wasting my time? From roger at efn.org Fri Jul 5 15:03:33 2002 From: roger at efn.org (Roger) Date: Fri, 5 Jul 2002 12:03:33 -0700 Subject: shallow copy's In-Reply-To: ; from rajarshi@presidency.com on Fri, Jul 05, 2002 at 02:42:55PM -0400 References: Message-ID: <20020705120333.A25180@efn.org> Around Fri,Jul 05 2002, at 02:42, Rajarshi Guha, wrote: >Hi, > I have some code: > >a = [1,2,3,4] >b = a > >Do some operations on a >Will the contents of b mirror a? Or will b remain unchanged? fire up python and try it. b mirrored a with my version. As in, a[3]=7 b [1,2,3,7] -- Roger --------------------------------------------------------------------------- roger at efn.org The following is generated by /usr/games/fortune: "I just need enough to tide me over until I need more." -- Bill Hoest From aahz at pythoncraft.com Tue Jul 9 00:14:01 2002 From: aahz at pythoncraft.com (Aahz) Date: 9 Jul 2002 00:14:01 -0400 Subject: Multi-threading on Multi-CPU machines References: Message-ID: In article , Garry Taylor wrote: > >I am attempting to make a multi-threading function in one of my >programs in an effort to gain a speed increase, but I'm getting quite >the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten >me as to why, my code is below: Pure Python code will always slow down when threaded; in order to gain a speedup, you must call an extension that releases the GIL. All I/O functions in Python release the GIL, for example. For more info, see the slides on my home page. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From aleax at aleax.it Fri Jul 19 07:05:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 19 Jul 2002 11:05:45 GMT Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: David Eppstein wrote: > In article <5606b639.0207181429.2c6d2569 at posting.google.com>, > otis_usenet at yahoo.com (OtisUsenet) wrote: > >> Python newbie question. How does one do something like this in >> Python: >> >> # assign the value of j to i and then increment j by 1 >> i = j++ > > Python is not designed for maximal terseness, nor for compatibility with > C, so you need two statements to do this (well, maybe there's a way to > do it in one, but the easiest-to-read and therefore best is with two): > > i = j > j += 1 A particularly mysterious, unreadable and useless way to "do it in one": i = [ j for j in j, j+1 ][0] Generally, I find that abusing list comprehensions is the easiest way to produce obfuscated Python. The specific "feature" of LCs that makes them so suitable for obfuscation is their ability to rebind variables in their for clauses. Alex From chris.lyon at spritenote.co.uk Thu Jul 4 12:36:09 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Thu, 4 Jul 2002 17:36:09 +0100 Subject: Thanks ... and how to express them. Message-ID: <3d2479ba$0$24410$afc38c87@news.easynet.co.uk> Dear all, Just a question of etiquete. I have recieved beneficial help form individuals do I thank on the list or not? Chris Lyon From wurmy at earthlink.net Thu Jul 11 18:18:09 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Thu, 11 Jul 2002 22:18:09 GMT Subject: writing output to file References: Message-ID: <3D2E041A.9080704@earthlink.net> Allan Wermuth wrote: > Inspired by an existing Perl script, I wrote this chunk of code, but instead > of > writing the result to the screen, I would like to write output to a another > file. > > #!/usr/bin/python > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue > > temp = line.split(':') > if int(temp[2]) > 100 : > print "%10s %30s" % (temp[0], temp[4]) > > How can I do that? > It's possibly quite simple, in Perl it is ;-) , but I am trying to learn > Python, so > I would appreciate if someone would help me out. Redirect sys.stdout: oldstdout = sys.stdout sys.stdout = open("some file", "w") # or any file(-like) object # your code here; print statements should be redirected # clean up sys.stdout = oldstdout HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From peter at engcorp.com Mon Jul 1 00:16:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Jul 2002 00:16:33 -0400 Subject: A problem with urllib References: Message-ID: <3D1FD7A1.F265FC8E@engcorp.com> Aki Niimura wrote: > > urllib doesn't like user to be an empty string. Thus, it keeps asking > a new user, passwd input (another call to prompt_user_passwd() ). > And eventually it went crazy (recursive error?). Are you using the latest version? I don't have a server that has a user "" to check this, but from looking at the source it really looks like it would allow either the username or the password to be empty, but not both. This is with Python 2.2.1. I tried a URL in urlopen() similar to the one you gave (http://:admin at 192.168.1.1/Status.htm) and it didn't complain, and tried opening the page with that information. -Peter From pwanon at web.de Tue Jul 23 08:59:50 2002 From: pwanon at web.de (Peter Wichert) Date: Tue, 23 Jul 2002 14:59:50 +0200 Subject: newbie problems with Tkinter References: Message-ID: <60kjha.e28.ln@localhost.my.domain> Chris Liechti wrote: > [...] > you have an installation problem. the error does mean that the pyd/so file > _tkinter.so is missing. maybe the tkinter stuff is in a separate > install/package. Arrgl. You're so right. I found it in a separate port in ports/x11-toolkits. Thanks for your help, Peter -- Peter Wichert pwanon at web.de From aleax at aleax.it Tue Jul 9 17:16:04 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 21:16:04 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> <3D2B19CE.5040409@onsitetech.com> Message-ID: Robb Shecter wrote: ... > So again, I think that this does highlight the implicit nature of Python I think it most definitely does no such thing, > - when you grab an object out of a container, you can send whatever > message you want to it. You don't have to explicitly state what class > you think it is. And the reason you don't have to state that, is that it makes absolutely no difference whatsoever -- you can try to get any attribute (methods included) from any object, it either succeeds or fails (and that only partly depends on the object's class). Claiming that being able to not state such irrelevant things "highlights the implicit nature of Python" is just like saying that it "highlights the implicit nature of Python" that you don't have to state on what day of the week and at what time of day you wrote each function. It just doesn't matter, so OF COURSE you don't have to state it. Sheesh. Of course code written early on monday morning, or very late at night, will tend to be more buggy. Yet, all languages are so "implicit" that they don't force you to timestamp all your code. Just imagine...! Alex From kragen at pobox.com Mon Jul 1 01:43:42 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 01 Jul 2002 01:43:42 -0400 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> <831ybavprx.fsf@panacea.canonical.org> <3D0919AF.7050903@NOSPAMREMOVETHISxs4all.nl> <83it45lxfb.fsf@panacea.canonical.org> <3D1B92A2.7030605@NOSPAMREMOVETHISxs4all.nl> Message-ID: <837kkgj94h.fsf@panacea.canonical.org> "Steve Holden" writes: > "Irmen de Jong" wrote in message > news:3D1B92A2.7030605 at NOSPAMREMOVETHISxs4all.nl... > > Kragen Sitaker wrote: > > > What I guess you're not aware of is that asyncore supports the middle > > > ground (middle colors?) as well as the event-loop-driven end of the > > > spectrum. For example, Zope has an asyncore thread that handles I/O, > > > but actually processes requests and produces results in some child > > > threads. > > > > You're probably right. I don't know a lot about the workings of asyncore. It's pretty simple if you already understand select(). It might be simple even if you don't. > I understand that Zope used the asyncore code as a basis for development > rather than adopting it outright, but I haven't actually checked the source > to ensure this is so. Zope 2.4.2 on my machine uses the asyncore that ships with Python rather than using one of its own. > > Doing stuff the Zope way, the worker threads must have some way to > > get to the input and output streams that are handled in asyncore, right? Yes. > Well, it's a relatively simple matter: when an asyncore channel's > handle-connect() method is called, one fo the arguments is the socket that > was created by the connection. handle_connect() simply uses this socket to > create another channel, which is added to the map used by the asynchronous > select() loop. > > This new channel then starts to fire handle_read() method calls, which you > service by doing something with the data. If the something you do includes > putting data in an output buffer then handle_write() events also start to > occur. I think Irmen was asking, if the data handle_write is going to write is generated in another thread, how does it get written to the output buffer? Zope contains FIFOs, which look non-thread-safe to me but seem to work, that carry the data between threads. From prabhu at cyberwaveindia.com Fri Jul 12 14:17:47 2002 From: prabhu at cyberwaveindia.com (Prabhu Ramachandran) Date: 12 Jul 2002 11:17:47 -0700 Subject: Problems with mayavi, pyvtk References: <7396d2b2.0206191025.3351a888@posting.google.com> <7396d2b2.0206201046.4f0530fa@posting.google.com> Message-ID: <375ad208.0207121017.191aa33a@posting.google.com> hi, I'm looking at this via google (which of late is pretty rare). As Fernando suggested you are likely to get better help if you post on the mayavi users mailing list. A while back I posted instructions on getting VTK + Python + Tkinter working on Win32 using Les Schaffers DLL's. The instructions are avlbl. here: http://sourceforge.net/mailarchive/message.php?msg_id=1729179 HTH, prabhu d_blade8 at hotmail.com (Lemniscate) wrote in message news:<7396d2b2.0206201046.4f0530fa at posting.google.com>... > Hey, thanks for the info. Here's the only problem... I still get > errors. Here is what happens when I try to import vtkpython... > > >>> import vtkpython > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\Lib\site-packages\VTK\vtkpython.py", line 29, in ? > exec "from "+kit_name+" import *" > File "", line 1, in ? > ImportError: DLL load failed: The specified procedure could not be > found. > >>> import sys [snip] From roffe at aqualene.uio.no Sat Jul 20 04:58:09 2002 From: roffe at aqualene.uio.no (Rolf Marvin Bøe Lindgren) Date: Sat, 20 Jul 2002 10:58:09 +0200 Subject: [Q] wxPython - layout & placement References: Message-ID: [Robert Amesz] | But you'd better forget about wxLayoutConstraints altogether. The | manual states: | | Note: constraints are now deprecated and you should use sizers | instead. oh. -- Rolf Lindgren http://www.roffe.com/ roffe at tag.uio.no From aleax at aleax.it Sat Jul 13 17:07:25 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 21:07:25 GMT Subject: isA function? References: Message-ID: Roy Smith wrote: > Is there a standard isA() function in Python? It should take two > arguments, an instance and a class, and return true if the object is a > member of the class or one of the class's ancestors. Yep, it's spelled isinstance. > I looked at the inspect module, and was surprised to not find it there. It's a built-in. Alex From shagshag13 at yahoo.fr Thu Jul 25 09:24:01 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 25 Jul 2002 15:24:01 +0200 Subject: xml processing : too slow... References: Message-ID: i think i still miss something as i get : >>> line = 'this is an example of the kind of line that i could have and that i must check (could also contain 0-9, $ and punctuations)...' >>> p.Parse(line, 1) Traceback (most recent call last): File "", line 1, in ? p.Parse(line, 1) ExpatError: junk after document element: line 1, column 0 >>> anotherline = '' + line + '' >>> p.Parse(anotherline, 1) Traceback (most recent call last): File "", line 1, in ? p.Parse(anotherline, 1) ExpatError: junk after document element: line 1, column 0 this time line is really representative of the kind of suff i had (sentences with tag) (i had written a wrapper to handle this with find('<'), find('>'), and i check well formedness by using a stack...) but i would really understand why it doesn't work ! thanks, s13. From marklists at mceahern.com Thu Jul 18 10:23:39 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 18 Jul 2002 09:23:39 -0500 Subject: property problem In-Reply-To: <3D36C65A.5040300@mplusr.de> Message-ID: Subclass from object. // m - From aleax at aleax.it Fri Jul 12 03:33:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 07:33:24 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: <8DvX8.58418$Jj7.1534077@news1.tin.it> James J. Besemer wrote: ... >> Interestingly enough, I find I can live with everything that is >> mandated in PEP 8 -- some recommendations are not my favorite ones, >> but there's nothing really major in it that irks me. > > It's hard to complain about a style guide that acknowledges up front that > "A Foolish Consistency is the Hobgoblin of Little Minds" and that > furthermore common sense may at times dictate breaking the rules. Not hard at all -- PEP 7 does that too, yet every time I see that construct... } else { my blood still boils!-) Further, PEP 7 is enforced for patches to Python -- sensibly, mind you, as we wouldn't want Python's C sources to be a mixmax of styles -- but... Alex From zopestoller at thomas-guettler.de Fri Jul 12 07:59:49 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 12 Jul 2002 13:59:49 +0200 Subject: Calling Python from Allegro Lisp Message-ID: <3D2EC4B5.1070605@thomas-guettler.de> Hi! I have an old application which needs to call python. The old app is written in allegro lisp. I tried the following: (defparameter hlib "c:\\winnt\\system32\\python22.dll") (probe-file hlib) (ct:defun-dll Py_Initialize() :return-type :void :library-name hlib :entry-name "Py_Initialize") (ct:defun-dll PyRun_SimpleString((s :char *)) :return-type :long :library-name hlib :entry-name "PyRun_SimpleString") (Py_Initialize) (setq foo "print 'foo'") (PyRun_SimpleString (cref (ct:char *) foo 0)) But get: """ The first element (CREF (CHAR *) foo 0) of a function application is not a function name """ What could be wrong. I am new to lisp thomas From bh at intevation.de Thu Jul 4 12:36:02 2002 From: bh at intevation.de (Bernhard Herzog) Date: 04 Jul 2002 18:36:02 +0200 Subject: replacing instance __setattr__ References: Message-ID: <6qfzyzxxfx.fsf@abnoba.intevation.de> Jonathan Hogg writes: > There's only one special case that I know of and that's the special > attribute methods, which are different for the reason I posted before: they > *are* the mechanism that implements the lookup order. I'm not sure about the new style classes as I haven't had the time to really look at them yet, but for old style classes that's not quite true. For instance, __getattr__ does *not* define how attributes are looked up. It's only called by the interpreter when the normal attribute lookup fails. For __setattr__ and __delattr__ it's different. They do indeed override the normal set/del attribute operation. Otherwise they wouldn't be useful after all. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From aleax at aleax.it Sat Jul 27 10:50:52 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 14:50:52 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> Message-ID: Tim Gahnstr?m /Bladerman wrote: > > "Terry Reedy" >> > Things I want to change is for example, everything should be "call >> > refferense", >> >> It already is, which is why functions can mutate mutable objects. >> (This surprises some beginners.) Of course, for immutables (numbers, >> strings, tuples), there is no semantic difference between reference >> and value passing except for reduced memory usage. > > I want to make all variables mutable. Variables are just names, "post-it" tags that ate weakly attached to an object at any given time. They could (perverting terms) be said to be "mutable" in that nothing forbids detaching the post-it from one object and attaching it to another one (or just detaching it, that's what the del statement is for). If by "variables" you also want to mean structured names, i.e, x.y to mean attribute y of object x, right now it's up to x's type if attribute y is 'mutable' (reattachable, detachable, attachable at all). x's type may define for the purpose methods named __setattr__ and __delattr__, or in Python 2.2 "properties" (and potentially other descriptors) that defines what it means to try to attach an object to the name x.y. When x's type is a class and does not do anything about it, by default x carries around a dict and x.y is 'mutated' by acting on x.__dict__['y']. But the mutable/nonmutable distinction normally applies to OBJECTS. Python, like Java, uses nonmutable strings for the simplicity and clarity they bring (but Python was there first, just as it was for the "reference semantics" above summarized... well, not _first_, but definitely before Java:-). Don't confuse *mutating an object* with *reattaching a name to a different object*. Completely different issues. > When you want to make functions like > inc(x) where inc is supposed to increase the value of x by one. How is > that done in Python? It _isn't_ done! Python functions don't go around detaching and reattaching the names held by their callers, any more than Java or C ones do such intrusions in their callers' namespaces. Java is closer to Python -- reference semantics: names are just post-it notes. C uses a more complicated and ancient way to look at things, closer to the way a computer works internally - names are "boxes" with values "inside" them (value semantics). [Java makes things more complicated by having SOME types held in boxes, but that's just Java being cranky and complicated in the claimed name of efficiency]. One way to look at things is: passing an argument is exactly like assigning to a variable. I.e., say that you have: def inc(y): ...(something)... and you all inx(x). This is like doing: y = x After such an assignment, do you figure that there are things you can to do *y* that make *x* be connected to another object? There aren't. x and y are not all that tighly connected. They both refer to the same object, that's all. You can make y refer to another object, but that won't affect x. Do you think it SHOULD? Would you EXPECT, say: y = x y = 23 to rebind *x* to refer to 23 too? Now, it seems that what you want is: the y = 23 MUST rebind x IF it happens in ANOTHER function named 'inc', but must keep not rebinding x if it happens in the same function where x was also defined. I.e., the equivalence of argument passing to assignment must be broken, and argument passing must in some way create a far tighter binding between the source and destination names than assignment does. This is a very substantial complication to the language's definition, of course -- two ways to "associate", one the existing assignment-and-argument-passing way that must stay only connected to assigment syntax, the other a new and tighter association, that must take over argument passing syntax. Surely you realize that the more separate concepts there are, the harder a language is to teach, particularly to beginners. With Python, I can explain to a bright beginner ONCE that "the meaning of assignment is just like that of argument passing" (if I've taught argument passing first -- or else, the reverse, that works too), and I'm done. With your language, you will have to teach separately two different semantics, one for assignment and a subtly different ones for argument passing, making it harder for beginners that a language where just one semantics exists. > That is my view of CBR, maybe that is not the correct definition and I > don't need CBR. I'm sure you don't (need it, that is), but you do seem to keenly WANT it, which is another issue. value/copy-return is a simpler variant of CBR that, while still more complex than what Python does, might be easier for you to put in practice. There ARE differences, though. With CBR things happen magicaly and implicitly, as in: def f(x, y): x = "ciao" print y when called as f(a, a) must presumably print "ciao", since the rebinding of x has mysteriously rebound a which in turn is ALSO connected to y. With value/copy-return, just as with the simplest approach (i.e., Python's), f(a,a) will print whatever a contains on call; v/c-r adds one implicit rebinding at the end. Of course it IS still a mess, e.g. what does happen after g(a,a) when: def g(x, y): x = "one" y = "two" ...? With Python's semantics, nothing (simplest). With CBR semantics, a is presumably now worth 'two'. With v/c-r it's hard to say, since both copies back to a are done when g terminates and it's not clear how to sequence them in cases of conflict (even diagnosing the conflicts may not me trivial). What a mess. Still, you DO keenly want this mess (or some variant thereof), therefore, good luck in extricating yourself from it! Alex From tim.one at comcast.net Fri Jul 26 19:02:33 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 26 Jul 2002 19:02:33 -0400 Subject: extract elements of n char from a list In-Reply-To: Message-ID: [Fernando Perez] > ... > However, I'd like to mention a _minor_ inaccuracy in the text you > refer to by Tim. That's me! > He says that on Unix machines, time.clock() returns the user > time from your process. Technically that's not 100% true, as it returns > the sum of (user+system) time consumed by your process. > > The clock.c sources confirm this (from glibc-2.2.5): To be technical right back , I wrote about "Unix-like systems", which is a far broader world than is covered by glibc alone. The POSIX / Single UNIX Specification says only this: DESCRIPTION The clock() function shall return the implementation's best approximation to the processor time used by the process since the beginning of an implementation-defined era related only to the process invocation. RETURN VALUE To determine the time in seconds, the value returned by clock() should be divided by the value of the macro CLOCKS_PER_SEC. ... If the processor time used is not available or its value cannot be represented, the function shall return the value (clock_t)-1. There's no distinction drawn between "user time" and "system time", and "processor time" is left undefined. I do confess that I used the phrase "user time" merely to distinguish the behavior of UNIX-like systems from the Windows wall-clock time behavior of clock(), though, without your particular meaning of user time in mind. My apologies if it mislead, although, if it did, I hope it also helped drive home the larger point that timing algorithms across platforms (even just across different flavors of Unix!) is a business fraught with peril. From kurugant at denshi.ece.utk.edu Fri Jul 5 10:07:03 2002 From: kurugant at denshi.ece.utk.edu (Teja Sastry) Date: Fri, 05 Jul 2002 10:07:03 -0400 Subject: deleting a file References: Message-ID: <3D25A807.3070006@denshi.ece.utk.edu> I want to delete a file in the current directory from inside a python program. How do i go about doing it. Thanks, Teja Sastry From tdelaney at avaya.com Tue Jul 9 20:27:37 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 10 Jul 2002 10:27:37 +1000 Subject: Why self? Message-ID: > Louis> This one is lost on me. Sorry, I'm not operating at your > Louis> level. What is the point? I advocated initializing object > Louis> variables in a mandatory __init__ statment. So you should have > Louis> added > > Louis> def __init__(self): > Louis> name=None Why are you assigning None to the local variable "name", and then not using it? That's the basic problem here - there is no way of knowing if "name" is supposed to be a local variable which will be used only in __init__, or whether you want to create an instance name. Also, how would you then create proxy objects? If you *must* know the name of all attributes, you can't delegate "everything except what I want to intercept". Tim Delaney From sholden at holdenweb.com Thu Jul 25 15:43:13 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 25 Jul 2002 15:43:13 -0400 Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: <4xY%8.49963$xo1.20668@atlpnn01.usenetserver.com> "Fredrik Lundh" wrote in message news:VkW%8.944$HY3.237298 at newsc.telia.net... > Alex Martelli wrote: > > > > (does anyone here even know that readline takes an optional > > > integer argument, and what it does? ;-) > > > > I would hope so, given that > > http://www.python.org/doc/current/lib/bltin-file-objects.html > > documents it so clearly. > > does anyone here think that when I asked that question, I did > that because I didn't know, and wanted someone to look it up > for me? ;-) > Was that a rhetorical question? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From unlearned at learn2think.org Sun Jul 28 01:59:50 2002 From: unlearned at learn2think.org (Daniel Fackrell) Date: Sun, 28 Jul 2002 05:59:50 GMT Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> <3d438609$1@duster.adelaide.on.net> Message-ID: On Sat, 27 Jul 2002 23:50:01 -0600, Gerald Squelart wrote: > "Erik Max Francis" wrote >> Michele Simionato wrote: >> > I know a print statement cannot stay in a lambda function, however as >> > a newbie I ask : why ? >> Because a lambda is an expression, not a statement. > Therefore, a lambda *expects* an expression, not a statement. > > However, you could indirectly include a print statement in the course of > a running lambda expression: > def printArg(arg): > print arg > return arg > l = lambda x: printArg(x) > a = l(10) # will print 10 and assign 10 to a map(l, range(5)) # will > print numbers 0 to 4 and return [0, 1, 2, 3, 4] It may be useful to > debug a lamdba expression. Correct me if I'm wrong, but doesn't this just create an anonymous function that calls the named function printArg? Besides the added function-call overhead, how are the two following lines functionally different? l = lambda x: printArg(x) l = printArg Daniel Fackrell From jon+usenet at unequivocal.co.uk Wed Jul 10 19:33:10 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 10 Jul 2002 23:33:10 -0000 Subject: php function "addslashes" / "removeslashes" in python References: <%RKW8.47006$n4.11323296@newsc.telia.net> Message-ID: In article , Lowel Stern wrote: >>if you're doing database, you really should learn to use bound >>parameters... >> > I don't belive that MySQL can use that yet. Err, it certainly can. Go get MySQL for Python from http://sourceforge.net/projects/mysql-python Do not try and do addslashes-style quoting yourself, it is error-prone and you are just making things difficult for yourself. From donn at drizzle.com Tue Jul 9 02:06:42 2002 From: donn at drizzle.com (Donn Cave) Date: Tue, 09 Jul 2002 06:06:42 -0000 Subject: Why isn't this a bug? References: Message-ID: <1026194796.311156@yasure> Quoth "Russell Blau" : | "Jonathan Hogg" wrote in message | news:B94F68F5.D936%jonathan at onegoodidea.com... |> On 7/7/2002 21:12, in article aga7af$jsvv9$1 at ID-76829.news.dfncis.de, |> "Russell Blau" wrote: |> [...] |> > Of course, if someone would like to explain why something so simple and |> > intuitive is a "bad idea," please enlighten me. ;-) |> |> I think the problem is that you're considering an implicit behaviour to be a |> feature. The rough meaning of 'str' and 'repr' is: |> |> repr - return a string representation of an object (ideally such that |> the string can be 'eval'ed to re-produce the object) |> |> str - convert an object into a string |> |> For numbers, these two behaviours are easily defined. But for tuples and |> lists there is no obvious behaviour for 'str'. What does it mean to turn a |> tuple or a list into a string? In the absence of a defined behaviour, the |> interpreter falls back on just returning 'repr' of the object. | | Well, technically you're right. The documentation just says that | "str(object)" will return a printable string representing "object". It | does that, so it's not a bug. However, the language does define two | different functions (str and repr) for representing objects as strings. | There presumably is a reason for having two different functions and two | potentially different representations of the same object. Given that, | why shouldn't the representations of lists, tuples, and dicts recognize | this distinction? It would seem more logical, and more understandable | to newbies, if "repr(sequence)" recursively called "repr()" on its | elements [which it does], and "str(sequence)" recursively called "str()" | on its elements [which it doesn't]. However, I'll agree that this is | more a matter of "taste" than of right vs. wrong. I think that might be more symmetrical, but I disagree that it would be more logical - as perhaps you do too, if you think it's a matter of taste. I don't seem to be able to explain it more clearly than Jonathan Hogg does above, because he hit the nail right on the head. Lists don't have any rationale for a distinct str function, you're really seeing a repr. The kind of object that will have a distinct str function is usually one that contains some significant string data. Obviously, a string itself contains string data. rfc822.Message, various classes in the Cookie module. The resulting string data is not a representation of the object, for you to look at, it's what you would send to a mailer or a browser. The problem with floating point is that its repr/str split was done with a completely different perspective, one that makes little sense to me but is enshrined in documentation - repr is reversible, kind of a lightweight (and not at all reliable) marshalling function, and str is a "nice" representation (whatever that means.) But then when 2.0 introduced the full precision repr(float), people very much did not like it. They should have been delighted, because it's now more precisely reversible, but we all want a "nice" repr, not a reversible one. A third function would sure help resolve the problem, but it would be a lot easier to just go back to the 1.5 repr(float). Donn Cave, donn at drizzle.com From jdavis at empires.org Tue Jul 23 07:49:04 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 23 Jul 2002 11:49:04 GMT Subject: format strings or page tempaltes Message-ID: I am trying to make use of an organized templating system for web development. I really just need something simple, so I was considering using format strings (just doing "open('mytemplate').read() % mydict"). The only thing that seems to be lacking for me is the ability to call a function with arguments from the template file. For example, here's what I'd like to be able to do: .... %(myfunction("foo"))s ..... where the format would be replaced by the return value of myfunction. Is this possible with the string format syntax? If not, could someone recommend a good template module or something similar? Thanks, Jeff From jblazi at hotmail.com Tue Jul 16 13:04:26 2002 From: jblazi at hotmail.com (JB) Date: Tue, 16 Jul 2002 19:04:26 +0200 Subject: Making code faster References: <3d3445f9_7@news.newsgroups.com> Message-ID: <3d34504b_2@news.newsgroups.com> Gerhard H?ring wrote: > The line "self.sv.lv.rows = map(tmp1,tmp)" makes some call > into an external library (PyQt?) that's likely taking up > the whole time. No, not really. PyQt is not used here and no other external library is used either. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From todd_gable at invision.iip.com Tue Jul 2 18:24:29 2002 From: todd_gable at invision.iip.com (Todd) Date: Tue, 2 Jul 2002 15:24:29 -0700 Subject: Running scripts within scripts Message-ID: <3d2225d8$1@post.usenet.com> **** Post for FREE via your newsreader at post.usenet.com **** Is it posible for a python to call a second without importing a module? I don't really want to call os.system and have to include paths. Just call a second script in the same directory as the parent one. Thanks. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! *** http://www.usenet.com Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= From miracle at paradise.net.nz Thu Jul 11 01:11:24 2002 From: miracle at paradise.net.nz (Matthew Sherborne) Date: Thu, 11 Jul 2002 17:11:24 +1200 Subject: How to grab a part of web page? References: <3D2C10D7.13991.31D8789@localhost> Message-ID: <3D2D137C.20602@paradise.net.nz> Yes you need it already on your disk for that code. I'm not sure how to do it with http but it is possible on most servers. You have to send it special headers in the request. You can see which headers by reading the information in this URL: http://www.ietf.org/rfc/rfc2616.txt Search for "partial get" and "range header". For using httplib in python see this URL: http://www.python.org/doc/lib/httpconnection-objects.html Sorry I couldn't be more help. :) GBU Matthew Sherborne A wrote: >On 10 Jul 2002, at 13:47, Matthew Sherborne wrote: > > > >>A wrote: >> >> >> >>>Hi, >>>Is it possible to download only a part of web page? >>>Say I need to find out an information about a customer that starts at >>>1500 byte position and ends at 2000 byte position. If the whole page >>>has about 100 kb it seems to me waste of time to load all the page. >>>What is the best, yet easy, solution? Is it possible to use httplib >>>or necessary socket module? Thank you for help. Ladislav >>> >>> >>> >>> >>f = open('webpage) >>f.seek(1500) >>data = f.read(2000) >>f.close() >> >>The operating system takes care of the efficiency for you. >> >>:) >> >> >> >Thank you for your email. >But if I use the code above I need to have webpage already on my >local disk. Am I right? > >I look forward to hearing from you soon. > >Best regards, >Ladislav Blazek( Mr.) > >BMA TRADING Ltd. >email: export at sendme.cz >email2: export at bmatrading.com >Fax:/Tel +420 506 447921 >Tel:+420 506 447920, +420 602 849309 > > > > > > From tim.one at comcast.net Thu Jul 25 22:10:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 25 Jul 2002 22:10:13 -0400 Subject: join in threads In-Reply-To: <200207251917.PAA31615@test-area.com> Message-ID: [anton wilson] > Is there a reason why join is only available for threads created with the > threading library? The only primitive thread operation Python can assume exists across a gazillion incompatible platform thread implementations is the ability to start a thread. > Is there some architectural drawback why I couldn't just > release the GIL, pthread_join, and then grab the GIL when I'm > done? pthread_join only exists on pthreads systems, and Python's thread API is meant to be portable. > I'm not sure what the threading module does but it doesn't seem to use > the system's join functionality but somehow implements it on its own. Yes; in general, it has no choice about that. It can notice when a thread it itself created has exited, but can't know anything about "foreign" threads in a portable way. From gerhard at bigfoot.de Sun Jul 14 19:25:49 2002 From: gerhard at bigfoot.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 15 Jul 2002 01:25:49 +0200 Subject: Getting an error when quitting an app using a call 'self.master.quit'? In-Reply-To: References: Message-ID: <20020714232549.GA3646@gargamel.hqd-internal> * G. Willoughby [2002-07-15 00:10 +0100]: > I have been getting an error when quitting an app using a menu to call > 'self.master.quit'. the error is: > > 'The instruction at "0x00d7a0a3" referenced memory at "0x00000008". The > memory could not be "read".' > > My OS is winXP Pro any ideas whats going on? No, in theory it's possible to determine at which line in the C/C++/whatever code your program crashed, if you give the detail of exactly which Python version, versions of extension modules and where you got them. And if these were built in debug mode, and the stripped (or whatever the Windows equivalent of that is). But as Python and your extension modules are Open Source, you just need a debug version of Python and your extension modules and run your app in a debugger. When the segmentation fault happens, you can get a traceback in your debugger. For Python itself, this currently requires having access to Microsoft's Visual C++ (or lot of writing Makefiles for your favourite other compiler yourself). Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From loewis at informatik.hu-berlin.de Mon Jul 29 04:46:08 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 29 Jul 2002 10:46:08 +0200 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> <3D4263E7.3000107@ims.u-tokyo.ac.jp> <3D42D972.2060607@ims.u-tokyo.ac.jp> Message-ID: Michiel Jan Laurens de Hoon writes: > Sorry ... it seems that distutils ignores the CC environment variable > (see below). This was done on cygwin. On Unix, the CC variable was > also ignored using setenv CC gcc, and also with set CC=gcc. Here > distutils defaulted to the standard cc compiler. I am guessing that it > took the compiler name from the Makefile in /lib/python2.2/config. > Any ideas? You can't take your Windows run as a proof that the variable is ignored. On Unix, it is honored. Regards, Martin From dig.list at telkel.net Wed Jul 24 14:01:07 2002 From: dig.list at telkel.net (DIG) Date: Wed, 24 Jul 2002 13:01:07 -0500 Subject: Detecting pipe on stdout? -- col In-Reply-To: ; from "Alexander Schreiber" on Wed, Jul 24, 2002 at 02:32:17PM References: Message-ID: <20020724130107.C20383@lifebook> Hi, Alexander Schreiber ! On Wed, Jul 24, 2002 at 02:32:17PM +0000, Alexander Schreiber wrote: [...] > Is there any way for a Python program to detect wether its stdout has > been redirected to a pipe/file (like "./programm | less")? I've didn't > find anything about this in the FAQ and failed to come up with the right > search terms for google. > > Reason: I've got a Python program[0] here which normally colorizes its > output (to the terminal) using escape sequences. This is fine and nice > while running on a terminal, but when running the program with less > attached to it the escape sequences are annoying. Ideally, I want to > detect a pipe attached to stdout and switch of the color (the flag is > already there) in this case. It is not EXACT answer to your question, but I hope this could help you to solve your problem: you could use ``col'' command (if you are using Linux). >From ``man col'': [...] col - filter reverse line feeds from input [...] All unrecognized control characters and escape sequences are discarded. [...] So, you could use it like this: $ program | col | less HTH, -- DIG (Dmitri I GOULIAEV) From skunix at hotmail.com Wed Jul 31 18:13:35 2002 From: skunix at hotmail.com (SK) Date: 31 Jul 2002 15:13:35 -0700 Subject: Python Windll - passing python lists to DLL function using Windll Message-ID: Hello, I have a function named TestMap() with the following prototype:- void TestOpenCluster(_InputParamMap MapStateBefore); where, typedef std::map _InputParamMap ; How do I pass the python list to this function using Windll? I got an AV with the following code? import windll arr =[ (windll.cstring('VAR1'),windll.cstring('VALUE1')), (windll.cstring('VAR2') , windll.cstring('VALUE2')) ] modl = windll.module('MyTestDll') modl.TestMap(arr) Exception exceptions.AttributeError: "cstring instance has no attribute 'mb'" in ignored Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\windll.py", line 44, in __call__ args TypeError: an integer is required Thanks in Advance. /SK From kristian.ovaska at helsinki.fi Wed Jul 31 05:05:31 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Wed, 31 Jul 2002 12:05:31 +0300 Subject: lexing nested parenthesis References: Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard): [context-free grammars] >> it can parse any programming language. >I would not go that far. There are strange beasts out there. Moreover, >people usually throw good parts of the complexity in "semantic analysis" >passes. You're right, of course. The point was that context-free grammars are fundamental building blocks of parsers and you have to learn them if you want to write real parsers. Perl must be hard to parse, just think about that regexp stuff for instance! >In the caricatural case, your grammar may parse individual >characters and leave it all to later compilation stages, so a fortiori, any >kind of parser will do. We are diving in the complex art of compromises! :-) And a real world case is the handling of reserved keywords. Perhaps this is on the scanner side, but it illustrates the principle: often all names are recognized with a single rule, and then the token is checked for whether it's a keyword or a normal name. >PLEX and PLY are not so compact, they also require some more work to use, >but they reward us with speedier analysis, especially for bigger grammars. PLY has good error reporting, too. -- Kristian Ovaska From aleax at aleax.it Fri Jul 12 16:45:39 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 20:45:39 GMT Subject: Is count supposed to still work? References: Message-ID: David LeBlanc wrote: > Whether or not you explicitly import string, > count(mystring, substring) > isn't working ("NameError: global name 'count' is not defined") (N.B. this > statement is in a method of a class), > but > mystring.count(substring) > does. However, count is not listed as deprecated in the python 2.2.1 doc. > Even deprecated, it should still work. I don't know what you're talking about. Python has never had a builtin called 'count'. If you import string, then you can call string.count -- that's not a global name of your current module, of course, but rather a global of module string, i.e., an attribute of module string. > something, a different way to express the same thing. Exactly what we DON'T want in Python -- the ideal, alas unreachable, would be to have *ONE* way to express one thing. Alex From bokr at oz.net Sat Jul 27 21:40:25 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Jul 2002 01:40:25 GMT Subject: xrange questioin References: <3d43234e$1@duster.adelaide.on.net> Message-ID: On Sat, 27 Jul 2002 23:32:45 GMT, "Fredrik Lundh" wrote: >Gerald Squelart wrote: > >> Ok, let me rephrase Chris' question for a simpler case: >> What is better: for x in range(n) or for x in xrange(n)? >> (with n is relatively small, like 10 or 100) > >for in range() is usually a few percent faster, but if you do some- >thing inside the loop, you'll hardly notice the difference. > >if performance matters a lot, I suggest benchmarking. > But speed isn't the only thing. Range builds a potentially huge list in membory. If we didn't have range to seduce us into wasting memory, we could still do [x for x in xrange(n)] now that we have list comprehensions. It might be slower than range(n), of course, unless that case were specially optimized. Regards, Bengt Richter From loewis at informatik.hu-berlin.de Wed Jul 24 06:00:20 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 24 Jul 2002 12:00:20 +0200 Subject: locale on Japanese win XP References: <3324f4eb.0207240105.48db826e@posting.google.com> Message-ID: amir at clockwise3d.com (Amir Hadar) writes: > I'm trying to get the locale settings with the locale module under Japanese > windows XP. > when I try to set the locale settings with the following command: > > locale.setlocale(locale.LC_ALL,'') > > the locale throws the following exception: > > locale.Error locale settings not supported > > Any ideas? Interesting. Please try the following: - use _locale.setlocale, instead of locale. - try settting individual categories only (in particular LC_TIME, LC_CTYPE, LC_NUMERIC, and LC_MONETARY) If any of those succeeds, please report the details. Also, is the Japanese XP proper, English XP with Japanese MUI, or just English XP with Japanese local settings? If Japanese XP, are the locale settings left at their defaults? Regards, Martin From raimo-news at mail.com Sat Jul 13 11:58:59 2002 From: raimo-news at mail.com (Raimo Tuisku) Date: Sat, 13 Jul 2002 18:58:59 +0300 Subject: Tkinter Menu command Message-ID: Is it possible to pass arguments to a method which is executed after event? I am trying to do so with add_command method from Menu widget to avoid writing separate method for every case. #From class App: self.mb = Menubutton(self.frame, text="Color") self.mb.grid() self.mb.menu = Menu(self.mb,tearoff=0) self.mb['menu'] = self.mb.menu self.colors=['red','green','blue'] for item in self.colors: self.mb.menu.add_command (label=item,command=lambda :self.set_color(item)) # Even this doesn't work. Apparently it always uses # self.set_color('blue'). (self.label colors to blue) # Method for setting the color in class App: def set_color(self,color): self.label.config(fg=color) -- Raimo Tuisku From grahamd at dscpl.com.au Mon Jul 22 19:28:15 2002 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 22 Jul 2002 16:28:15 -0700 Subject: xmlrpclib question References: <3D3BFA10.92E38B5B@millfilm.co.uk> Message-ID: Eric Texier wrote in message news:<3D3BFA10.92E38B5B at millfilm.co.uk>... > I posted this question earlier but I am still confuse about what I am > doing wrong. > Why, in the class 'clientRootTask' just taking out the 'if' statement > will make > it work: > > > . > . > if serverp: > serverp.SendTask(msg) > .. > produce the error: > raise apply(Fault, (), self._stack[0]) > xmlrpclib.Fault: is not supported'> The XML-RPC proxy class defines __getattr__ to intercept all method calls made against the proxy and translate them into a request against the remote object on the server. Your "if" statement does the equivalent of call the __nonzero__ method. What is most likely therefore happening is that the exception is being raised on the server because the remote object doesn't have __nonzero__ as a method. This is translated into an XML-RPC Fault object at the client. Try writing your code as: if type(serverp) is not types.NoneType: serverp.SendTask(msg) Alternatively, the XML-RPC proxy class in xmlrpclib could have provided the method: def __nonzero__(self): return 1 If serverp was indeed a None object, it would then fail the "if" test and the code wouldn't get run. With __nonzero__ above in the XML-RPC proxy, it would have resolved the test on the actual local proxy object, returning true and thereby running your code. Understand? From mgilfix at eecs.tufts.edu Mon Jul 29 10:14:32 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 29 Jul 2002 10:14:32 -0400 Subject: Size in byte of a string ? In-Reply-To: ; from shagshag13@yahoo.fr on Mon, Jul 29, 2002 at 01:15:23PM +0200 References: Message-ID: <20020729101432.D15737@eecs.tufts.edu> For the easy part, I suggest you simply layout a dict object as you suggested: dict[header_name] = (start, end) and then you can do as you wish: start_at_byte, end_at_byte = dict[header_name] f.seek(start_at_byte) content = f.read(end_at_byte) Each char is 1 byte and len(string) will give you the number of bytes. If your file format is consistent, you can probably do something like: get_first_position() for line in f.xreadlines(): if is_header(line): record_last_position() make_entry() record_new_start() That should build up your dict and help you do what you want. -- Mike On Mon, Jul 29 @ 13:15, Shagshag13 wrote: > "Shagshag13" a ?crit dans le message de news: ai37ij$10tmvq$1 at ID-146704.news.dfncis.de... > > [sorry for the previous incomplete post] > > > > hello, > > > > i had the following problem : i had huge files > 1,5 go. each of theses files contain some other small files and they are separate > > by a header. i need to do some kind of random access to the small files so i wish to write a script which would build some kind of > a > > table of content for theses huges files. > > > > i would like to have something like > > samllfile_header_name_i : start_at_byte : end_at_byte > > > > and i will do : > > f.seek(start_at_byte) > > samllfile_header_name_content = f.read(end_at_byte) > > > > but to do this i need to be able at the building time to know how much bytes take a string ? > > > > (i think there is something with the size in byte of CR/LF but how to measure it ? i hope i won't have to do some > > start_at_line, end_at_line as it will need to always read file from start...). > > i forget to write that theses are text files, that what i call "header" is more some kind of separator ("name_of_the_file\n"). > > thanks in advance, -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From rich at worldsinfinite.com Fri Jul 12 09:52:06 2002 From: rich at worldsinfinite.com (Rich Harkins) Date: Fri, 12 Jul 2002 09:52:06 -0400 Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?) In-Reply-To: <2c60a528.0207120147.498bc1f3@posting.google.com> References: <2c60a528.0207120147.498bc1f3@posting.google.com> Message-ID: <200207120952.06357.rich@worldsinfinite.com> > I like that kind of syntax. I'd like to propose an alternative > keyword: > > while cond1: > dofoo() > andwhile cond2: > dobar() > So does this eqate to the following in current python? while cond1: dofoo() if cond2: dobar() or? while cond1: dofoo() if cond2: dobar() else: break > with an analogous structure: > > if cond1: > dofoo() > andif cond2: > dobar() > else: > doqux() > and this? if cond1: dofoo() if cond2: dobar() else: doqux() or? if cond1: dofoo() if cond2: dobar() else: doqux() else: doqux() > where foo is done if cond1, bar is done if (cond1 and cond2) and qux > is done if not (cond1 and cond2). For consistency with elif it could > be called anif instead? What if I get more complicated: if cond1: true1() andif cond2: true2() elif cond3: true3() andif cond4: true4() else: false() How does this translate to current Python? (I'm gettting a headache now) I think I like Python's explicit nature better than these cases (as well as the all of the messages in this thread). I don't have to guess how Python will process my instructions nor do I have to think very hard about what a program will do when reading it. Rich From Gabe.Newcomb at noetix.com Mon Jul 29 14:47:54 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Mon, 29 Jul 2002 11:47:54 -0700 Subject: decoding XML-ified special chars such as " Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6164@NOXMAIL.noetixad.com> Is there a module to take strings such as ", & and turn them into the characters they normally represent (', &)? Gabe Newcomb Software Test Automation Engineer 425.372.2732 Noetix Corporation www.noetix.com after years of waiting, nothing came From aahz at pythoncraft.com Sat Jul 20 10:20:35 2002 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2002 10:20:35 -0400 Subject: Using pointers References: <4210d7a2.0207200538.44a91c0f@posting.google.com> Message-ID: In article <4210d7a2.0207200538.44a91c0f at posting.google.com>, Joe Krahn wrote: > >Can I make a pointer to an object in Python? I know that all >objects/variables are references, but not in the same sense as in C. >How do I get multiple pointers to reference and modify one variable? No, objects are not references, they're data. Variables (which I prefer to call "names" because of the confusion) only contain references, but it's all implicit. Thus: >>> x = [] >>> y = x >>> y.append('foo') >>> x ['foo'] This sequence creates the name x, binding it to an empty list object. Then the name y is created, referring to the same object as x. y gets mutated, and because x is bound to the same object, you can see the result of the mutation by accessing x. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From b.maryniuk at forbis.lt Thu Jul 4 08:57:00 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 4 Jul 2002 14:57:00 +0200 Subject: OpenOffice Python Bindings Message-ID: <200207041457.00217.b.maryniuk@forbis.lt> Hello, all. Somebody something heard sbout this (Python Bindings for OpenOffice)? If yes, please link me there at least... -- Sincerely yours, Bogdan M. Maryniuck Not me, guy. I read the Bash man page each day like a Jehovah's Witness reads the Bible. No wait, the Bash man page IS the bible. Excuse me... (More on confusing aliases, taken from comp.os.linux.misc) From jb at cascade-sys.com Wed Jul 24 16:43:12 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 24 Jul 2002 13:43:12 -0700 Subject: Numeric data question References: <%Nz%8.15893$A72.86385@news1.mts.net> <3D3EF9AD.A0F661BC@noaa.gov> Message-ID: <3D3F1160.EE1C1C19@cascade-sys.com> Chris Barker wrote: > Do any programming languages have a built in "money" type? Visual Basic does, as I am sure do several others. Curency was not part of VB for quite a while. I believe currency eventually was introduced to VB mainly in order to facilitate interfacing with various database engines, most all of which have an explicit currency type (distinct from real and int). The Python interfaces to MySql and MSql implement a currency type for this very reason. Time and Date also. These in fact are not arbitrary implementations of currency, et al., but necessarily track the database native format and ease conversion to/from native Python formats. Amongst the various attributes that may be counted on the list of benefits of an explicit currency type are (a) it is a good place to isolate locale issues and (b) accuracy requirements generally prohibit use of floating point (which is intrinsically inaccurate for decimal fractions) or integers (which lack the necessary precision). Of course, such a thing could be implemented in Python as you suggest, probably with longs or strings emulating fixed-point numbers. All those cute anecdotes about round off error -- they're not actually tolerated in real commerce applications. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From mark.charsley at REMOVE_THIS.radioscape.com Wed Jul 17 05:40:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Wed, 17 Jul 2002 10:40 +0100 (BST) Subject: Debugging Embedded Python References: Message-ID: In article , mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote: > We've got a (win32) C++ program that has an embedded python interpreter > that runs a bunch of scripts. We've been asked to enable it's users to > run the python scripts under a debugger, allowing the users to put in > breakpoints, examine/alter values etc. Thanks all for your advice. Have finally got the pythonWin debugger working. Not in my original executable, mind you (which still acts as if the breakpoint had been hit, the debugger brought up and then instantly shutdown by the user), but in a second executable which uses the same source files and, as far as I've been able to tell, the same compiler settings. Don't you just love working with a completely deterministic, fully predictable systems :-) -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From maciej at maciejsobczak.com Wed Jul 24 10:15:40 2002 From: maciej at maciejsobczak.com (Maciej Sobczak) Date: Wed, 24 Jul 2002 16:15:40 +0200 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> Message-ID: Hi, "Jay O'Connor" wrote in message news:20020724.064941.722308542.1589 at cybermesa.com... > A while back, as part of a code sample I submitted for a job, I developed > a basic framework for distributed Python. This is a tool that allows one > Python application to communicate with another, whether on the same > machine or on remote machine(s) > > Being that it was just a sample, I never fully fleshed it out. I've been > contemplating developing it further but first I was wondering if such a > tool would be of interest to anyone else In addition to CORBA, you can also check out: http://www.maciejsobczak.com/prog/yami/ You can also go directly to the Python section: http://www.maciejsobczak.com/prog/yami/impl/index.html#python The advantage of this infrastructure is that it is really light. It allows you to write distributed apps not only in Python, but also in C, C++ and Tcl. Cheers, -- Maciej Sobczak http://www.maciejsobczak.com/ From torppa at staff.megabaud.fi Sat Jul 6 18:53:47 2002 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Sat, 6 Jul 2002 22:53:47 +0000 (UTC) Subject: signal.alarm() for less than one second? References: Message-ID: In article , Andrei Kulakov wrote: > It looks like signal.alarm takes 1+ seconds as argument. I need > something lower, like 0.5 second or so. Usual way to do input timeouts on unix is to use select. there is also setitimer syscall but it does not seem to be wrapped into anything. -- Jarkko Torppa, Elisa Internet From wyojustin at hotmail.com Sat Jul 20 00:22:37 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Sat, 20 Jul 2002 04:22:37 GMT Subject: PDB question References: Message-ID: > Does pdb list function only works with funtions defined on a seperate modules? Is seem like you can only list one line at a time when debugging a function entered into the interpreter. Use 'h' to list the valid pdb commands. Basic usage is clear after about 5-10 minutes experimenting with the commands. > What does these mean (in pdb prompt) : > (1)?() This is always the initial position, not sure exacactly what is is telling you. > (1)foo() This says that you are currently in function 'foo()' which came from standard in which seem to always be at line 1. In general the format is: (line#)functionname() -> sourceline (If applicable) > TIA Hope it helps Justin From cliechti at gmx.net Sun Jul 21 15:04:07 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Jul 2002 21:04:07 +0200 Subject: Calling a python function with a list as the input argument from C References: <3D3B0160.9090800@img-online.de> Message-ID: Michael Grabietz wrote in news:3D3B0160.9090800 at img-online.de: > I tried the example given in the Python documentation calling Python > from C. In this example the input argument of the python function is a > tuple. See the code below which works fine. ... > Calling Python function with pArgs as tuple: That works fine ! > Calling Python function with pArgs as a list: That fails ! the tuple contains the arguments. if you want to pass a list as first argument then fill in the list as first element in the tuple. chris -- Chris From wurmy at earthlink.net Wed Jul 10 21:45:56 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Thu, 11 Jul 2002 01:45:56 GMT Subject: Learning how to program... but what's the best way? References: <3D2BB54C.90500@earthlink.net> Message-ID: <3D2CE339.8000407@earthlink.net> Thanks to all who replied. I got some good ideas here, that I will certainly try. First I'm going to find out more about why she wants to learn programming and what interests of her could be combined with it. I knew I could count on the newsgroup. Next day, 7 replies. :) Nice. -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From gerhard.haering at gmx.de Fri Jul 19 19:50:54 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 20 Jul 2002 01:50:54 +0200 Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) In-Reply-To: References: Message-ID: <20020719235054.GA3500@lilith.my-fqdn.de> * eugene kim [2002-07-19 18:46 -0500]: > i used this code.. > self.url=attributes["url"].encode('utf-8') > what should i do more? Encode all the other Unicode strings into utf-8 bytestrings. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 15.7 ?C Wind: 0.7 m/s From maxm at mxm.dk Tue Jul 2 02:16:05 2002 From: maxm at mxm.dk (Max M) Date: Tue, 02 Jul 2002 08:16:05 +0200 Subject: Testing self-written imported Modules in a Zope python external method References: <5cf809e9.0207011318.3965d29d@posting.google.com> Message-ID: <3D214525.9070109@mxm.dk> Peter Schwalm wrote: > I have a written a Python external script in Zope. It uses a small > self-written helper module producing a page header. Naturally the > first version of this module is not error free. During testing I > discovered that Zope never refreshes the version of this imported > module. Zope even doesn't care, if I delete the generated .pyd-File. > > Does this mean I always have to completely shutdown Zope if I want to > test a new version of the module? You are probably better of asking this on the zope at zope.org list. You should just save your external script in the Zope management interface every time you have changed it, then it will be updated in Zope. Or you could start Zope with the -D option, then I believe it will automatically update it. If you are importing the module into the external script you will need to "reload(external_module)" Else you need to list some code of your external method. regards Max M From pablo.pernot at albert.com Fri Jul 5 02:32:47 2002 From: pablo.pernot at albert.com (Pablo Pernot) Date: Fri, 05 Jul 2002 08:32:47 +0200 Subject: start working with gzip : probs with linux/windows References: <3D24B922.2000605@obscure.dk.X> Message-ID: cooL. it works. On Thu, 04 Jul 2002 23:07:46 +0200, Thomas Jensen wrote: > Do you open the files in binary mode? Makes a difference on Windows. > > /Thomas > > Pablo Pernot wrote: >> Hello all, >> >> I started working with the gzip module. It works fine in full linux >> env. >> But when I upload (working with socket) gzip files in a windows env, >> the files appear corrupted. >> any clue ? From petrk at pochtamt.ru Thu Jul 18 11:44:19 2002 From: petrk at pochtamt.ru (Petr Klyushkin) Date: 18 Jul 2002 19:44:19 +0400 Subject: __del__ in classes derived from Tkinter classes Message-ID: Hello! I'm a Python and Tkinter newbie. I've noticed that __del__ methods of my classes derived from Tkinter classes are never called. Is this normal behavior, or I am doing something wrong? Example code: import Tkinter class Test(Tkinter.Toplevel): def __del__(self): print 'hey!' tk = Tkinter.Tk() test = Test(tk) -- C'ya, Peter. --=[petrk at pochtamt.ru]=--=[http://petrk.pochtamt.ru]=-- --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=-- From sholden at holdenweb.com Mon Jul 1 10:13:42 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 10:13:42 -0400 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> <831ybavprx.fsf@panacea.canonical.org> <3D0919AF.7050903@NOSPAMREMOVETHISxs4all.nl> <83it45lxfb.fsf@panacea.canonical.org> <3D1B92A2.7030605@NOSPAMREMOVETHISxs4all.nl> <3D1C9DF8.3010607@NOSPAMREMOVETHISxs4all.nl> Message-ID: "Irmen de Jong" wrote ... > Steve Holden wrote: > > > asyncore/asynchat really repay the effort of study, so I would advise you to > > take a fresh look when you get time. > > I will. Am I correct to conclude that the benefits of using asyncore as a > basis for Pyro are: > 1. uses a well-tested stable I/O module (though the current implementation > in Pyro isn't bad at all) Certainly the code is pretty sound, being (among other things) the basis of the server used in Zope. > 2. able to process multiple requests without using threads, because > the I/O is multiplexed Yes, although there may be other benefits to multi-threading. For example, I wrote a web framework using a relational database to grab content. In its naiive state (i.e. as implemented) each transaction must terminate before the next one can begin. If I had used a thread-per-request implementation (which wouldn't have been that hard, IIRC) then the slack time during database access would have been available to the other requests, which I anticipate would have improved throughput in heavily-loaded environments. > 3. able to handle very many concurrent connections (no thread overhead > per connection -- but is a thread really that heavy?) > The effbot said: """lot's of information and links here: http://www.kegel.com/c10k.html""" I can't say better. > > > To assist you, I plan to add documentation for asynchat for 2.3. > > That's nice because I was looking for that one just yet :) > But glancing at the code of asynchat makes me think that this > one isn't suited for Pyro because Pyro is no line-based command-response > protocol. > I don't know the details of Pyro, but I imagine the interactions could be similar to web interactions: sometimes you want to recognise a particular string in the datat stream (like the empty line that terminates the headers) and sometimes you want to read a fixed number of characters (such as when guided by a "Content-Length:" header). Naturally, that would be your call. > > when-sourceforge-stops-playing-silly-buggers-ly y'rs - steve > What's wrong with SF? > It was just running like a dog the day I wrote that. SF can get a bit slow at busy times. > Cya why-should-i-cover-my-ass-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From gherman at europemail.com Tue Jul 16 08:01:36 2002 From: gherman at europemail.com (Dinu Gherman) Date: Tue, 16 Jul 2002 14:01:36 +0200 Subject: Any Python distribution solutions for Mac? References: <080720021958161862%rodneys@nospam.io.com> Message-ID: <20020716140415308+0200@news.t-online.de> Rodney Somerstein wrote: > The subject says it all. Is there any packaging mechanism for > distributing Python applications on the Macintosh? I know that > there is py2exe for Windows and that I can do similar things > for Unix. But what about for the Macintosh? > > If not, is there anything planned? If so, when will it be avail- > able? > > This, along with UI issues which wxPython is slowly taking care > of on the Mac is one of the things that has kept me from using > Python. I wrote something to create "packages" (.pkg) on OS X. All Apple update pacakges seem to use this kind of in- staller. For some reason they are compressed using pax, which is not always available on other platforms. Also, my tool never handled multi-packages. And Installer.app seems to give wrong install size estimates by definition, but... Yep, some people suggested to make a distutils adaptor for it, but at the time that seemed too complicated to me. I haven't used it (buildpkg.py) for a while, but you can get it here: http://python.net/~gherman/#buildpkg Regards, Dinu From andreas at kostyrka.priv.at Wed Jul 31 08:37:25 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 31 Jul 2002 14:37:25 +0200 Subject: A better self In-Reply-To: <3D3DD787.4060906@NOSPAMREMOVETHISxs4all.nl> References: <2259b0e2.0207231348.7496eca0@posting.google.com> <3D3DD787.4060906@NOSPAMREMOVETHISxs4all.nl> Message-ID: <1028118135.7025.6.camel@vaio2> Am Mit, 2002-07-24 um 00.24 schrieb Irmen de Jong: > Michele Simionato wrote: > > > It has not been mentioned in this thread, but there a simple way to cope > > with this problem without changing the language: a Python preprocessor. > > This will work if you know that the code you're dealing with has to be > processed first before it is real Python code. > > It will not work if you are somehow unable to run the preprocessor first. > Think about importing modules. They have to be processed first, > otherwise the import will not work because the module is not correct > Python code. Well, the preprocessor would need to bring a custom import procedure. For an example see the page templates in Quixote. Andreas From walter at livinglogic.de Wed Jul 24 08:37:15 2002 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 24 Jul 2002 14:37:15 +0200 Subject: Content-Type Guesser References: <3D3E9E43.2050507@thomas-guettler.de> Message-ID: <3D3E9F7B.2050604@livinglogic.de> Thomas Guettler wrote: > Hi! > > Has someone a function for guessing the content type > given a filename? > > foo.xml --> text/xml > foo.html --> text/html > .... > > It should work for the most common file-extensions Python 2.2.1 (#1, Apr 10 2002, 19:08:12) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mimetypes >>> help(mimetypes.guess_type) Help on function guess_type in module mimetypes: guess_type(url, strict=1) Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. Hope that helps, Walter D?rwald From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 21:43:27 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 18:43:27 -0700 Subject: performance problem in python 2.2 References: <260720021725073781%mday@apple.com> Message-ID: <7xbs8uymgw.fsf@ruckus.brouhaha.com> Fernando Perez writes: > Out of curiosity, why does this happen? I understand looking up > global variables when in a function being expensive, since you first > must go through the local dict (and fail). But when the code is > itself global and there's no other scope in sight, why is it any > slower? In a sense, for global code 'everything is local', so I > don't quite understand why the difference. Global variables are accessed by a dict lookup in the global environment. Local variables are accessed by looking directly at the appropriate slot in the local stack frame. From martin at v.loewis.de Thu Jul 25 04:29:29 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Jul 2002 10:29:29 +0200 Subject: VERY URGENT : Python 2.2 Installation on Solaris 2.5 References: Message-ID: "dhananjay" writes: > Can you send us the Python 2.2 package for installation on Solaris > 2.5. We could not install from Python binary file. From the > www.sunfreeware.com site we see that Python 2.1.1 package is > available only for Solaris 7. Can this Python 2.1.1(for Solaris 7) > package be installed on Solaris 2.5? That is easy to answer: It cannot be used. Regards, Martin From tom.verbeure at verizon.no.sp.am.net Sun Jul 28 13:04:27 2002 From: tom.verbeure at verizon.no.sp.am.net (Tom Verbeure) Date: Sun, 28 Jul 2002 17:04:27 GMT Subject: How to detect the last element in a for loop References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: > I did not follow this thread, I may be missing something, but why not: > > for a in myList: > do_stuff(a) > special_stuff(a) > > taking advantage on the fact that `a' keeps the last value it received? Then what about this? for a in myList: if last_one: special_stuff do_stuff Tom From aleax at aleax.it Fri Jul 12 04:56:40 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 08:56:40 GMT Subject: How to replace multiple-line text References: <3D2D0782.45FCEC98@bellatlantic.net> <3D2E35C6.5B2612CF@bellatlantic.net> Message-ID: David Lees wrote: > Thank you kindly Alex for this solution. This is the problem that I had You're welcome! > in mind. You also taught me something rather basic about Python that I > misunderstood I thought that to use string methods I needed to import > the string class and then use it like this: > >>>> import string >>>> x='this is junk' >>>> string.replace(x,'junk','stuff') > 'this is stuff' > > Time to do some more reading on classes, since I don't understand why it > is not necessary to import string here. 'string' is a module, not a class. "import string" loads the module (if it wasn't already loaded) and makes the module object available, with name 'string', in the current namespace. The class (type) is named 'str', and you never need to do anything strange to access it because it's a builtin name, always available. But when you have an instance of any type, you never need to get the type -- you can just call methods directly on the instance. This is part of object-oriented programming -- you have the object (that is, the instance), you don't need to access types or modules to call the object's methods -- just do it. Module string does offer functions named just like the methods of str instances (string objects), for historical reasons -- it used to be, until a few years ago, that string objects had no methods, so you HAD to import string and call its functions back then. To avoid breaking old working code, you still CAN work that way, but there's no need at all to do that in new code. If you look at string.py in the directory where you keep your Python library (C:\Python22\Lib, say) you'll see a lot of code such as: def lower(s): return s.lower() i.e., the function is just a thin wrapper over the object's method, and delegates everything to the object's method -- it's pure (if small) overhead and exists only for backwards compatibility. Alex From simon at uggs.demon.co.uk Tue Jul 9 18:57:26 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Tue, 09 Jul 2002 22:57:26 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: <3d2b69b6.15643974@news.dsl.pipex.com> On Tue, 9 Jul 2002 22:01:24 +0000 (UTC), huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) wrote: >Simon Foster wrote: >>On Tue, 9 Jul 2002 15:23:49 +0200, "Bo M. Maryniuck" >> wrote: >> >>>On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote: >>>> eval! >>> >>>Overkill. Unsafe. Ugly. Lame. >>> >> >>What do you mean by unsafe? > >Something like the following could happen (don't try it!) > ># eval('system("rm -rf /")') > >Huaiyu Emile Bo Matt Huaiyu You seem to be mistaking me for an idiot. -- Simon Foster Cheltenham England From Gregory_Engel at csgsystems.com Fri Jul 19 15:10:49 2002 From: Gregory_Engel at csgsystems.com (Engel, Gregory) Date: Fri, 19 Jul 2002 14:10:49 -0500 Subject: Windows, Python and Strings Message-ID: I'm trying to update an NT/W2K service configuration (service written in Python) using win32service.ChangeServiceConfig. The following code runs without error: >>> import win32serviceutil >>> scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) >>> svc = win32service.OpenService(scm, "TestQueueMgrSvc", win32service.SC_MANAGER_ALL_ACCESS) >>> svccfg = win32service.QueryServiceConfig(svc) >>> svccfg (16, 2, 1, u'"D:\\Python\\Lib\\site-packages\\win32\\PythonService.exe"', u'', 0, u'', u'LocalSystem', u'Test Queue Manager') So, I have a handle to the service and can retrieve it's current configuration. Now I want to make this service dependant on MS SQL Server: >>> win32service.ChangeServiceConfig(svc, svccfg[0], svccfg[1], svccfg[2], svccfg[3], svccfg[4], svccfg[5], 'MSSQLServer', 'LocalSystem', '', "Green Bar Queue Manager") This also executes without error. When I look at the Registry, the value shows as "M S S Q L S e r v e r" rather than "MSSQLServer" so the dependency fails. If I use the MS tool, sc.exe: sc config TestQueueMgrSvc depend= "MSSQLServer" the Registry value correctly shows as "MSSQLServer". I've tried a number of approaches to resolving this with no luck. It doesn't appear to be a encoding issue. The method requires a string parameter. The Registry stores the value as binary data. What am I missing? Is there something I don't understand about how to use this method? Many Thanks. C'ya, Gregory Engel Senior Software Engineer Professional Services CSG Systems, Inc. 9555 Maroon Circle Englewood, CO 80112 Voice: 303-200-3426 ???????????????????? My other computer is spongy gray matter. From grante at visi.com Thu Jul 11 19:08:06 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 11 Jul 2002 23:08:06 GMT Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> Message-ID: In article , Terry Reedy wrote: > > "Robb Shecter" wrote in message > news:3D29CE9D.4000802 at onsitetech.com... >> Matt Gerrans wrote: >> I completely agree, but I think the situation's even worse than you >> described: A'typical' case of standard OO programming is made the > most >> tedious to write: References to instance variables from methods: >> >> self.__velocity = self.__factor1 * self.__factor2 >> >> etc. I find this totally unreadable (7 extra characters per > referenced >> instance variable). > > Only 2 'extra' chars are needed -- a letter and '.'. Why the extra > '__'? Thy're "private" instance variables. Whereas other languages provide a declaration for such a propterty, you get a similar result in Python by mangling the name... -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.com GARBAGE CAN? From nathan at cjhunter.com Thu Jul 11 12:59:57 2002 From: nathan at cjhunter.com (Nathan Cassano) Date: Thu, 11 Jul 2002 09:59:57 -0700 Subject: Python Embedded Instances Message-ID: <0a2901c228fc$63290ee0$2901a8c0@amos> Hi Pythoneers, I am working on developing an application that utilizes embedded python. My question is, can I create multiple instances of the Python interpreter within my application? My application has multiple documents each with their own embedded python code. I have read the Extending and Embedding Python documentation several times and have not found the answer. Thanks for you help. Nathan From Gabe.Newcomb at noetix.com Fri Jul 26 14:03:59 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Fri, 26 Jul 2002 11:03:59 -0700 Subject: Figured it out: Tkinter grid and why 'sticky' option seems iffy Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F6151@NOXMAIL.noetixad.com> I was having problems where the sticky option in grid() didn't seem to move widgets out of the middle of the cell they were in. Turns out the reason was Tkinter default behavior is to determine column/row width based on the size of the widget that is contained, NOT based on the width of the master divided by the number of rows/columns. This seemed wierd to me, e.g., why, if I had a single cell in one frame (one row and one column only), should that cell not fill the entire frame? Anyways, the answer for me seems to always be to set the weight of the columns/rows to 1 (assuming I want equal widths). I'm posting this in the hopes that it helps out other newbies. Thanks, Gabe Newcomb Software Test Automation Engineer 425.372.2732 Noetix Corporation www.noetix.com after years of waiting, nothing came From ianb at colorstudy.com Wed Jul 31 17:00:22 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 31 Jul 2002 16:00:22 -0500 Subject: Let's Talk About Lambda Functions! In-Reply-To: <3D484585.448736C1@cascade-sys.com> References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitete ch.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <3D475AB5.2060207@nowhere.org> <1028096804.836.1812.camel@lothlorien.colorstudy.net> <3D47B936.1AFA8DB8@cascade-sys.com> <1028133358.578.3668.camel@lothlorien.colorstudy.net> <3D484585.448736C1@cascade-sys.com> Message-ID: <1028149223.578.4511.camel@lothlorien.colorstudy.net> I know this is getting off topic (or at least into another language), but I am weak and my ego does not allow me to let you tell me I am wrong when I am not ;-) On Wed, 2002-07-31 at 15:16, James J. Besemer wrote: > > Ian Bicking wrote: > > > Well, it looks a lot like lambda calculus, because True and False are > > two different classes, with definitions like: > > > This should remind one of true/false in lambda calculus (though > > obviously with a very different notation). > > Narrowly interpreted, there is a similarity, in that both systems > build up their "control flow" abstractions from True and False, > as opposed to, say, COND. Further, they both define True > and False in terms of each language's fundamental abstraction > mechanism, class definitions in Smalltalk's case and and Lambda > expressions for Lambda Calculus. You really can't see the similarity? In lambda calculus (in Python syntax): True = lambda t, f: t() False = lambda t, f: f() Translating traditional Python: if something: # Where something is True or False, nothing else doA() else: doB() In lambda calculus: something(doA, doB) That is, "if" becomes a function call, where true evaluates the first argument, and false evaluates the second argument. Obviously, you need a better lambda syntax to do this nicely, but the lambda calculus is still possible to implement in Python. So trueness or falseness is an object/function that reacts in a certain way -- calling the first function/argument if true, calling the second if not. This is exactly how Smalltalk works. You have to write ifTrue:ifFalse: instead of parenthesis, but that's incidental. If you pass that message to a True object, if evaluates the first argument/block, if you pass it to False it evaluates the second. Traditional control structures have a Mind that looks upon the conditional value, and decides what to do next based on it. In lambda calculus, true/false *is* the Mind, there is no outside logical force directing computation. At least, that's how I see the essence of the distinction -- in this way Smalltalk is like the lambda calculus (or at least pretends to be -- in fact the VM is actually the Mind just like always, at least for true and false values). > > That is, you can't (usefully) implement ifTrue: in your own custom > > class. > > Absolutely not true. I really don't know about anything but Squeak, but it's absolutely true in Squeak (even more annoyingly you can't reimplement to:do:, but that's another issue). I have gotten the impression that other implementations of Smalltalk act the same way. This isn't true of most other control structures in Smalltalk/Squeak, just ifTrue:ifFalse: and maybe a handful of others (ifNil:?) It means that: x ifTrue: [a] ifFalse: [b]. y gets compiled into something like (very rough bytecode): push x (if popped value is True) goto loop_a else goto loop_b # (if popped value is True) being a primitive bytecode loop_a: a goto loop_y loop_b: b loop_y: y That is, the ifTrue:ifFalse: message is never passed to x, and no closure is created for [a] and [b]. (And, of course, if you did something like "x ifTrue: a ifFalse: b" it'll compile slightly differently) You'll never notice this unless you try to implement an ifTrue:ifFalse message in your custom class. If you do, and you try to use it, you'll find it doesn't work like you'd have expected (it'll should cause an error). This does *not* happen for messages like do: or whileTrue, which are not optimized in this way. Ian From vovka_foreverREMOVE_THIS at hotmail.com Sun Jul 21 17:17:38 2002 From: vovka_foreverREMOVE_THIS at hotmail.com (Vladimir Cherepanov) Date: Mon, 22 Jul 2002 01:17:38 +0400 Subject: XML with Python - supposed to be simple? ;) References: Message-ID: "Martin v. Loewis" wrote in message news:m3it38lsxm.fsf at mira.informatik.hu-berlin.de... > "Vladimir Cherepanov" writes: > > > As a complete newbie to both XML and Python, I've been trying to > > create (any!) XML document using DOM API in PyXML package. Very > > simple task isn't it? > > No, XML is difficult; it becomes more difficult the closer you get to > it. > > Creating documents with DOM is indeed tricky. I recommend that you use > plain print statements, like > > print "" Well, creating XML document wasn't my ultimate goal - in that case, C runtime and "fprintf()" would do nicely ;), and I wouldn't be needing such heavy machinery as Python and DOM. What I was trying to do was the following: 1. Start learning DOM with the most basic problem. 2. Get some coding experience with Python. I skimmed through some w3c documentation on DOM, but didn't find anything about creating documents, apart from the statement that "it's implementation-specific" (why?!). Most w3c documentation concerns more advanced topics like XML parsing, etc. > You'll then learn that you can create > Document instances by invoking createDocument on the > DOMImplementation. For minidom, you get the DOM implementation by > calling xml.dom.minidom.getDOMImplementation(). Thanks, I'll try this. Btw, I didn't find this method in DOMImplementation Interface - the only method I found was "hasFeature()". And what about serializing? From cris at udm.ru Sun Jul 7 06:22:10 2002 From: cris at udm.ru (cris) Date: Sun, 7 Jul 2002 14:22:10 +0400 Subject: òÁÓÓÍÏÔÒÀ ÌÀÂÙÅ ÐÒÅÄÌÏÖÅÎÉÑ Message-ID: ?????? ????????? ?????? ??? ?? ?-?. ????????? ? ???????????? ??????? ??? ??????. ??\?? ??????, ???????, ??????. ???????? ??????? ?????????. ????????? ????? ???????????, ? ???? ???????????. ?????? cris at udm.ru From 102030405 at gmx.net Thu Jul 11 15:17:20 2002 From: 102030405 at gmx.net (Ralf Claus) Date: Thu, 11 Jul 2002 21:17:20 +0200 Subject: writing output to file References: Message-ID: "Allan Wermuth" schrieb im Newsbeitrag news:agklgl$rvu$1 at news.net.uni-c.dk... > Inspired by an existing Perl script, I wrote this chunk of code, but instead > of > writing the result to the screen, I would like to write output to a another > file. > > #!/usr/bin/python dat=open('test.txt','w') > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue > > temp = line.split(':') > if int(temp[2]) > 100 : > print "%10s %30s" % (temp[0], temp[4]) out="%10s %30s" % (temp[0], temp[4]) dat.write(out) dat.close() > > How can I do that? > It's possibly quite simple, in Perl it is ;-) , but I am trying to learn > Python, so > I would appreciate if someone would help me out. > > /Allan Wermuth > > > From talsit at talsit.org Wed Jul 31 08:57:26 2002 From: talsit at talsit.org (tALSit de CoD) Date: 31 Jul 2002 22:57:26 +1000 Subject: Debug version crashing... References: Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote in news:m3heig4cbi.fsf at mira.informatik.hu-berlin.de: Fatal Python error: Interpreter not initialized (version mismatch?) > > Could it be that you are loading python22.dll instead of > python22_d.dll? > > Regards, > Martin > No, it's using an linked to the python22_d.dll. At least, that's what is says in the dependancy walker (depends)... From aleax at aleax.it Thu Jul 11 03:21:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 07:21:47 GMT Subject: Why self? References: Message-ID: David LeBlanc wrote: > Louis; > > I think he was proposing an idea. I don't believe you can import from > self, You can, but of course you'll get stuff from a module such as self.py or an object that's already in sys.modules['self']. The latter could be an instance of a peculiar class, so it WOULD be possible to play very dirty tricks -- a __getattr__ method that looks into the caller's locals for a variable named 'self' and delegates the attribute requests to it. Very, VERY dirty:-). > and i'm almost positive that "to ... export" isn't part of Python. Right, that syntax can't be made to work, but the semantics are easy. Sometimes I tire of writing a gazillion boilerplatish self.somename = somename and take a shortcut, e.g. in the currently online version of YAPTU, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305 , there's a: def __init__(self, regex=_never, adict={}, restat=_never, restend=_never, recont=_never, preproc=identity, handle=nohandle, ouf=sys.stdout): "Initialize self's attributes" self.regex = regex self.globals = adict # etc, etc, ETC, ... ad nauseam ... but for the printed version I changed __init__'s body into: def self_set(**kwds): self.__dict__.update(kwds) self_set(**vars()) a "bit" sloppier (sets self.self which in turn makes a loop... that, at least, could be specialcased away in self_set!-) but half a page shorter. Boilerplate is error-prone -- whenever you (e.g.) change an argument-and-attribute's name, the boilerplate version forces you to change it in at least three places... the kind of mindless boring task that in the long range produces numerous silly little errors. Alex From e.d.andersen at mosek.com Sun Jul 21 06:21:09 2002 From: e.d.andersen at mosek.com (edadk) Date: 21 Jul 2002 03:21:09 -0700 Subject: ssh and Python Message-ID: Hi, There is a telnet and ftp object for Python. But how about ssh? I would like to write script that using ssh automatically execute commands commands on a remote machine. How can I do that? Erling From pinard at iro.umontreal.ca Mon Jul 8 15:24:42 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 15:24:42 -0400 Subject: stackless python In-Reply-To: <20020708102618.A4681@glacier.arctrix.com> References: <20020708102618.A4681@glacier.arctrix.com> Message-ID: [Neil Schemenauer] > Here's tow examples: > http://aspn.activestate.com/ASPN/Mail/Message/602876 > http://aspn.activestate.com/ASPN/Mail/Message/602993 > They need to be updated to use generators as they are now implemented. Other pointers I'll follow. Thanks! (My main question, maybe already answered in there -- I did not check yet -- is how one proceeds to `yield' from within a nest of function calls, and to later kludge resuming the function nesting sequence on `.next()'.) P.S. - Smiley mode on. I read "tow" in the quote above and surely, this is a typo. But I wonder if it is a typo of "two" or a typo of "toy". :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From fperez528 at yahoo.com Fri Jul 19 18:14:21 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 19 Jul 2002 16:14:21 -0600 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: Rhymes wrote: > > When Python 2.3 will be released? > > I've read the "what's new" and i'm waiting generators and true > division :-) ... both of which are available in 2.2 with a from __future__ directive. f. From h_j_fong at hotmail.com Sun Jul 28 12:50:38 2002 From: h_j_fong at hotmail.com (Chris) Date: 28 Jul 2002 09:50:38 -0700 Subject: wxRadioButtons logic (2 Qs) Message-ID: <1d2e2585.0207280850.95fe6a0@posting.google.com> Hi there, I've got 2 questions for a GUI I'm writing. Checked Google, Google groups, and wxPython demo - no luck. 1. Is there some way to get the logical binding of buttons found in RadioBox, but the flexibility of button positioning found in RadioButton? I want two sets of irregularly spaced RadioButtons, and it seems it should be possible to somehow bind the IDs into sets; otherwise if I want to use different sets of exclusive buttons, it seems I'm contrained to a grid layout as in RadioBox. If I use RadioButtons as is, all four buttons are considered one mutually exclusive set. Alterntively, perhaps RadioBox has more felxibility than I understand. 2. Is it possible (I know it is...) to dynamically change my window as the user inputs information? For example, imagine two radio buttons "books" and "movies". Then a second set of buttons, heretofore present but blank, might be labeled "fiction"/"nonfiction" or "color"/"b&w" depending on his/her first choice. Presumably there is some way to seamlessly refresh the window, or overwrite a sizer with another. Just some advice about where to start reading would be helpful, although a demo/snippet might be nice as well :-). Thanks a bunch, expyrts, Chris From marklists at mceahern.com Fri Jul 5 11:01:50 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 5 Jul 2002 10:01:50 -0500 Subject: Why self? In-Reply-To: Message-ID: > Other than in an obfuscated python contest, I can't think of any reason > why anybody would *ever* use any variable name other than "self" as the > first formal parameter of a method. > > Have you ever seen an example that does? iirc, one time this topic came up, someone was all vehement about how their use of "me" was preferable due to it saving two characters. whatever. // m - From sandysj at juno.com Wed Jul 31 12:52:38 2002 From: sandysj at juno.com (Jeff Sandys) Date: Wed, 31 Jul 2002 16:52:38 GMT Subject: alternatives to getopt? References: Message-ID: <3D4815D6.7421A174@juno.com> Use mkpythonproj by Harry George. Use it when you start a module and it will put in the boilerplate getopt methods. http://www.seanet.com/~hgg9140/comp/ Francisco Borges wrote: > Hi all, > I've just started using getopt and I'm not very fond of it. > Is there a better alternative to it? From pyth at devel.trillke.net Thu Jul 4 16:52:19 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 4 Jul 2002 22:52:19 +0200 Subject: [OT] What is Open Source? (fwd) In-Reply-To: ; from mertz@gnosis.cx on Thu, Jul 04, 2002 at 01:24:38PM -0400 References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> Message-ID: <20020704225219.O10625@prim.han.de> David Mertz, Ph.D. wrote: > |mertz at gnosis.cx (David Mertz, Ph.D.) writes: > |> The only problem with this belief is that it is completely, totally, > |> 100% wrong. A copyright is, quite simply, a legally enforced artificial > |> monopoly--not a contract. These are quite different things. > > Paul Rubin wrote previously: > |I think Clark was using contract in a metaphorical sense, describing a > |deal made with authors on one side, and society as a whole on the > |other. In what's called the "copyright bargain", society agrees to > |grant limited temporary monopolies, in exchange for increased > |"progress in science and the useful arts". > > Well... I suppose Clark's use is a metaphor. But it is an extremely > *bad* metaphor, one that does far more to conceal what's going on than > reveal. > > Here's a better one: Copyright is like blue cheese. (OK, I guess you > can say it's a simile, since it uses 'like'). I admit this isn't a very > -good- metaphor (but both are, indeed, smelly and created by molds > :-)... but I *like* blue cheese, so there's a flaw... well, maybe not, > since both are bad for me). Always helps to have a gnostic tasteful philosopher around :-) holger From loewis at informatik.hu-berlin.de Thu Jul 25 11:06:37 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 25 Jul 2002 17:06:37 +0200 Subject: distutils gcc unix References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp> Message-ID: Michiel Jan Laurens de Hoon writes: > It is possible to specify which compiler distutils should use? You need to set the CC environment variable. HTH, Martin From marklists at mceahern.com Tue Jul 30 11:01:02 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 30 Jul 2002 10:01:02 -0500 Subject: How to execute an external binary reading from standard in In-Reply-To: <3D46A6FC.AA068BC8@iki.fi> Message-ID: > How to execute a exeternal (binary) program reading from standard input > in a python code ? > For example : /home/mok/my_prog.bin < my_input.txt > > My system is Linux and the binary is written originally in fortran 90 > (if that should matter). > > I tried > os.popen('/home/mok/my_prog.bin < my_input.txt ') > with no success Have you looked at popen's cousins? popen2, 3, 4, etc? Cheers, // mark - From aleax at aleax.it Wed Jul 24 10:32:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 14:32:12 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: Bo M. Maryniuck wrote: ... >> > for line in open(filename): >> > count += 1 > > In anyway this example probably does not work: looping over not sequence > and you probably should use xreadlines(). Not with today's Python, 2.2.* -- looping over files and dicts is perfectly well supported today (and since 7 months ago)... Alex From gv at cs.uu.nl Wed Jul 24 08:36:04 2002 From: gv at cs.uu.nl (Gerard A.W. Vreeswijk) Date: Wed, 24 Jul 2002 14:36:04 +0200 Subject: Function wrapper a la Perl's Hook::WrapSub? Message-ID: <3D3E9F34.90FB8B3F@cs.uu.nl> Hi there, I very much would like to have a Hook::WrapSub (Perl) module for Python. What does it do? Well, read http://de-filippis.com/h/Hook-WrapSub-0.03.readme.shtml :-) Or, if that one's dead, http://cpan.lerner.co.il/modules/by-category/20_Control_Flow_Utilities/Hook/Hook-WrapSub-0.02.readme In a nutshell, a subroutine (or function, or def) wrapper enables intercepting a call to any named function; handlers may be added both before and after the call to the intercepted function. My example: ========================================================== #!/usr/bin/perl use Hook::WrapSub qw( wrap_subs ); # import module wrap_subs \&before, 'f', \&after; # execute 'before' before 'f' and 'after' after 'f' sub f { # some pointless recursive function my $arg = shift; return 2*f($arg-1) if $arg > 0; return 1 } sub before { print "Entering function $Hook::WrapSub::name with arguments @_\n"; } sub after { print "Exiting $Hook::WrapSub::name with result @Hook::WrapSub::result\n"; } f(5); ========================================================== Outputs: Entering function main::f with arguments 5 Entering function main::f with arguments 4 Entering function main::f with arguments 3 Entering function main::f with arguments 2 Entering function main::f with arguments 1 Entering function main::f with arguments 0 Exiting main::f with result 1 Exiting main::f with result 2 Exiting main::f with result 4 Exiting main::f with result 8 Exiting main::f with result 16 Exiting main::f with result ========================================================== I know that there is this magnifient trace.py-module by Skip Montanaro and Andrew Dalke but I don't have enough skills to rework that script into a inline function hook (rather than as a standalone tracer, like trace.py is) Further, I suspect that a Python Hook::WrapDef can be distilled from trace.py, but currently I do not have enough Python skills to figure out how. Anyone? Thanks. Gerard Vreeswijk From squelart at hotmail.nospam.com Mon Jul 29 20:34:49 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Tue, 30 Jul 2002 10:34:49 +1000 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> <3d438609$1@duster.adelaide.on.net> <3d439616$1@duster.adelaide.on.net> <2259b0e2.0207280652.202f1721@posting.google.com> Message-ID: <3d45df2a$1@duster.adelaide.on.net> "Steve Holden" wrote > "Michele Simionato" wrote > > why Guido decided to keep > > the distinction between statements (with no value returned) and > > expressions ? what are the advantages ? is it a matter of personal > > taste ? > He made that decision for the same reason he decided not to allow > assignments inside expressions. You can find the justification in the FAQ if > you look for it ... 6.30: Why can't I use assignment in an expression. Static FAQ is there: http://www.python.org/doc/FAQ.html 6.30 is there: http://www.python.org/doc/FAQ.html#6.30 However, as you point out, 6.30 is 'Why can't I use an assignment in an expression?', whereas the question asked here is 'Why is there a distinction between statements and expressions?'. You write 'He made that decision for the same reason...'; how do you know this? I had a quick look, but didn't see anything about the question asked by Michele. It may be a good thing to add to the FAQ... Cheers, Gerald. From fredrik at pythonware.com Mon Jul 22 11:26:16 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Jul 2002 15:26:16 GMT Subject: xmlrpclib question References: <3D3BFA10.92E38B5B@millfilm.co.uk> Message-ID: Eric Texier wrote: > I posted this question earlier but I am still confuse about what > I am doing wrong. Why, in the class 'clientRootTask' just taking > out the 'if' statement will make it work: what did you expect that if statement to do? as written, you're asking the server if it's "true". to figure that out, Python calls the proxy object's __nonzero__ method, which the proxy happily forwards to the server. maybe you meant "if server is not None"? From corrada at ciirsrv.cs.umass.edu Thu Jul 18 14:37:37 2002 From: corrada at ciirsrv.cs.umass.edu (Andres Corrada-Emmanuel) Date: Thu, 18 Jul 2002 14:37:37 -0400 (EDT) Subject: How to set tempfile.tmpdir? In-Reply-To: <200207181752.g6IHqLZ07190@localhost.localdomain> Message-ID: Duh! Thank you. Andres Corrada-Emmanuel Senior Research Fellow Center for Intelligent Information Retrieval University of Massachusetts, Amherst On Thu, 18 Jul 2002, Dave Reed wrote: > > From: Andres Corrada-Emmanuel > > > > Hi, > > > > I'm trying to use tempfile to generate a temporary filename in the > > directory of my chossing. I thought that this would work: > > > > import tempfile > > > > tempfile.tmpdir = '/my/path' > > temp_name = tempfile.mktemp() > > > > However, it doesn't. I'm working on SunOS and temp_name always comes back > > with /tmp/some_unique_identifier. > > > > What am I doing wrong? > > You're missing an e > > tempfile.tempdir='/my/path' > > Dave > > From nde at comp.leeds.ac.uk Fri Jul 12 08:06:33 2002 From: nde at comp.leeds.ac.uk (N D Efford) Date: Fri, 12 Jul 2002 12:06:33 GMT Subject: Recomendations on Books References: Message-ID: Ray Tux wrote: > Hello I am a beginer to programming and I have chose Python. I was just > wandering if you guys could recomend some good Python Beginers books. O'Reilly books are good - "Learning Python" would be the one you want. Check out also the "Learning to Program" book by Gauld, which uses Python. Gauld's stuff is available online, as is "How To Think Like a Computer Scientist". This is available for several programming languages, Python included. N. From gerhard.haering at gmx.de Wed Jul 24 17:54:46 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Wed, 24 Jul 2002 23:54:46 +0200 Subject: http to https forwarding In-Reply-To: References: Message-ID: <20020724215446.GA1847@lilith.my-fqdn.de> * David Iungerich [2002-07-24 16:44 -0500]: > Has anyone setup anything to implement the following scenario. I recently did a proof-of-concept: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import BaseHTTPServer import urllib2 FORWARD_URL_START = "https://sourceforge.net" class ProxyRequestHandler(BaseHTTPRequestHandler): def do_GET(self): f = urllib2.urlopen(FORWARD_URL_START + self.path) data = f.read() content_type = f.info()["Content-Type"] self.send_response(200) self.send_header("Content-Type", content_type) self.end_headers() self.wfile.write(data) def main(): BaseHTTPServer.test(ProxyRequestHandler) if __name__ == "__main__": main() > I need to do it, and fast. Was that fast enough? ;-) > I need to an http to https forwarder. My scenario is as follows: > > I have an appserver that needs to POST http requests to another > company's appserver. Unfortunately, the particular product we are > using has issues being able to send https, and the other company > requires it. They have issued us certificates to talk to them. For certificate handling you need something better than the standard Python SSL. Both PyOpenSSL or m2crypto can do certificates. Oh well, I promised to look into this and write a PEP, but was occopied with other stuff lately :-/ Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From nospam at bigfoot.com Thu Jul 11 06:32:36 2002 From: nospam at bigfoot.com (Gillou) Date: Thu, 11 Jul 2002 12:32:36 +0200 Subject: PyGPG References: Message-ID: Try searching from www.sourceforge.net I remember having seen a python gpg wraper there. --Gilles glenfant AT bigfoot DOT com "Ivica" a ?crit dans le message news: agjivb$e3l$1 at bagan.srce.hr... > I'm looking for PyGPG wrapper around gpgme ... the URL i found does > not work any more. Can any one tell me where to find them. > Tnx! From nicolas at otelnet.com Mon Jul 15 14:40:19 2002 From: nicolas at otelnet.com (Nicolas Duchastel) Date: 15 Jul 2002 11:40:19 -0700 Subject: loading of modules in jython 2.1 !? Message-ID: <8e0ac4fb.0207151040.2dd9ffef@posting.google.com> 3 questions about how to start JYTHON and where it reads module from. Any help would be greatly welcomed. I tried the FAQs and other resources and I never found anything. P.S. adding this to FAQ would be great: i.e. the reason I am posting now is that I often get these kinds of problems and always end-up trying a zillion things and "mysteriously" fixing it. I never understand why and how it got fixed (e.g. some times I simply copy a bunch of files to my local dir!!), and I am pretty sure that I am not the only one out there (i.e. cry for help! :)) Thanks, Nicolas -------------------------------- QUESTION: ======== 1- why is my local registry file (e.g. ~/.jpython) not read when I start script as: jython myfile.py but it does work if I do: ./myfile.py 2- when is the CLASSPATH (or PYTHONPATH) env variables used by jython; if it is ever used !? 3- why do I get different results depending if I start script directly or by 1st calling jython !? e.g. "jython myfile.py" is different than "./myfile.py" DETAILS ======= I have a jython file called: myTestCase.py. It is executable and has as it's first line of text: #! /usr/bin/env/ jpython It use a bunch of utilities that we have written; these are all found under some directory called /export/home7/Tools/CSP/train/OTelCORE/lib: e.g. util.py (yeah! I know, its not a great name! :)) results.py ... I have different behaviours based on how I call this script; and I don't know why. Can anyone help. a) ./myTestCase.py -> doesn't work Traceback (innermost last): File "./myTestCase.py", line 12, in ? File "/export/home7/Tools/CSP/train/OTelCORE/lib/util.py", line 8, in ? AttributeError: java package 'org.apache' has no attribute 'oro' that's because util.py has line 8 which reads: from org.apache.oro.text.regex import * I then add the path to my Jython 2.1 distribution and I now get another error: Traceback (innermost last): File "./1.2-sendOneMsg.py", line 12, in ? File "/export/home7/Tools/CSP/train/OTelCORE/lib/util.py", line 8, in ? TypeError: can not dir a java directory package I have a ~myuser/.jpython file which has the proper "python.path" stuff to point to /export/home7/.../lib. I know that this file is read since when I change another property such as "python.verbose", the display does change!! b) if I try by using jython directly -> does work, but needs lots of work! i.e. jython ./myTestCase.py it first complains that it can't find 'results.py': i.e. that's a module which was loaded BEFORE util.py!!! It worked before!! import: 'results' not found (ImportError) Traceback (innermost last): File "1.2-sendOneMsg.py", line 10, in ? ImportError: no module named results It seems that this time around my registry information at ~myuser/.jpython is completely ignored (i.e. I don't get the verbose stuff on the display). WHY IS THAT !? Anyway, if I had the extra dir to my classpath: setenv CLASSPATH "${CLASSPATH}:/export/home7/..../lib" I still get the same thing! i.e. can't find the results.py (or the util.py I would guess) even though the previous one did !! The only way I get it to work is if I do: jython -Dpython.path=/export/home7/Tools/.../lib ./myTestCase.py From maxm at mxm.dk Mon Jul 15 03:00:50 2002 From: maxm at mxm.dk (Max M) Date: Mon, 15 Jul 2002 09:00:50 +0200 Subject: Open document formats References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: <3D327322.5000006@mxm.dk> .doc is the most common file format there is outside of html/txt so naturally anybody who has customers that lives in an MS world must be able to read it. Which means most of us. Publishing/reading in ps/pdf is rather easy for *nix types and Publishing/reading in .doc is easy for Windows types, so it is very much a matter of taste which format you use. I use Open Office with only small problems for reading/writing .doc. Sometimes the pages are not formatted correctly but I can allways read the text. But the fact is that it is pretty painless with open/free software. So I believe there is a good argument for publishing in .doc instead of .ps or .pdf, especially if the target audience is bussiness people. But on the other hand if something is meant to be published on the net it is a very bad idea not to convert it to html. I rarely bother to open something that my browser doesn't open natively like txt/html. If I do it is allways a major work like an online book or somesuch, never a "single page" document. regards Max M From edream at tds.net Wed Jul 10 10:22:40 2002 From: edream at tds.net (Edward K. Ream) Date: Wed, 10 Jul 2002 14:22:40 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> Message-ID: <3D2C432E.5FEDD75E@tds.net> Gerhard Haering wrote: > I've no idea about Tkinter at all, but this should accomplish what you > need: > > command=lambda: self.myCallback(val) Thanks very much. That did the trick. I've been wondering how to define lambda expressions with no args ;-) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From gerhard.haering at gmx.de Fri Jul 19 13:54:42 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 19 Jul 2002 17:54:42 GMT Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: In article , eugene kim wrote: > hi.. > i'm trying to parse a xml file and feed into postgresql... > the xml file contains korean.. > is this python problem or postgres problem? An understanding problem. I don't need to read the rest of your message because there's exactly one reason for the error message in the subject: you're trying to convert a Unicode object into a string object and don't provide the encoding to use. For example if you want to convert Unicode into an utf-8 encoded string, you can do something like: x = unicode("?sterreich", "iso-8859-1") # create a Unicode object print x.encode("utf-8") # convert it into a Python string > sqlclause = 'INSERT INTO history VALUES (' + tmp + self.url + tmp +","+ > tmp + self.title + tmp + "," + self.firsttime + "," + self.lasttime + "," + > self.visits + " )" Also it's not advisable to create SQL strings yourself. It's much better to use a DB-API module like pyPgSQL, psycopg (or even PyGreSQL's pgdb ;-) and let the database module quote your parameters: ... cursor.execute("insert into history (col1, col1, col3) values (%s, %s, %s)", (self.url, self.title, self.firsttime)) This will use the proper quoting of the parameters (escape apostrophes, etc.). For pyPgSQL, there's even a patch waiting for testers that will allow you to use Unicode strings here. For now you'll have to encode your Unicode strings that you get from parsing the XML into Python strings of your favourite encoding. > import _pg I'd recommend to stay away from low-level modules with underscores in front. PyGreSQL (if you want to use it) has a DB-API wrapper in the pgdb module. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From jhefferon at smcvt.edu Sat Jul 13 12:52:26 2002 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 13 Jul 2002 09:52:26 -0700 Subject: Pros/cons of various PostGres modules Message-ID: <545cb8c2.0207130852.74d88a5@posting.google.com> Hello, I'm starting on a project that will have Python interfacing with PostGres. I see that there are now four modules listed on the Python web site. I'd be very interested in any suggestions as to which ones are best. I've used PyPgSQL with good luck in the recent past. But there are two that are newer that are thread safe. Will I notice on a moderately-loaded application? Are they debugged? Is one faster than the others? Any other experiences? They all look good to me! Thanks, Jim Hefferon From tim at vegeta.ath.cx Tue Jul 9 07:02:53 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: 9 Jul 2002 04:02:53 -0700 Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: Alex Martelli graced us by uttering: > Tim Hammerquist wrote: > ...[snipped lots of intense agreements]... >> Trusting a language structure to protect against malicious or >> simply incompetent users is bad design, and is likely to inhibit >> flexibility. > > Not too sure I agree fully with THIS point. I don't cling to it zealously, either. It's mostly a wordy way of saying: clean-compile != correct-program. IOW, you can't determine program quality by the number of errors it generates. =) [ snip ] > Regarding _accidental_ misuse, i.e., errors, having the compiler do > more checks does help a bit -- if nothing else, you learn about such > errors a few seconds earlier, and that must be worth SOMEthing (as > long as it doesn't lull you into a false belief that therefore you > don't need code inspections and unittests -- of course you do, no > compiler will catch a typo such as + where you meant -, and that can > be a disaster!-). Agreed. Syntax checking and similar measures go farthest in catching simple mistakes, such as Perl's 'use strict' pragma. This is what they were intended for, right? But similar to above, what the program does and what the programmer means are all too often different. =) [ snipped thoughtful analysis ] > Alex I think I'm vaguely on the same page with you. But whether I can put the thoughts in my head clearly onto paper, er, rather, into words, is another matter entirely. =) Tim Hammerquist -- > (It's sorta like sed, but not. It's sorta like awk, but not. etc.) Guilty as charged. Perl is happily ugly, and happily derivative. -- Larry Wall in <1992Aug26.184221.29627 at netlabs.com> From markus.vonehr at ipm.fhg.de Mon Jul 1 07:41:16 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 01 Jul 2002 13:41:16 +0200 Subject: dynamic buttons with tkinter References: Message-ID: <3D203FDC.C88779F7@ipm.fhg.de> Dear Mirko, use a lambda function as command for the button and pass a name or number to that function, this is a way to identify the clicked button: for file in os.listdir( dir ): tmp_func_load = lambda index=0, obj=self: obj.load(file) Button( load_dlg_frame, text=file, relief=GROOVE, command=tmp_func_load).pack() def load(self, filename): pass I pack the whole stuff into a class, that's the reason for the selfs, but it works without it, too. Markus Mirko Koenig schrieb: > Hi > > In my i want to make a button for every file > in a special directory, so that i can load it. > I did: > > for file in os.listdir( dir ): > Button( load_dlg_frame, text=file, relief=GROOVE, > command=load).pack() > > But how can i find out which button is pressed? > Or another question: How can i pass a event funktion more than 1 > parameter (the event and other things). > I can't give any button a new event function, because it's dynamic, > because of the number of files in the directory. > > thanx > > Mirko From ianb at colorstudy.com Tue Jul 30 14:46:16 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 30 Jul 2002 13:46:16 -0500 Subject: Let's Talk About Lambda Functions! In-Reply-To: References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: <1028054777.837.766.camel@lothlorien.colorstudy.net> On Tue, 2002-07-30 at 11:05, John Roth wrote: > I tend to agree with you on that one, but it's a matter of style. I > observe > that e.g. Smalltalk style does anonymous code blocks all over the place. I've seen people argue that you can do all the same things with iterators as Smalltalk does with code blocks. And, really, it's not as though Smalltalk has truly novel control structures -- everything still boils down to while, for, and if. Smalltalk does give you easy callbacks, though. > There's no reason my proposal couldn't be extended to anonamous > classes: the syntactic issues are exactly the same. The difficulty is > in extending it to methods, as opposed to functions. The only way > to distinguish a method from a function today is to observe that > methods are defined at the top level of a class; a def anywhere > else is a function (I think.) A method is just a function that is bound to a class variable. So you can do something like: class X: pass X.func = lambda self, x: x * 2 x = X() x.func(10) ==> 20 In fact, you can even do: class X: func = lambda self, x: x * 2 Ian From tebeka at cs.bgu.ac.il Sun Jul 14 03:11:25 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 14 Jul 2002 00:11:25 -0700 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: Message-ID: <33803989.0207132311.7fd3607d@posting.google.com> Tim Peters wrote in message news:... > The value of an aphorism is in provoking you to ponder. So long as you > suspect there's something of value in it that you don't yet understand, it's > doing its job. As soon as someone thinks they understand it, and then just > repeats it (whether to endorse or ridicule doesn't much matter) in lieu of > contemplation, its usefulness is exhausted. I agree. However I wanted some other opinions. I got more than I've imagined. > I suspect that's why God always > arranges to get himself killed whenever he takes on human form . Or maybe it's the only way back up :-) > I've read that if you confine too many rats in too small a living space, > they become sociopathic. That's density for you. I've seen no reason to > suspect that code, concepts, data structures, interfaces, programmers or > managers have an advantage over rats in this respect. Give yourself some > room to breathe and stretch: couple interfaces loosely, let a subsystem > deal with a little rather than a lot, leave a little whitespace for flowers > to grow between tokens, fail soft on feathers instead of hard on rocks, > don't do two things at a time until you're pretty sure you can do one, a > function with 14 arguments-- or a module with 14 classes --is a bad idea, > don't fall for the idea that between any two abstractions you always need to > compromise on a third. Etc. > > In other words, sparse is better than dense. Except when it comes to chip > design, where sparseness plain sucks . > > pythons-swallow-rats-one-at-a-time-ly y'rs - tim I prefer something else on my plate. Thanks. Miki From spyglass106 at yahoo.com.au Wed Jul 24 08:38:06 2002 From: spyglass106 at yahoo.com.au (Jolly Roger) Date: 24 Jul 2002 22:38:06 +1000 Subject: GUI toolkits References: Message-ID: <85adoh5mj5.fsf@axis.localdomain> Alex Martelli writes: > Dunno 'bout the license situation though -- I'm pretty sure you're > OK with GPL for Qt-using stuff on (e.g.) Linux, Definitely. > but on Windows it > might be different (alas, Trolltech's license lawyers have weaved a > thick thicket there, sigh). I think Windows software using Qt ("non-commercial") can be distributed under BSD or LGPL (or similar) license, but not under the plain unmodified GPL. If GPL is a must, it's possible to add a clause to the GPL which, I think, exempts the recipient of the software from having to redistribute Qt source code with the application. Something like that anyway. From gtaylor at lowebroadway.com Mon Jul 8 11:02:54 2002 From: gtaylor at lowebroadway.com (Garry Taylor) Date: 8 Jul 2002 08:02:54 -0700 Subject: Multi-threading on Multi-CPU machines Message-ID: Hello, I am attempting to make a multi-threading function in one of my programs in an effort to gain a speed increase, but I'm getting quite the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten me as to why, my code is below: -------- import thread import time ThreadCounter = 0 Iterations = 100 def Threader(): global ThreadCounter global Iterations Counter = 0 temptime = time.time() while Counter < Iterations: Counter = Counter + 1 thread.start_new_thread(TakesTime,()) while ThreadCounter < Iterations: pass print "Threaded: "+str(time.time() - temptime) def TakesTime(): global ThreadCounter Text = "Test" Counter = 0 while Counter < 20: Text = Text + Text Counter = Counter + 1 ThreadCounter = ThreadCounter + 1 def NoThreader(): global Iterations temptime = time.time() Counter = 0 while Counter < Iterations: Counter = Counter + 1 TakesTime() print "Non-Threaded: "+str(time.time() - temptime) Threader() NoThreader() -------- This does the same thing, threaded and then not, but on all of my machinbes, the multi-threaded is slower, what can I do about this? Thanks garry From claird at starbase.neosoft.com Thu Jul 11 08:54:20 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 11 Jul 2002 07:54:20 -0500 Subject: Python in the enterprise: Pros and cons References: Message-ID: <1C6211461DB80328.51DA5B9AE6161E41.D6F1B5526387FEFF@lp.airnews.net> In article , David LeBlanc wrote: . . . >My conclusion is that Python is entirely ready for the enterprise - and it's >already there! . . . I read Ms. Fraser's article more charitably than others who have been following up here. I thought she made clear that she's reporting on both tech- nical reality and organizational perception. So, for example, it doesn't matter (boy, can I testify it doesn't matter) that Python is, for example, as fast as Java, if a customer is incapable of retaining that fact. My main point, though, is to encourage the folks working on Pyadvocacy pages. In particular, yes, it's absolutely true that Python is already in the enterprise, and thriving. I know, for example, of companies which provide goods and services at rates of over a million customer-contacts per month, in which Python plays a central role. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From see_reply_address at something.invalid Thu Jul 4 20:37:01 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 12:37:01 +1200 Subject: creating a file from python References: Message-ID: <3D24EA2D.9050505@something.invalid> > gollem wrote: > >> I want to create a file from inside a running python script. >> I can do that using commands and touch but it won't work if the intended >> name of the file is the value of a python variable. You mean you just want to create an empty file? This will do it: filename = "some_file_name" f = open(filename, "w") f.close() Names of your Python variables don't come into it at all. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From shalehperry at attbi.com Sat Jul 6 15:54:38 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 06 Jul 2002 12:54:38 -0700 (PDT) Subject: problems with a for loop (noobie) In-Reply-To: Message-ID: On 06-Jul-2002 Charles Mantha wrote: > >> > ps : and for some reason, the output is not the same as in the tutorial >>> when >> > I try this. >> >> This is kind of hard to explain if we don't see the output that you saw. >> Are you certain you typed it exactly as it appeared in the tutorial >> (including indentation)? > > This is what I get : > > for n in range(2, 10): > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > # loop fell through without finding a factor > print n, 'is a prime number' > the 'else' belongs to the 'for' not the 'if'. Observe: >>> for i in (1,2,3): ... print i ... else: ... print "finished" ... 1 2 3 finished the else is reached when the for finishes UNLESS a break was used to stop the for loop early. From sandysj at juno.com Mon Jul 22 11:11:51 2002 From: sandysj at juno.com (Jeff Sandys) Date: Mon, 22 Jul 2002 15:11:51 GMT Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: <3D3C20B7.93D94300@juno.com> When will O'Reilly give us _Regular Expression Pocket Reference_? Thanks, Jeff Sandys David LeBlanc wrote: > > Book. It's out. From O'Reilly. See > http://www.oreillynet.com/pub/a/network/2002/07/15/regexp.html > > Claims extensive Python re coverage. In addition to the other usual > suspects, also covers Java, Ruby, php and .net. > > Hope it's as good as the first one was/is! > > David LeBlanc > Seattle, WA USA From mwh at python.net Thu Jul 18 05:56:01 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Jul 2002 09:56:01 GMT Subject: slicing and parallel assignment: inconsistent behaviour?? References: Message-ID: tjd at sfu.ca (Toby Donaldson) writes: > Hi, > > I was hoping someone might be able to help me with a problem I've run > into with slices and parallel assignment. I want to swap to segments > of a list. For instance: > > >>> B = range(10) > >>> B[1:5], B[5:10] = B[5:10], B[1:5] > >>> B > [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] > > This works as I expect. But if I leave out the 10s in the slice > indices, I get this: > > >>> A = range(10) > >>> A[1:5], A[5:] = A[5:], A[1:5] > >>> A > [0, 5, 6, 7, 8, 1, 2, 3, 4] > > Where has the 9 gone? It got stomped by the assignment to A[5:]. Writing this out long hand may be clearer: >>> A[1:5] = t[0] >>> A [0, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] >>> A[5:] [9, 5, 6, 7, 8, 9] >>> A[5:10] [9, 5, 6, 7, 8] So you can see that A[5:] = t[1] and A[5:10] = t[1] are going to have different effects. Cheers, M. -- ZAPHOD: Listen three eyes, don't try to outwierd me, I get stranger things than you free with my breakfast cereal. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From fredrik at pythonware.com Sun Jul 14 12:27:26 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Jul 2002 16:27:26 GMT Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: ppcdev wrote: > i was working on an old pentium II and wanted to send a very long > string in the USER parameter but it made my computer bug.. is it > normal??? > > str='a'; r=range(1024); > for x in r[:]: > str=str+str > > but it even bugs with a value of 512 and 256 for r=range(..) hint: len = 1L for x in range(1024): len = len + len print len prints 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814 416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586 298239947245938479716304835356329624224137216 do you have that much memory? (if you want to create a 1024-character string, use 'a'*1024) From sholden at holdenweb.com Mon Jul 1 10:21:08 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 10:21:08 -0400 Subject: M2Crypto: select() behaves weird on SSL sockets References: <3D04ED17.5070606@NOSPAMREMOVETHISxs4all.nl> <3D066E77.4070901@NOSPAMREMOVETHISxs4all.nl> <3D0790E1.9080904@NOSPAMREMOVETHISxs4all.nl> <831ybavprx.fsf@panacea.canonical.org> <3D0919AF.7050903@NOSPAMREMOVETHISxs4all.nl> <83it45lxfb.fsf@panacea.canonical.org> <3D1B92A2.7030605@NOSPAMREMOVETHISxs4all.nl> <837kkgj94h.fsf@panacea.canonical.org> Message-ID: "Kragen Sitaker" wrote ... [...Zope discussion...] > > I think Irmen was asking, if the data handle_write is going to write > is generated in another thread, how does it get written to the output > buffer? Zope contains FIFOs, which look non-thread-safe to me but > seem to work, that carry the data between threads. Thanks for pointing this out. I was probably misinterpreting that part of the post. Now that you mention it, the data transfer mechanism between the producer thread and the asynchronous loop doesn't actually look completely thread-safe. It might be better to use a Queue rather than the home-rolled fifo in the code, but that might be a little expensive per-thread. Maybe asynchat needs a couple of code revisions as well as some documentation ... regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From ama at esss.com.br Tue Jul 16 13:58:50 2002 From: ama at esss.com.br (Alexandre Motta de Andrade) Date: Tue, 16 Jul 2002 14:58:50 -0300 Subject: =?iso-8859-1?Q?RE:_how_i_use_'=E3'_in_python=3F=3F=3F?= In-Reply-To: <3D343570.7000202@o-x.ch> Message-ID: <000001c22cf2$71190c90$1b00000a@esss.com.br> Hi there! Well, my solution for this problem was UNICODE. Python has a good support for UNICODE characters and with them you can use brazilian 'accents' and any other special character from other languages too. There is a nice UNICODE and CODECs tutorial in this link: http://www.reportlab.com/i18n/python_unicode_tutorial.html Good luck! []'s ama Alexandre Motta de Andrade Software Developer - ESSS ama at esss.com.br -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Florian Eggenberger Sent: Tuesday, July 16, 2002 12:02 To: python-list at python.org Subject: Re: how i use '?' in python??? jubafre at zipmail.com.br wrote: > i?m brazilian, and in my laguage(Portguese) there are many other caracters > how ?, ?, ? and a string in python doesn?t support this > how i can use??? have a import module for this??? > > BRASILEIROS DA LISTA COMO VCS CONSEGUEM USAR ACENTO NO PYTHON?? > > for exmple: > s='?' > doesn?t work?why?? > > > Juliano Freitas > www.gebrasil.hpg.com.br > > > > ------------------------------------------ > Use o melhor sistema de busca da Internet > Radar UOL - http://www.radaruol.com.br > > > > > It's the same problem in german. i think it is not possible in the IDLE. i used hexcodes in the string to "solve" the problem. example: '\xE4\xF6\xFC\xC4\xD6\xDC]' -> ?????? not very good but it works for me. -- http://mail.python.org/mailman/listinfo/python-list From gerhard.haering at gmx.de Sat Jul 20 11:45:11 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 20 Jul 2002 17:45:11 +0200 Subject: Python 2.3 In-Reply-To: References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <1027175934.94979.0@iris.uk.clara.net> Message-ID: <20020720154510.GA1362@lilith.my-fqdn.de> * Rhymes [2002-07-20 17:13 +0200]: > Gerhard H?ring wrote: > >python-dev archives (http://mail.python.org/pipermail/python-dev/). > how much daily-traffic has this maillist? same as lkml or bugtraq's ? This question can easily be answered by looking at the above link. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From val at vtek.com Wed Jul 3 09:52:05 2002 From: val at vtek.com (val) Date: Wed, 3 Jul 2002 09:52:05 -0400 Subject: pipes.py and its limits Message-ID: Hi All, i'm looking at pipes.py, a great pipeline implementation in python (BTW, who is the author?), and trying to figure out its limits. The description says that the commands to be appended to the pipeline template have to be shell functions. I'd like to try to build the dynamic pipelines using the python functions or callable objects. In other words, i'd like to modify the pipeline - its functional components on-the-fly depending on the results of running the pipeline (its output). I'm sure the real Pythoneers know how to do that. Any pointers/help would be highly appreciated. thanx, val From bh at intevation.de Mon Jul 22 14:21:53 2002 From: bh at intevation.de (Bernhard Herzog) Date: 22 Jul 2002 20:21:53 +0200 Subject: Python very slow on the Sharp Zaurus - any idea why? References: Message-ID: <6qy9c339oe.fsf@abnoba.intevation.de> "Anders J. Munch" writes: > Python uses floating point to check for integer arithmetic overflow. Not any more. This change was introduced in 2.1 IIRC. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From skip at pobox.com Thu Jul 18 18:53:17 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Jul 2002 17:53:17 -0500 Subject: i++ in Python? In-Reply-To: <5606b639.0207181429.2c6d2569@posting.google.com> References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <15671.18141.929136.241921@localhost.localdomain> otis> How does one do something like this in Python: otis> i = j++ That would be i = j j += 1 -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From baptism_of_fire_842 at hotmail.com Sat Jul 6 09:18:46 2002 From: baptism_of_fire_842 at hotmail.com (Mike Johnson) Date: 6 Jul 2002 06:18:46 -0700 Subject: idiots guide to python References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: <626290cd.0207060518.298744f2@posting.google.com> Oren Tirosh wrote in message news:... > On Fri, Jul 05, 2002 at 04:29:48PM -0700, Mike Johnson wrote: > > I am starting an A-Level course in computing in september, and i will > > need to learn how to use python. I have no previous experience of > > programming, but could anyone point me in the direction of an "Idiots > > Guide"? > > I see you already got a few answers. I was just wondering - who is giving > this course? I believe Python is an excellent first language to learn and > it's nice to see that beginner courses are using Python. > > Oren Thanks very much for the replies, i'll look at those guides. The course starts in september and is being run by Geoff Tarrant of Trinity School, Carlisle (UK). Python is being used because it is easy to learn and unlike Visual Basic, if you want to continue to work on computers at home, you will not have to pay about ?100 for a copy of VB (or use pirated disks) and it is open source. Thanks Again, Mike From loewis at informatik.hu-berlin.de Tue Jul 2 07:52:48 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Jul 2002 13:52:48 +0200 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: "Mike C. Fletcher" writes: > Well, that answers that question, I suppose. No clue what a surrogate > is for, but I suppose there's no point including them in a > character-classes set if they're designed specifically as unicode > internal chars. Correct. For a definition of surrogates and UTF-16, see http://www.ietf.org/rfc/rfc2781.txt Regards, Martin From duncan at NOSPAMrcp.co.uk Wed Jul 31 07:19:53 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 31 Jul 2002 11:19:53 +0000 (UTC) Subject: How do you import a module with "." in its filename? References: Message-ID: "Keith Dart" wrote in news:xsP19.36095$Zw6.135530681 at newssvr21.news.prodigy.com: > But.... why bother? Why not just rename the original modules to > a_test.py, etc.? That's what I do. Well, the OP said: > For both practical and political reasons, renaming a.test.py to a_test.py > is not an option. I'm not entirely sure I believe there are practical reasons, but the politics may well be insurmountable. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From R.Barrett at ftel.co.uk Mon Jul 8 14:13:00 2002 From: R.Barrett at ftel.co.uk (Richard Barrett) Date: Mon, 08 Jul 2002 19:13:00 +0100 Subject: Why self? In-Reply-To: <3D29CE9D.4000802@onsitetech.com> References: Message-ID: <5.1.0.14.2.20020708190501.0348edd8@pop.ftel.co.uk> At 17:42 08/07/2002 +0000, Robb Shecter wrote: >Matt Gerrans wrote: > >>In Python, I think the required "self" reference in methods is a case where >>the solution is worse than the problem it solves. Since indentation is the >>method of scoping in Python, this addition of five characters to each >>instance variable is particularly annoying -- a one-line statement that >>contains several instance variables can easily become unmanageable. > >I completely agree, but I think the situation's even worse than you >described: A'typical' case of standard OO programming is made the most >tedious to write: References to instance variables from methods: > > self.__velocity = self.__factor1 * self.__factor2 > >etc. I find this totally unreadable (7 extra characters per referenced >instance variable). > >Robb And now you are going to tell which language (compiled or scripting, functional or procedural, or whatever) with OO capability is more productive, from the standpoint of tested lines of code per day, as Python ... From whisper at oz.net Thu Jul 18 19:58:29 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 18 Jul 2002 16:58:29 -0700 Subject: Calling Fredrik Lundh, (dare i ask) Guido, all other Guru's, could this be a bug? In-Reply-To: Message-ID: > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of G. Willoughby > Sent: Thursday, July 18, 2002 15:01 > To: python-list at python.org > Subject: Calling Fredrik Lundh, (dare i ask) Guido, all other Guru's, > could this be a bug? > > > I have been getting an error when quitting an app using a menu to call > 'self.master.quit'. the error is: In what app? What does self refer to here? > 'The instruction at "0x00d7a0a3" referenced memory at "0x00000008". The > memory could not be "read".' > > I've also had a few people email me about old utils i've released > about the > same problem. This only seems to occur for people running WinXP. > I've never > had people email me about this before. You need to create a debug version of ActiveState Python and track that error to a source line to get a true idea of what's going on. Being able to say "my program crashed in a python distribution file 'randomfile.c' at line 23" is going to get you heaps more attention and, likely, gratification too. > My particular OS is WinXP Pro, with ActiveState Python 2.1 (#15, Jun 18 > 2001, 21:42:28) with PIL (via ppm.py) installed. any ideas whats > going on? I > never used to get this error with Win98 or WinME. > > Thanks, > > --G. Willoughby > Dave LeBlanc Seattle, WA USA From fperez528 at yahoo.com Fri Jul 26 18:06:21 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 16:06:21 -0600 Subject: performance problem in python 2.2 References: Message-ID: Jeff Davis wrote: > I wrote a small python program to help me solve a math problem. When I > tried to run it with large values, it ate all my RAM and I eventually had > to kill it. I tried writing the same thing in C and it used almost no RAM > (and had an upper limit) and finished much faster. > > Then I was talking to someone who suggested that I try perl. I have the > exact same algorithm in perl, and it doesn't eat my RAM, and executes much > more quickly (same order of magnitude as the c program). It seems almost > as if there's a memory leak in one of python's simple math operations, > because it is so much worse than the other ones I tried. > > I have listed the two programs below. Does someone think I found a > bug/memory leak? Does someone know about something else that might be > going on? Well a few people have already given you some pointers, and the caveats to the problem of representing p as a float which Tim Peters indicated. But ignoring those for a moment, and doing things with xrange, it remains true that Python's flexibility does have a price. All names are bound to objects whose behavior needs to be looked at every time. On the other hand, I'd be INCREDIBLY surprised to see that perl can come anywhere close to C speed on this little problem. Here are some quick benchmarks: # Python version: higgs[python]> time ./numbers.py 1000000 2.71050724088e-08 4.360u 0.000s 0:04.42 98.6% 0+0k 0+0io 457pf+0w # Perl version: higgs[python]> time ./numbers.pl 1000000 2.71050724087729e-08 1.920u 0.000s 0:01.93 99.4% 0+0k 0+0io 293pf+0w # C version: higgs[python]> time ./numbers.cx 1000000 2.7105081417191923e-08 0.030u 0.000s 0:00.04 75.0% 0+0k 0+0io 115pf+0w As you see, perl/python are in the same league, even though perl is a factor of 2 faster. I am one of those people who would like to see that factor of 2 gone, but in reality when speed matters I'm happy inlining C code in python via weave. But the C code is in a different league altogether, as it should. I'm aware though that the factor of 2 for perl's faster performance isn't always there, it just tends to show up under certain circumstances. 99% of the time I don't care, and I'd much rather see the dev team's time and efforts spent on more important problems (as they do). For reference, the codes are below: #include #include int main(int argc,char *argv[]) { long i,c; double n = 1.0; double p = 1.8446744073709551616e+19; c = atol(argv[1]); for (i=1;i<=c;++i) n = (n * (p-i)) / p; printf("%.16e\n",1-n); return 0; } #!/usr/bin/perl $p = 2**64; $c = $ARGV[0]; $n = 1; foreach $i (1..$c) { $n = ($n * ($p-$i)) / $p } print 1-$n, "\n"; #!/usr/bin/env python import sys n = 1.0 p = 2.0**64 # making p a float for fariness of comparison, not correctness c = int(sys.argv[1]) for i in xrange(1,c+1): n = (n * (p-i)) / p print 1-n So in summary, Python does offer you the easiest way to get the problem _right_, by allowing you to use long integers for everything. In the tight loops it does remain a bit slower. Most of us are willing to pay that price though (even though we'd like it to disappear, of course, if it was so easy :). But again, there's NO WAY you are going to write perl code to do this at C speed (short of a trick like inlining C in perl). Cheers, f. From anuraguniyal at yahoo.com Tue Jul 16 03:42:04 2002 From: anuraguniyal at yahoo.com (Anurag Uniyal) Date: 16 Jul 2002 00:42:04 -0700 Subject: Debugging Embedded Python References: Message-ID: <57a8f637.0207152342.51de3e77@posting.google.com> Hi, I think what you want can be found at archaeopteryx.com. You can get a 30 day trial verison. I am using it and for debugging my embedded scripts and by importing a script provided by archaeopteryx.com you can attach debugger to any running script. rgds Anurag mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote in message news:... > We've got a (win32) C++ program that has an embedded python interpreter > that runs a bunch of scripts. We've been asked to enable it's users to run > the python scripts under a debugger, allowing the users to put in > breakpoints, examine/alter values etc. > > Now the C++ program basically does the following... > > - Initialises some C++ stuff > - loads in the python DLL > - initialises some python stuff > - starts a long complicated bunch of processing that bounces between > python and C++ > > One way to get the python running under a debugger is to tweak the system > so that the C++ executable becomes a C++ DLL that can be loaded as a > python extension. Then it's just a case of having a tiny python script > that > > - initialises some python stuff > - loads in the C++ DLL > - initialises some C++ stuff > - starts a long complicated bunch of processing that bounces between > python and C++ > > It's then a simple matter of running the above python script in a python > debugger. > > While this would work, it has two irritants > 1) the work required to change the C++ executable into a python extension > DLL > 2) the python debugger will (presumably) be built to use release-build > DLL's. Which means that any build where we can run the whole thing under a > python debugger (i.e. a release build) can't easily be run under a C++ > debugger and vice versa. > > Are there any win32-compatible python debuggers out there which can > a) do an "Attach to process" and debug any executable that's using the > python DLL > and/or > b) have source or pre-built debug builds available? > > Many TIA From jb at cascade-sys.com Sat Jul 13 06:34:44 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Sat, 13 Jul 2002 03:34:44 -0700 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> <1026545186.810050@yasure> Message-ID: <3D300244.3089F1C4@cascade-sys.com> Donn Cave wrote: > We can say "follow the standard", or we can say "follow the standard > unless you have some other idea." In merely advocating flexibility on minor points in the standard. I am in no way advocating total anarchy as you suggest in this rhetorical statement. I think rather you are the one advocating the extreme view. If you hadn't said "to the letter" and furthermore objected to Mr. Corns perfectly reasonable suggestion in your previous post, I probably would not have taken exception. Furthermore, we're talking about a sub-heading marked "pet peeves", which I read as one of the more advisory parts of the standard, something you follow more or less closely depending on how much you want to emulate a particular individual. It's not a vital part of the standard. Browsing through the 2.2 Library, about half the modules I checked exhibited deviations from the standard re horizontal whitespace. So not too many key contributors appear to share your zealous view on this particular point. > If you have a good way for people > to tell the difference between their own personal idiosyncrasies and > a really good idea that really deserves to be an exception, that > would be interesting. Well, you're asking for an algorithm which anyone would be hard pressed to provide. I guess that makes the question rhetorical. Howver, I am prepared to defend tabular organization of code. Tabular data is such a common paradigm in computers and in printed reports precisely because it is a tremendous aid to comprehension. In programming, first off, you are clued in that the corresponding section of code is highly repetitious. Second, you are shown that each repeated part may be logically divided into parallel pieces with similar roles. Most importantly, a tabular format tells you at a glance those code fragments that are common among all the various cases, those that are common only among a subset and those that are unique in each case. Finally, it just looks neater. I don't see how you can argue that to jumble the stuff all together (thereby eliminating these choice visual cues) makes tables or highly parallel code EASIER to read. In my experience, code comprehension takes place at two levels. At the higher level, humans perceive pages or "paragraphs" at a time. This is why proper indentation is to vitally important. The left whitespace and the leading keywords give you a lot of information about the overall structure of the program without having to read each line. It helps you navigate the code and provides a context for local changes. Tables are another aid to comprehension at the higher level. At a lower level, you zoom into individual statements, comprehend and edit them. > Once a coding style has > really become standard, deviations from it will tend to be less readable > for most of the people who are used to that standard, and it makes no > difference if the deviations are in principle superior. In this PEP 8 itself seems to contradict you by saying one explicit reason for breaking the rules is: (1) When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules. Even if you still disagree about tabular formatting specifically, the express directive here seems to be to NOT compromise the principle of readability in favor of standards as you suggest. PEP8 covers vitally important major issues (like indentation) and it covers lesser issues down to the level of horizontal whitespace (beyond tab stops), which frankly I've NEVER seen in a coding standard. Nevertheless, I even agree with a lot of THOSE details, e.g., spaces around assignments and after commas. I think your point is perfectly valid about the big issues, particularly those that affect comprehension at the higher level. But it breaks down when it comes to some of the nitty details, which I bet most users can't exactly recall. I leave that trivia to the Hobgoblins. > By the way, speaking of style - you may not have noticed that you > formatted your post to 84 columns. 75 or less would be nice. I > reformatted for you. According to my Preferences settings, Netscape is supposed to wrap outgoing messages to 66 columns. Like a lot of free software it doesn't always do the right thing. Dunno where the 84 came from, probably the listmanager. On the plus side, Netscape wraps lines on incoming messages to my window width, which is great. So I don't ever find myself in the position of complaining to others about what amounts to a limitation of my own tools. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From osuchw at ecn.ab.ca Fri Jul 5 11:36:31 2002 From: osuchw at ecn.ab.ca (waldekO) Date: 5 Jul 2002 08:36:31 -0700 Subject: Using .UDL files with Python References: Message-ID: "Opus" wrote in message news:... > Is there anything for Python that allows the usage of a .UDL to describe the > connection to a database? The .udl file is really a text file. You could open it from Python using open('some_udl.uld'). >>> udl = open('c:/sample.udl') >>> connstring = udl.readlines()[2] >>> connstring '\x00P\x00r\x00o\x00v\x00i\x00d\x00e\x00r\x00=\x00M\x00S\x00D\x00A\x00O\x00R\x00A\x00.\x001\x00;\x00U\x00s\x00e\x00r\x00 \x00I\x00D\x00=\x00s\x00u\x00p\x00p\x00o\x00r\x00t\x00;\x00D\x00a\x00t\x00a\x00 \x00S\x00o\x00u\x00r\x00c\x00e\x00=\x00m\x00f\x00i\x00s\x00;\x00P\x00e\x00r\x00s\x00i\x00s\x00t\x00 \x00S\x00e\x00c\x00u\x00r\x00i\x00t\x00y\x00 \x00I\x00n\x00f\x00o\x00=\x00F\x00a\x00l\x00s\x00e\x00\r\x00\n' >>> connstring = connstring.replace('\x00','') >>> connstring 'Provider=MSDAORA.1;User ID=support;Data Source=mfis;Persist Security Info=False\r\n' >>> Each character is padded with 0 but replace() takes care of that. waldekO From kalle at lysator.liu.se Sun Jul 21 00:34:57 2002 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sun, 21 Jul 2002 06:34:57 +0200 Subject: maximum recursion depth In-Reply-To: References: Message-ID: <20020721043457.GA1835@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Paul] > My question to you: Is there a way to change the limit of the recursion > depth? You want the function sys.setrecursionlimit. Check the documentation for more info: http://python.org/doc/current/lib/module-sys.html . Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9OjnudNeA1787sd0RAs0/AJ0bpyQOGvDe4U8fBOQayObvWu6kpACfbh4c t+gydeMyqGgoUF226ELQ4Es= =ye1N -----END PGP SIGNATURE----- From deltapigz at telocity.com Sun Jul 28 16:01:35 2002 From: deltapigz at telocity.com (Adonis) Date: Sun, 28 Jul 2002 16:01:35 -0400 Subject: python mysql interface Message-ID: <3d444d8e$1_2@nopics.sjc> i hav downloaded Python mySQL, but lacks any documentation? is there a recommended mySQL module for Python? any help is greatly appreciated. Adonis From chicken7373 at yahoo.com Mon Jul 15 11:43:27 2002 From: chicken7373 at yahoo.com (Becky Hehn) Date: Mon, 15 Jul 2002 08:43:27 -0700 (PDT) Subject: Newbie: Capture output of compile_dir Message-ID: <20020715154327.46010.qmail@web13007.mail.yahoo.com> Hello All, I want to be able to capture the output of compile_dir because I want to further process the output of this command. It appears that compile_dir prints output to the screen rather than returning it to the caller. How do I capture the output of this command? If I do something like: output=compile_dir(path) the output of compile_dir gets printed to the screen and the variable output just hold an integer. Help! Thank you very much. __________________________________________________ Do You Yahoo!? Yahoo! Autos - Get free new car price quotes http://autos.yahoo.com From parameter at go.com Mon Jul 22 20:38:06 2002 From: parameter at go.com (bilbo) Date: 22 Jul 2002 17:38:06 -0700 Subject: URLopener with x509? Message-ID: <174d1ff2.0207221638.4738a41b@posting.google.com> I'd like to use https with Python as a client to a private apache server. Because it's my server and my client, I thought I could create my own RSA keys. URLopener looks promising. It can take arguments called key_file and a cert_file. That sounds like what I need. The documentation leaves me wondering what should be in the key_file and cert_file. Does anyone have an example of doing this? Does the client need a private key for an https connection? The code I've tested so far works with official keys from a certificate authority, but not with my keys (I'm testing without using the key_file and cert_file arguments). I'm hoping I can somehow refer the client to the server's public key and have the client trust it without asking a certificate authority. From d2002xx at yahoo.co.uk Thu Jul 18 14:53:20 2002 From: d2002xx at yahoo.co.uk (d2002xx) Date: 18 Jul 2002 11:53:20 -0700 Subject: Appication server other than zope Message-ID: Hi. I'm searching for application servers other than zope. Would somebody tell me where to get such thing? From marklists at mceahern.com Thu Jul 4 13:20:53 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 4 Jul 2002 12:20:53 -0500 Subject: testing a sequence for 'identicalness' In-Reply-To: Message-ID: [Rajarshi Guha] > Thanks! Did'nt know about this module. > OK - what if I allow numbers like 1.1 and 1 to be equal (that is numbers > which are close are also consdiered to be identical) > > I'm not really clear on how to set this up in difflib - maybe the bagging > idea is a better choice for this problem? I didn't know about difflib either. Thanks Emile! Before I read Emile's response, I began working on this very simplistic attempt to solve the problem. For XP fans, note that I wrote the unit test BEFORE writing the code. ;-) You'll note that compare_items() -- I'm not sure that's the best name -- utilizes a make_bag function (modified slightly from something Alex Martelli posted in reference to a different problem). def compare_items(seq1, seq2): """compare_items(seq1, seq2) --> float Return the ratio of items in the smaller sequence found in the larger sequence. """ larger, smaller = (len(seq1) > len(seq2)) and (seq1, seq2) or (seq2, seq1) def make_bag(l): dict_l = {} for x in l: if hasattr(x, "lower"): x = x.lower() # This takes care of duplicates. dict_l[x] = 1 + dict_l.get(x, 0) return dict_l s = make_bag(smaller) l = make_bag(larger) matches = 0 for k, v in s.items(): if k in l: l_v = l[k] # Accumulate the count of items matched, which is the # smaller of the two. matches += (v > l_v) and l_v or v # Should I divide by len(larger) or len(smaller)? Or perhaps just # return matches? return matches / float(len(larger)) import unittest class test(unittest.TestCase): def test(self): seq1 = range(10) seq2 = range(10) # Reverse seq2 to make sure our algorithm isn't dependent # on order--of course, perhaps it should be? seq2.reverse() v = compare_items(seq1, seq2) expected = 1.0 self.assertEquals(v, expected) seq3 = range(9) v = compare_items(seq1, seq3) expected = .9 self.assertEquals(v, expected) seq4 = [1, 0, 100, 'a', 'b', 'c'] v = compare_items(seq1, seq4) expected = .2 self.assertEquals(v, expected) if __name__ == "__main__": unittest.main() - From zopestoller at thomas-guettler.de Wed Jul 3 05:20:06 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 03 Jul 2002 11:20:06 +0200 Subject: Syntax Error at end of file References: <3D22BD53.7020507@thomas-guettler.de> Message-ID: <3D22C1C6.1020109@thomas-guettler.de> Thomas Guettler wrote: > > Hi! > > I get the following error-message: > > """ > File "", line 254 > > ^ > SyntaxError: invalid token > """ > > This wrror occurs at the end of the file. I think > it is because a left a (, ' or " open. > > Is there a tool which can give me the line of the opening > character? I programmed a lot and don't want to scan > a lot of lines for an not closed paranthesis Found the error: It was an open >'''<. Would it be very difficult if the error message could say what it was suspecting (''') and tells me where the matching start is? thomas From cliechti at gmx.net Wed Jul 3 19:42:31 2002 From: cliechti at gmx.net (Chris Liechti) Date: 4 Jul 2002 01:42:31 +0200 Subject: ANN: pythonwin patch to run in a separate process Message-ID: this (tries to) solve some troubles when e.g. running other GUI scripts in the pythonwin editor. from the readme: this patch adds a new entry to the "Run" dialog: "Run External". the script is run in its own subrocess, but the outputs are captured and sent to the pythonwin console. (this is especialy useful on NT/2k/XP where the console window quickly closes and exceptions can not be read...) if the script requests input (raw_input, sys.stin.read(), etc.) a request is sent to pythonwin, which in turn displays the usual input box. for the full text and download go here: http://www.geocities.com/chrisliechti/en/python/runext.html have fun, chris -- Chris From bokr at oz.net Wed Jul 3 16:03:45 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Jul 2002 20:03:45 GMT Subject: [NEWBIE]-Object referencing?? References: Message-ID: On Tue, 2 Jul 2002 15:46:36 +1000, "Alistair Campbell" wrote: >Hi, > >I have class defined as below > > >... >class Brew: > > def __init__(self): > self.brew_id="" > self.brew_date="" > self.brew_type="" > self.hydro_init='1040' > self.hydro_final='1000' > self.starter="" > self.amt_start="" > > def alcohol(self): > return >((string.atoi(self.hydro_init)-string.atoi(self.hydro_final))*0.00036251)*10 >0 >... > > >I assign data from a file so the data that goes into the alcohol method >needs to be converted from string. >The problem is that when I try to reference an instantiation of the Brew() >class, i.e; > >current_brew=Brew() > >I can get all the other data items but a call to; > >current_brew.alcohol > >returns > > > >So. I know that the calculation of alcohol content is not true but I am just >fiddling and will put in the correct formula when I get round to it. > >But, what am I doing wrong in relation to my definition or calling of the >Brew.alcohol method? > >Trivial but nonetheless I have to start learning somewhere. Your help is >much appreciated. > Other posts haven't revealed that you actually can make it so you can write current_brew.alcohol and get a calculated value much as if you called your current_brew.alcohol() method explicitly. The mechanism is called a property. Using this mechanism, you could write your code as: ( I'm using Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 ) >>> class Brew(object): ... def __init__(self): ... self.brew_id="" ... self.brew_date="" ... self.brew_type="" ... self.hydro_init=1040 ... self.hydro_final=1000 ... self.starter="" ... self.amt_start="" ... def _get_alcohol(self): ... return (self.hydro_init-self.hydro_final)*0.036251 # 0.00036251*100 ... def _no_no(self,*args): ... raise TypeError, 'alcohol is a dynamically calculated read-only value. See Brew.alcohol.__doc__' ... alcohol = property( ... _get_alcohol, # get fcn ... _no_no, # set fcn ... doc = 'alcohol is calculated as (hydro_init - hydro_final)*0.00036251*100: see those attributes' ... ) ... Below, for cb read current_brew ;-) >>> cb = Brew() >>> cb.alcohol 1.45004 Now we'll change values it depends on: >>> cb.hydro_final -= 40 >>> cb.alcohol 2.90008 >>> cb.hydro_init += 40 >>> cb.alcohol 4.3501199999999995 Try to change it as if it were an ordinary attribute. We have defined a set fcn, so we get: >>> cb.alcohol = 1.2 Traceback (most recent call last): File "", line 1, in ? File "", line 13, in _no_no TypeError: alcohol is a dynamically calculated read-only value. See Brew.alcohol.__doc__ But we didn't specify a del fcn after that in property(...), so we get the default response: >>> del cb.alcohol Traceback (most recent call last): File "", line 1, in ? AttributeError: can't delete attribute We did define a doc string for the property, but you have to access it via the class itself >>> Brew.alcohol.__doc__ 'alcohol is calculated as (hydro_init - hydro_final)*0.00036251*100: see those attributes' More about properties: http://www.python.org/2.2/descrintro.html#property BTW, note that .alcohol is an attribute of the class, but the magic execution of _get_alcohol() depends on accessing the attribute via a class _instance_: >>> cb.alcohol 4.3501199999999995 >>> Brew.alcohol Also note that you have to derive your class from object to get the property magic. HTH Regards, Bengt Richter From plungermonkey at cox.net Tue Jul 16 11:46:28 2002 From: plungermonkey at cox.net (Jef) Date: Tue, 16 Jul 2002 15:46:28 GMT Subject: Radians vs. Degrees References: <3D33016C.8030804@cox.net> <3D3440D3.2060400@cox.net> Message-ID: <3D344147.2030006@cox.net> Jef wrote: > Jef wrote: > >> Hi All, >> >> I'm new to this NG so please bear with me :-) I'm writing an addon >> for the Quake2 editor named QuArK and could use some advice from the >> math/coding gurus out there. >> >> My problem is that I'm trying to create a torus (donut) and the C >> code I'm looking at uses DTOR to convert degrees to radians and I see >> no mention of it (DTOR) in Python. My question is whether I need this >> in Python or does Python automatically convert to radians during >> calculations? Also, do the FOR loops work the same as in C++ (e.g. >> FOR(x=0, x<360, x++))? If not, any suggestions on how to do this? >> >> TIA >> >> -Jef >> > > Thanks for the info! It'll certainly save what little I have left :-p ^^^^^^^ insert here DOH! From kristian.ovaska at helsinki.fi Thu Jul 25 04:46:26 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Thu, 25 Jul 2002 11:46:26 +0300 Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: Tom Harris : >Massive regular expressions are certainly difficult to maintain, and I >sometimes wonder if they are the best solution to some problems. It's strange that while regular languages are a small subset of real, Turing-complete languages, it's very hard to read or write any non-trivial regexp. The syntax is straight out of computer science mathematical notation (with some extensions) and is not suitable for anything complex. It's bit like programming for the Turing machine. On the other hand, the syntax is compact and IS suitable for simple tasks. I'm sure there are alternative regular languages that are more readable, altough I've never come across one. The problem of such languages is, I guess, that since they are more verbose than this very compact CS notation, you can't just wrap them in a string, but would need to expand the underlying language (Python in this case). -- Kristian Ovaska From duduca007 at yahoo.com Mon Jul 8 19:10:29 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Mon, 8 Jul 2002 16:10:29 -0700 (PDT) Subject: VisAD/Jython or PyOpenGL for 2D/3D cellular automata? In-Reply-To: <3d28904f.1941722@news.atl.bellsouth.net> Message-ID: <20020708231029.38317.qmail@web11402.mail.yahoo.com> --- Ralph Richard Cook wrote: > I was wondering what experience people had > with either of > these packages PyOpenGL nowdays is a very stable version (2.0.0.44). I make 2 or 3 full programs with PyOpenGL (and PyQt). My unique warning is: "PyOpenGL is tooooooooooooo slow". []'s Cadu Moreira KaduSoft President ---------------------------- [...PyOpenGL is cool...] __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com From xscottgjunk at yahoo.com Fri Jul 5 14:25:14 2002 From: xscottgjunk at yahoo.com (Scott Gilbert) Date: 5 Jul 2002 11:25:14 -0700 Subject: Memory ? References: Message-ID: <79b2b0bb.0207051025.45cc314b@posting.google.com> "Shagshag13" wrote: > Hello, > > i'm still looking for a way to check which are the best ways to save memory > because i work on many GB with float, etc. so is there a > way to check how many bytes needs an object, a tuple, a list, a dict of > objects and so on ? (something like itemsize for array - in > fact array should be great if they weren't boxed) > Your best way to find out how much memory is being used is to measure it using your native tools. (something like ps on Unix, or somethig like Task Manager on Windows) Probably your best way to figure out what is most efficient is to try different strategies and measure the results. The array module is going to give you very efficient storage as is Numeric. If you're concerned about putting different types of data in one array (both float and char for instance), you might consider creating 3 arrays: 1 for type float, 1 for type char, and one that lets you know which of the other two to use. Wrap it all up in a class so that access to the data is transparent. Also, if you know that some values simply can't occur (char 0) for instance, then you could just use 2 arrays etc... All kinds of clever hacks are possible, and if you hide them in a class they don't have to be that ugly to use. Finally, all of these are just going to get you some percentage of savings. I think you can safely assume that all Python data structures use memory proportional to how much data you are storing in them (a notable exception being interned strings). So if you can reorganize your problem to switch from O(N*N) space to O(N*log(N)) space, you'll get much better savings. Cheers, -Scott From gerhard.haering at gmx.de Fri Jul 26 21:40:20 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 27 Jul 2002 03:40:20 +0200 Subject: performance problem in python 2.2 In-Reply-To: <7xznwem0qe.fsf@ruckus.brouhaha.com> References: <7xd6tayqt6.fsf@ruckus.brouhaha.com> <7xptxaj9kq.fsf@ruckus.brouhaha.com> <6_l09.28101$_M2.10183516@twister.socal.rr.com> <7xznwem0qe.fsf@ruckus.brouhaha.com> Message-ID: <20020727014020.GA1850@lilith.my-fqdn.de> * Paul Rubin [2002-07-26 18:13 -0700]: > Jeff Davis writes: > > > If you read my C code, you'll see that I used the 'unsigned long long type' > > which is a 64-bit int. And I only stored 2^32 in it. When I needed to > > crunch the numbers, I treated 2^64 as p*p (because 2^64 == > > sqrt(2^64)*sqrt(2^64) == 2^32*2^32), and then I commuted the > > multiplication so it would happen in a way that wouldn't overflow. > > Oh whoops, yes, I missed that. "Long long" is not part of standard C, It is. C99. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 02:30:25 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 06 Jul 2002 23:30:25 -0700 Subject: structs in python References: Message-ID: <7xsn2wyrr2.fsf@ruckus.brouhaha.com> "Sean 'Shaleh' Perry" writes: > However this breaks down for your delta = ... example. > > is > > class Point: > def __init__(x, y, color): > self.x = x > self.y = y > self.color = color > > really that much to type? Yes, it seems clumsy to me. See how error prone it is: your __init__ function arg list forgot to mention 'self'. The new slots scheme may be better but it doesn't exist in older Pythons and isn't well documented in 2.2. From richie at entrian.com Fri Jul 5 06:11:52 2002 From: richie at entrian.com (Richie Hindle) Date: Fri, 05 Jul 2002 11:11:52 +0100 Subject: determining instance attributes References: Message-ID: > how can an instance easily find out all its non-method instance attributes? This finds all non-callable instance attributes. That means it won't find inner classes, but I'm guessing you didn't want those anyway: >>> class Test: ... def __init__( self ): ... self.attribute = 1 ... ... def findNonMethodAttributes( self ): ... names = [] ... for name, attribute in self.__dict__.items(): ... if not hasattr( attribute, '__call__' ): ... names.append( name ) ... return names ... >>> >>> test = Test() >>> print test.findNonMethodAttributes() ['attribute'] >>> If you're using Python 2.x and you're a fan of list comprehensions: def findNonMethodAttributes( self ): return [ name for name, attribute in self.__dict__.items() if not hasattr( attribute, '__call__' ) ] -- Richie Hindle richie at entrian.com From K.Rdt at TU-Berlin.DE Wed Jul 3 11:05:02 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Wed, 03 Jul 2002 17:05:02 +0200 Subject: HT clear some wxPython fram? Message-ID: --------------------------------------------------------------------- Hi When I do: import wxPython.wx for i in dir(wxPython.wx): print i I can filter: WXK_CLEAR wxCLEAR wxID_CLEAR wxLog_ClearTraceMasks wxResourceClear But I can't use wxClear(). HOW I CAN CLEAR SOME FRAME? K at Rdt --------------------------------------------------------------------- From mgilfix at eecs.tufts.edu Mon Jul 29 10:27:28 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 29 Jul 2002 10:27:28 -0400 Subject: DIV and MOD In-Reply-To: <5.1.1.6.0.20020729112008.009fa0c0@imap.datacraft.com.br>; from m.laranjeira@datacraft.com.br on Mon, Jul 29, 2002 at 11:21:47AM -0300 References: <5.1.1.6.0.20020729112008.009fa0c0@imap.datacraft.com.br> Message-ID: <20020729102727.E15737@eecs.tufts.edu> Math module isn't necessary. Just use the '/' and '%' operators as necessarily. Why does % not work properly in this content? Python 2.1.3 (#1, Apr 9 2002, 20:09:43) [GCC 2.95.3 20010315 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> 4 / 3 >>> 1 >>> 5 % 3 >>> 2 -- Mike On Mon, Jul 29 @ 11:21, Marcus Vinicius Laranjeira wrote: > I need to use some function like DIV (returns the integer part of a > division) and MOD (returns the reminder of a division) in python, but I > don't know how to do that. % does not work as expected (in this context) > and in the MATH module, I didn't find any kind of function to do such thing. > > Can anyone help me ? > > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (m.laranjeira) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From tjreedy at udel.edu Thu Jul 25 10:49:28 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Jul 2002 14:49:28 GMT Subject: xml processing : too slow... References: Message-ID: > I suspect you'll need to get a new parser for each line. Is is possible, and might it be faster, to make and use a copy of the parser for each line? With copy module? From aleax at aleax.it Sat Jul 20 08:06:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 12:06:33 GMT Subject: args command line... References: <409a56e2.0207200133.35cdc06b@posting.google.com> Message-ID: Shagshag wrote: > hello, > > i'm looking for a script able to handle/understand "common" command > line options like : > > ascript.py -option this_is_a_directory/* > ascript.py -another_option file1 file2 file3 -another_option2 > this_is_another_dir > > i think that should exist somewhere... > > (i wish to learn as it should be written in a good pythoner's way but > also gain time by re-using it) Standard module getopt in the Python library does not meet your examples because it follows a more restrictive standard: all options come before all other arguments, and options with long names start with -- (two dashes, not just one: one dash is reserved for one-letter options, so e.g. -fop is equivalent to -f -o -p, for options not taking arguments, and equivalent to -f op, for an option taking an argument, as Unix users expect). Optik, at http://optik.sourceforge.net/ , is much richer but I think you will still have to tweak to get the option styles you want, that don't appear to follow a recognizable standard. Still, I'd suggest starting from there. Alex From trentm at ActiveState.com Wed Jul 24 15:11:10 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 24 Jul 2002 12:11:10 -0700 Subject: PyXPCOM and SVG In-Reply-To: <3D3EEFE1.5090109@myrealbox.com>; from johann.hoechtl@myrealbox.com on Wed, Jul 24, 2002 at 08:20:17PM +0200 References: <3D3EEFE1.5090109@myrealbox.com> Message-ID: <20020724121110.A13787@ActiveState.com> [Johann H?chtl wrote] > Hello ! > > I was thinking of using Mozillas new SVG and/or the gecko rendering > engine and XUL capabilities in a wxpython-application using PyXPCOM > bindings. Phew. I don't know how you would mix XUL and wxPython. They are independent graphical systems with their own message frameworks, widget sets, etc. > First of all: is this the right track to follow? I don't know. I would think not, though. > I was rather unhappy when i noticed that his requires me to build > mozilla and PyXPCOM from sources. > > Are there technical reasons why there are no binary packages available? > Or is the reason it's almost commercial background as it is used in the > Komodo IDE? That means is there a legal or licence issue? There are no legal/license issues. PyXPCOM has been released to the Mozilla source tree under the MPL (an open source license). The technical reasons why there are no binary Mozilla-with-PyXPCOM releases are that (1) mozilla.org does not do it because PyXPCOM is a non-default extension and they generally don't have the resources to provide binary builds for all possible configurations, (2) it is not a simple task to build Mozilla and PyXPCOM so noone in the community is doing it that I am aware of. Trent -- Trent Mick TrentM at ActiveState.com From chris.gonnerman at newcenturycomputers.net Sun Jul 7 08:30:46 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 7 Jul 2002 07:30:46 -0500 Subject: sqlite-python-0.2.0.win32-py2.2.exe fails References: <1b8c5fe1.0207060550.72952217@posting.google.com> <1b8c5fe1.0207070212.679882af@posting.google.com> Message-ID: <004d01c225b2$2a34b960$0101010a@local> ----- Original Message ----- From: "Comcol" > Gerhard H?ring wrote in message news:... > > * Comcol [2002-07-06 06:50 -0700]: > > I don't think that this is of use to you, though. As far as I know > there's nothing wrong with PySQLite itself, but with the > self-extracting installation program. If the distribution had been > available as a zip file then I would probably be able to install it. Try unzipping the installation file and doing the install by hand. Standard Python Win32 installation packages made by distutils are just an exe stub with a zipfile appended, and all zip packages I've ever used can read that format easily. > > PPS: Have you installed all updates for Windows 95? Service Pack 1? > > Good Lord no. I don't know where one could get a service pack anyway. Usually from Microsoft: http://www.microsoft.com/windows95/downloads/ All the service packs and hotfixes seem to be there. Right-click on My Computer and select Properties. If the version number does not end with a letter, you need Service Pack 1. If it ends in a letter 'a' (lowercase always I think) you have SP1 already. If it ends in a 'b', 'B', or 'C' you have OSR2.0, 2.1, or 2.5 (the only released versions AFAIK). OSR means OEM Service Release... you can't upgrade an 'a' version to a 'b' or higher legally (although given a CD and the magic MSBATCH.INF file it's technically easy). Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From karczma at info.unicaen.fr Wed Jul 10 05:40:39 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Wed, 10 Jul 2002 11:40:39 +0200 Subject: sorting many arrays from one... References: <%KCW8.60416$vm5.2194409@news2.tin.it> <3D2B0973.B553A25F@info.unicaen.fr> <15FW8.61099$vm5.2221340@news2.tin.it> Message-ID: <3D2C0117.89BCDC43@info.unicaen.fr> Alex Martelli comments my remarks on the slowdown of the sorting functional parameterized by a named comparison function: > > Somebody cares about explaining this behaviour? Dynamic dispatching, > > while sort() does not any dereferencing? Or what? > Basically, sort needs to do O(N log N) comparisons -- if each comparison > requires a function call, the time for those calls dominates sorting times > even if each call does little -- the overhead is the same. Sorry, but this does not explain anything. Each comparison requires a function call (perhaps inlined in some cases, but I don't believe that 'compare' may be universally inlined) whether this comparison is passed as a parameter, or called "because the sorting device <> what to call". So, thank you very much indeed for your nice N log N remainder, but the issue is not the cost of the *call* (execution), but of "call" (dereferencing/dispatching). > If you pass > nothing, sort knows to use built-in comparison methods, and its wonderful > optimizations take hold. May I ask somebody WHO KNOWS, what are those "wonderful optimizations", and why are they so brutally desactivated with, say, .sort(cmp)? > Indeed passing cmp directly > in my test I see a slowdown of about 5 times, while f which calls cmp > gives 10 times -- see, it IS all about function-call times. Thank you for confirming my test. And for confirming that all IS about the function call. I believe I made it clear that I am aware of that. I asked WHY? One of important paradigms of modern programming are higher- order functions. > > For people coming from the Functional Programming Realm such slowdown > > of parameterized functionals is hard to accept... > A slowdown of about 3.9 CPU seconds > on my machine for that many calls works out at about 0.76 microseconds > per call -- preparing the arguments tuple, unpacking it in the > called function, etc. Doesn't feel wildly out of control to me -- > it's just a LOT of function calls, using mechanisms studied for an > intepreted, dynamic language's needs for flexibility, not to get > superb performance. Aha, preparing argument tuples (you mean: making them physically, or just stacking arguments, or what?). Yes, it takes some time, but there are interpreted languages (e.g. ML) where it is very well optimized. No physical unpacking of any tuples inside a function. > What makes it FEEL huge is sort's own superb performance -- 0.16 > microseconds per comparison *everything included* when using the > built-in comparison. > > So, it's all Tim Peters' fault, for making sort so incredibly fast -- > let's all gang up against him!!! Now, put 4 more (!) marks and it will be even more funny... But, seriously again a question for somebody who *knows* the details: concretely WHAT is optimized, and WHY it cannot be done with parameterized sort. > Oh, and, a warning when you try to do such measurements: if you > mistakenly call sort on an already-sorted list, it only does > 299999 comparisons (for a 300000 items list) and finishes in > 0.04 seconds -- 0.78 with a comparison function, so the ratio > gets even worse. If you have just one item out of order at > the end, 300019 comparisons, and the same performances. This > is truly intolerable -- we HAVE to slow this darn this down!!! I happen to know a little bit about serious sorting, so the warning is a bit redundant, but thank you anyway, it suggests at least that the sorting procedure does not use the naive quicksort. Unfortunately, apart from an attempt to be funny, which I appreciate enormously , it does not address my questions... > > ... the idea of Decorate-Sort-Undecorate, which begins by constructing > > an additional list with fast-sortable keys is also something hard to > > digest. > > May I suggest some Fernet-Branca or other Italian amaro to your liking? > They do wonders to help you digest rich, too-abundant meals. My <> has perhaps some different views on what is a too-abundant meal, and also some different view of what is an elegant answer to a technical question. Further on, you suggest (in a long and explicit way) that it is a good idea, because the speed of comparison makes you gain alpha * NlogN, while the cost of decorating/undecorating is linear. That's OK, I never claimed that it wouldn't work. I used it myself, and I submitted my query because I am still convinced that it shouldn't be done. For some people wasting space *is* harmful independently of the asymptotic complexity issues. > What's surprising, at all, about this...? Shall I repeat it once more? I think that the call overhead should be perhaps better optimised, and if it seems difficult, I would like to know why. What's surprising in my question? I am not a flea on your nose, Maestro. > Suppose there was no call overhead at all, just a very > complicated comparison. The effect would be exactly the same, > no? Appliying a complicated comparison function must happen > N logN times; applying an equally complicated transformation > function that makes the items rapidly comparable only must > happen N times, and thus becomes irrelevant for large N. Nothing to do with my questions. Moreover, in complicated, interesting cases you won't be able to find this transformation producing fast comparisons in linear time anyway, so this speculation is not so interesting. The following paragraph neither, I am still asking about the function call overhead... > But the same effect will apply in ANY language for the > appropriate kind of sorting task if the comparison op > you need grows rich and complicated enough to matter. > > Assuming the language's sort has perfect optimization > and the language makes it very easy to build, handle > and dismantle sequences of tuples, of course:-). But > these are hardly DEFECTS, are they?-) What does it mean: "language's sort has perfect optimization"? It is no magic. > > I found it a bit ridiculous to pollute the > > memory with an ephemeric sequence just because there is something lousy > > with parametrized sort > I think you're using loaded language, presumably reflecting > loaded and not-well-considered sentiments. Thank you. I am always ready to learn how to behave correctly from serious, elegant people, full of sparkling humor, and who show invariably their full respect for all people in this newsgroup they address to. > There's nothing "lousy" with functions in Python -- they just take > measurable time to call, that's all. Most often one doesn't care all > that much about performance. In the name of *who* you are claiming this? Almost all creators of almost all programming languages care a lot about efficiency, about removing redundancies and optimizing frequent operations. Higher-order functions, and parameterized functionals are absolutely fundamental in functional programming, and the compiler optimisations are pushed into extreme there. In OO languages all the caching mechanisms and some other ways of accelerating the dispatch of virtual methods are also quite important. Python is no exception. It is already very good, sure, and still improving, so I see no reason not to see a place which I think to be fragile (if you prefer that than the word "lousy"). I appreciate your contribution to the Cookbook and I understand that you will defend DSU. > That's not "polluting the memory with an ephemeric sequence" -- > it's investing some memory (not much -- O(N) memory, peanuts!) > to reduce computation. A hallowed, time-honored approach, you know. It is your philosophy but there are others. For some people space matters, you know. Jerzy Karczmarczuk Caen, France From andreas at kostyrka.priv.at Sat Jul 27 04:08:36 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 27 Jul 2002 10:08:36 +0200 Subject: how to count lines in a file ? In-Reply-To: References: Message-ID: <1027753012.8774.212.camel@vaio2> Am Die, 2002-07-23 um 18.35 schrieb Sean 'Shaleh' Perry: > > On 23-Jul-2002 Shagshag13 wrote: > > do = 'wc ' + filename > > p = os.popen(do, 'r') > > line = p.read() > > p.close() > > > > read() copies the whole chunk into memory as well so you might as well use > readlines(). otherwise just use a standard loop and counter. Well, no matter how large the file is, wc just produces one line. So read() is ok :) Andreas From phr-n2002b at NOSPAMnightsong.com Sat Jul 27 20:54:18 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 27 Jul 2002 17:54:18 -0700 Subject: how to count lines in a file ? References: <7aU%8.139472$vm5.4528856@news2.tin.it> <1027656130.63094@yasure> Message-ID: <7xbs8sy8n9.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > write a handler for. A rack of event handlers might be specified > much like __slots__, except a list of tuples instead of names, > (could use a dict, but might want to specify piority order to > put likely events first) e.g., (using a fictional container for > standard platform event, perhaps extendable a la sys.modules): Oh please no. Python has too many magic variables already (__slots__, __all__, and so forth). These are used to do things that would normally be done by adding statements to the language, e.g. __all__ is what would normally be an export statement and __slots__ is what would normally be variable declarations. Somehow it's considered unminimalistic to add statements to the language to do these necessary things, so clumsy magic variables get added instaed. From jepler at unpythonic.net Mon Jul 15 18:45:53 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 15 Jul 2002 17:45:53 -0500 Subject: horizontal line in tkinter???? In-Reply-To: <3D3308B500000725@www.zipmail.com.br> References: <3D3308B500000725@www.zipmail.com.br> Message-ID: <20020715174553.A987@unpythonic.net> Another poster suggests using a frame which is 1 pixel tall and black. The following looks a little more like a


in HTML. A height of 2 gives a pixel for the lighter color and for the darker color, and the padx/pady leaves a gap on all sides in the color of the enclosing frame or toplevel. I just translated this from some experimentation in wish, so the code is only probably right... def Separator(master): return Frame(relief=ridge, height=2, bg="white") def PackedSeparator(master, **pack_kw): f = Separator(master) f.pack(padx=5, pady=5, **pack_kw) return f def GriddedSeparator(master, **grid_kw): f = Separator(master) f.grid(padx=5, pady=5, **pack_kw) return f Jeff From tjreedy at udel.edu Mon Jul 29 19:17:42 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Jul 2002 23:17:42 GMT Subject: pretty basic: get variable name from list of strings? References: Message-ID: wrote in message news:i1fbku0neslja6vup69542aojqaph1nem3 at 4ax.com... > in the specific, > > if I have a list > > animals = ['horse_0', 'horse_1'] > horsenames = ['smokey', 'silver'] > > how do assign variables with those strings as names? > > ie, I want > horse_0 = "smokey" > horse_1= "silver" > > but if I write animals[0] = "smokey", it replaces the value, it > doesn't assign it. What I want is like assign() or eval() in other > languages. > > you can imagine i am trying to iterate over large indexes of > animals[i] = 'horse_' + str(i) > and then assign them from a value list > > or even screw the variable list and instead iterate over the > value list > 'horse_' + str(i) = horsenames[i]. I think you are looking for something like g = globals() # for i in range(len(horses)): g['horse_'+str(i)] = horses[i] However, I strongly question whether you *really* want to do that. Accessing a list of names such as horses thru an index is much easier that thru a dict keyed with sequential strings. Cluttering globals is also a bad idea, and above will not work with locals(). Terry J. Reedy From martin at strakt.com Tue Jul 16 05:11:53 2002 From: martin at strakt.com (Martin =?ISO-8859-1?Q?Sj=F6gren?=) Date: 16 Jul 2002 11:11:53 +0200 Subject: select.select for non-sockets in win2k In-Reply-To: <930dfcf0.0207131436.153edc47@posting.google.com> References: <930dfcf0.0207131436.153edc47@posting.google.com> Message-ID: <1026810713.711.62.camel@ratthing-b3cf> s?n 2002-07-14 klockan 00.36 skrev Alex Eggenberger: > Is there still no select.select function that works with non-sockets > like the object returned by os.popen()? AFAIK, this is a limitation (for better or for worse) in Windows. It's not a limitation in Python. Martin -- Martin Sj?gren martin at strakt.com ICQ : 41245059 Phone: +46 (0)31 7710870 Cell: +46 (0)739 169191 GPG key: http://www.strakt.com/~martin/gpg.html From loewis at informatik.hu-berlin.de Tue Jul 30 08:41:27 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Jul 2002 14:41:27 +0200 Subject: python 2.1.3 with tkinter support on Solaris 9 References: Message-ID: Marc Petitmermet writes: > > Maybe you have overdone that; please chose *one* of the strategies, > > not all of them. Just using LD_LIBRARY_PATH should be enough. What > > value are you using for that? > > I have tested all of them but none worked. What value are you using for LD_LIBRARY_PATH? > In the meantime I could compile python with tkinter support but I had to > make a soft link from /p1/local/tcltk/tk-8.3.4/libtk8.3.so to > /usr/local/lib. I just have the feeling that the find_file function in > the setup.py script does not work porperly, at least in my case. If it > would have worked properly, it should have found the libraries according > to Modules/Setup, shouldn't it? No, that doesn't work on Solaris, unless you explicitly add -R options. Regards, Martin From marklists at mceahern.com Fri Jul 12 10:49:35 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 09:49:35 -0500 Subject: Converting 2 bytes string into INT In-Reply-To: Message-ID: > Hi to all, I'm a newbie of Python and I already have a big > problem. I read 2 > bytes from files and I like to convert them into an integer. How can I do > it? > Thanks a lot. > Bye, DeDa. x = int(x) // m - From amuys at shortech.com.au Tue Jul 23 22:23:39 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 23 Jul 2002 19:23:39 -0700 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: <7934d084.0207231823.757dbe65@posting.google.com> Mack wrote in message news:... > In , John Hunter wrote: > python, python1.5 and python2. python were identical to python 1.5 so I > just did a cp /usr/bin/python2 /usr/bin/python. I can always revert if > somethings wrong. I strongly suggest you use a symbolic link instead of a copy. You may very well forget that you have made this change, or if you get someone to help you with an admin-problem they will not realise (without signifigant pain) that you have switched default python versions. A symbolic link makes this change explicit, and documents it in the filesystem. To make the change do the following as root: cd /usr/bin rm /usr/bin/python ln -s python2 python Naturally as a complete stranger is recommending you execute certain commands as root, sanity check them yourself first---or if you don't feel confidant doing that, get someone else with more Linux/Unix experience to do it first. Andrae Muys From donn at u.washington.edu Mon Jul 29 18:01:39 2002 From: donn at u.washington.edu (Donn Cave) Date: 29 Jul 2002 22:01:39 GMT Subject: Python design failures (was Re: Let's Talk About Lambda Func References: Message-ID: Quoth "Sean 'Shaleh' Perry" : | On 29-Jul-2002 Neil Schemenauer wrote: |> Sean 'Shaleh' Perry wrote: |>| I could submit a patch for the repr cleanup in pretty short order. |> |> Guido's not big on this kind of "hit and run" cleanup. He prefers it if |> someone looks at the entire module while modernizing it. Keep in mind |> though, I'm an amateur when it coming to channelling the BDFL and he |> might tell you differently himself. | | That is a reasonable attitude. | | Comments from the direct python hackers? Would more work on the lib be | welcomed? Do we want the standard library to be a good example of python best | practices? (sorry i know that sounds like a loaded question). I would be opposed, personally. (Since I don't know what "direct python hacker" means, I'm probably not one, but will comment anyway since it seems to me I brought it up in the first place.) 1. It's up to the people who write the code. There are probably some standards for contributed code, I hope so anyway, but I wouldn't want to expect someone to maintain a module that had been recoded at a later date for essentially religious reasons. 2. The distribution library is a useful reality check in cases like this. Want to know how people really use repr, str, lambda, integer arithmetic, you name it? The distribution library represents a group of reasonably accomplished programmers, whose work we all use. They don't always follow the party line on everything, but past any initial submission requirements, they're entitled to call their own shots on usage, and I think that's actually useful. It helps us to distinguish between comp.lang.python dogma and what everyone's really doing. If they want to ask me how to code their programs, I'd sure advise them to get rid of the back ticks and I wouldn't take any BS about how elegant and readable they are. But I want them to see that on their own, I don't want to whitewash their code so we can pretend everyone agrees about these matters. Donn Cave, donn at u.washington.edu From cbbrowne at acm.org Sun Jul 14 15:49:43 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 14 Jul 2002 19:49:43 GMT Subject: Python and Parrot References: <3D316CCA.90605@myrealbox.com> <7FeY8.15997$p56.5173354@newsb.telia.net> <3D31C707.9020706@myrealbox.com> Message-ID: In the last exciting episode, Johann H?chtl wrote:: > I'm not advocating it, I only stumbled over > > http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/nondist/sandbox/parrot/ > and was wondering why work stopped as the papers of parrot look > promising. The code that exists is pretty neat. Yes, I'd say it looks _quite_ promising. The problem is that the prime people working on it need to put food on their tables, and apparently the Perl community, while large, has not found the ability to throw a few bucks at the critical programmers. The guys who _were_ being funded by the "Perl Foundation" are trying to scrabble up some alternative sources of funding so they can continue work. It's apparently not a trivial matter. A not-so-idle idle thought: It might be a neat idea, instead of buying a $40 book from some of these folks that _maybe_ they get $2 out of, to go with the online/electronic version and send them a $20 in the mail. If a few thousand people did that, I suppose O'Reilly or Addison Wesley might be somewhat chagrined, but it would certainly pump _your_ money more directly to the authors and "prime mover" types... -- (concatenate 'string "chris" "@cbbrowne.com") http://cbbrowne.com/info/fssp.html ``God decided to take the devil to court and settle their differences once and for all. When Satan heard of this, he grinned and said, "And just where do you think you're going to find a lawyer?"'' From spam at your-site.com Tue Jul 9 11:55:17 2002 From: spam at your-site.com (spam-here) Date: Tue, 09 Jul 2002 15:55:17 GMT Subject: Converting a hex string to a number References: <4b628986.0207090252.5338178d@posting.google.com> <3d2adb64$0$12283$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Alex Martelli wrote: AM# me wrote: AM# ... >> Like this solution. Is there a way to use that long as hex, so bit >> operations can be done on it piecewise? Slice a byte, then xor it or >> and it, and put it back? AM# Longs, like ints and other kinds of numbers, are immutable -- so each AM# time you change even one bit you're allocating a new one and copying AM# all the rest. Use an array.array with a typecode of 'B' (unsigned bytes), AM# it may prove substantially better-performing as it's mutable. AM# Alex thanks, stan From spahievi at vega.bg Thu Jul 11 02:12:42 2002 From: spahievi at vega.bg (Niki Spahiev) Date: Thu, 11 Jul 2002 09:12:42 +0300 Subject: Multi language software development? In-Reply-To: References: <3D2B1E91.4070102@gmx.de> Message-ID: <631578760.20020711091242@vega.bg> 7/9/2002, 21:48:53, Martin v. Loewis wrote: MvL> Ingo Linkweiler writes: >> One way is to replace all strings by variables, and put the >> variables in a module. Do you know other good ways to develop >> software for more than one language and to translate existing >> software? MvL> I recommend to use the gettext module. then get poedit from sourceforge.net -- Best regards, Niki Spahiev ______________________________________ VEGA(TM) Internet Service Provider Scanned and protected by Inflex Tova pismo e provereno i zashtiteno ot programite "Inflex/Antivir". From samschul at pacbell.net Mon Jul 22 18:30:20 2002 From: samschul at pacbell.net (Samuel Schulenburg) Date: 22 Jul 2002 15:30:20 -0700 Subject: Problem with diferences in executinion Message-ID: If I execute the following code snipit from Python it executes the way I expected it. If I build a standalone exe with McMillan's installer the function call to startscsi() function in MaxPTI's __init__() is not in scope. Maxscsi.py is a file that initializes and loads MaxSCSI.dll which contains startscsi(). This DLL and Maxscsi.py have been used in other McMillan installer programs without any problems. This is the first time I have tried to use a class to instanuate the DLL. The whole idea behind this program is the desire to embed Python in an exe with some added methods to allow non programmers to write an external script file and execute it with the exe with the following call: "MaxPTI MyTest" Any Help would be appreciated Sam Schulenburg ======================= MaxPTI.py/MaxPTI.exe contains =============== from Maxscsi import * # import scsi library from sys import * class MaxPTI: def __init__(self,Headless=0): startscsi(1,Headless) # Start scsi initializtion setting # Genericflag = 1,and Headless initscsi("MaxPTI","physicaldrive",1) # Locate drives setshowcdb(0) setlogerror(1) setpauseonerror(0) ..... ..... def Function1() .... .... def Function2() .... .... if __name__ == '__main__': a = MaxPTI(1) exec("from %s import MyScript"%(argv[1])) print 'Start Script' MyScript(a) =================== End MaxPTI.py ============== ================== MyTest.py =================== def MyScript(a): print a.DeviceTable for i in range(a.DeviceTableLength): print a.DeviceTable[i] print a.DeviceTable[2][a.pSERIALNUM] print a.DeviceTable[2][a.pVENDOR] From iphi at imagis.ch Wed Jul 24 10:15:12 2002 From: iphi at imagis.ch (Iphigenie) Date: 24 Jul 2002 14:15:12 GMT Subject: Fwd: Re: good books References: Message-ID: I started thinking something odd was going on in comp.lang.python when one foggy november evening Jostein Berntsen came into my office and told me: > Subject: Re: good books > Date: Wed, 24 Jul 2002 13:45:06 +0200 > From: Jostein Berntsen > To: Percy Tambunan > > A book I have used much is this one: > > Python Essential Reference - David M. Beazley > > http://www.amazon.com/exec/obidos/ASIN/0735710910/qid=1027510682/ > sr=1-3/ref=s r_1_3/103-0614004-5992611 > > Nice and tidy and straight to the point. Talking about this book I have edition 1 - anyone know if there's enough additions in edition 2 to make it worth a purchase? -- Iphigenie http://www.iphi.net From tim.one at comcast.net Tue Jul 9 16:11:30 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 09 Jul 2002 16:11:30 -0400 Subject: File size error in os.stat with large files. In-Reply-To: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: [Joe Woodward] > Does anyone know the file size limit that os.stat will handle > correctly? It depends on OS, Python version, and whether Python was compiled with "large file" support. > I have a 4.2GB file that os.stat is reporting to be 164MB. Smaller > files seem to work just fine, but I have not played with it to find > out where the cut-off point is. > > I am using Python 2.1 on Windows 2000. Microsoft's implementations of the standard C functions for doing this stuff are limited to 32-bit results, and there's no indication of overflow when they're applied to files that are "too large" for that; information is just lost. Python 2.1 uses these MS C functions in 2.1. Substantial work was done for Python 2.2 to use better large-file functions on Windows. C:\Python21>dir \junk\big.file2 07/09/2002 03:57p 5,847,842,817 big.file2 C:\Python21>python Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import os >>> os.path.getsize('/junk/big.file2') # Nonsense result 1552875521 >>> C:\Python22>python Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.getsize('/junk/big.file2') # Correct result, as unbounded long 5847842817L >>> (Note that getsize() calls a stat()-like routine under the covers; the same kinds of concerns apply to other calls, like stat() and tell()). If you need to do real work with large files on Windows, upgrade to 2.2.1. From phr-n2002b at NOSPAMnightsong.com Tue Jul 30 18:57:53 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 30 Jul 2002 15:57:53 -0700 Subject: global interpreter lock not working as it should References: Message-ID: <7xy9bs7rim.fsf@ruckus.brouhaha.com> Jonathan Hogg writes: > > That discussion typically revolves around multi-CPU systems, but the OP > > didn't mention having multiple CPUs. > > If the OP isn't trying to exploit parallelism then why write multiple > CPU-bound threads? If his threads were blocking to do I/O he'd have no > problem, so clearly they are doing CPU intensive work. If there's more than > one of them he's trying to do CPU intensive work in parallel. If he doesn't > have a multiple CPU machine and a kernel-level threads implementation then > this will always be an exercise in futility. He might be trying to accomplish something like timesharing between tasks. I can see plenty of reasons to want to do that. From martin at v.loewis.de Tue Jul 23 03:07:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 23 Jul 2002 09:07:01 +0200 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> <7x7kjne14g.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > > considering the backwards incompatibility, it makes no sense to add a > > __call__ right now. > > What incompatibility? Do you think people are out there writing > modules with __call__ functions, and then depending on raising an > exception when they call the module directly? There is no incompatibility. Having or not having an __call__ method (i.e. a tp_call slot) is a property of the type, not a property of the instance. Each module is an instance of the module type, so you need to look at the module type - and it turns out it simply doesn't have an __call__ method. Now, if you could create modules of different types, they might have __call__ methods. There just isn't any syntax to create modules of different types. Asking for __call__ on modules is like asking for __call__ on, say, numbers: def call(self, *args):pass 1.__call__ = call 1("Hello, World") Regards, Martin From sethtoday at hotmail.com Tue Jul 30 19:15:38 2002 From: sethtoday at hotmail.com (Seth Ainsley) Date: Tue, 30 Jul 2002 23:15:38 +0000 Subject: .wav music problems Message-ID: An HTML attachment was scrubbed... URL: From tim.one at comcast.net Tue Jul 16 18:39:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 16 Jul 2002 18:39:49 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty In-Reply-To: <61957B071FF421419E567A28A45C7FE514A5C4@MAILBOX.nameconnector.com> Message-ID: [Geoffrey Talvola] > ... > I understand what you're saying. Would it make a difference if I told > you that for this application, it's OK if the "get_nowait_reliable" > operation blocks for "a little while"? In other words, I don't mind if > it blocks while 17 other threads manipulate the queue. What I care > about is that once the queue is no longer being manipulated in other > threads, I either get an Empty exception or an object out of the queue. > For my purposes if the queue was empty at any point during the operation > then raising the Empty exception is OK. > > My requirements are a bit fuzzier than the strict no-blocking > requirement of Queue.get_nowait() so maybe it's possible to implement > this. > > In case you're wondering, this is in Webware's WebKit application server > where there is a pool of N threads, and a queue of (non-thread-safe) > servlet instances acting as a cache. We only want to create servlet > instances when all existing instances are in-use. When a given thread > needs a servlet, it basically does: > > try: > instance = cache.get_nowait() > except Queue.Empty: > instance = new_instance() > # use the instance... > cache.put(instance) > > The problem is that every once in a while get_nowait() returns Empty > when the queue isn't actually empty, so the size of the cache grows > slowly and unboundedly over time. How do you know that the unbounded growth is *due* to that get_nowait() returns Empty at odd times? If service requests follow the usual sorts of lumpy distributions, the code you showed above simply will create an unbounded number of instances over time, since it caters to peak simultaneous usage as if resources were unbounded. Fiddling the Queue implementation isn't going to cure that, if so. > But I'd prefer for the cache to contain at most N instances where N is > the number of threads. In that case, why not use a bounded Queue (the Queue constructor has an argument for this purpose) of maximum size N, and use blocking get? That gives up the illusion that resources are unbounded, but the heart of your complaint is that writing code as if resources were unbounded leads to unbounded resource usage . If your threads are returning instances correctly to the queue, then the block will never wait long -- unless it's really the case that N instances aren't actually enough to service the threads. From tim.one at comcast.net Tue Jul 16 23:54:43 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 16 Jul 2002 23:54:43 -0400 Subject: map del efficiency python2.2 and 2.1 In-Reply-To: Message-ID: [John Hunter] > ... > Here then is the synopsis (excluded runs where %CPU < 99%) > 2.1 2.1 2.1 2.1 > del m yes yes no no > del seq yes no yes no > run time 7.9s 7.6s 15.4s 7.4s > > 2.2 2.2 2.2 2.2 > del m yes yes no no > del seq yes no yes no > run time 7.6s 7.24s 15.6s 15.4s This is exactly the kind of "seemingly random disaster" we see when the platform free() goes nuts, although it's usually much more pronounced than a measly factor of 2. If so, rebuilding with pymalloc is likely to fix it, while if you don't you'll never answer "why?" without a deep understanding of your platform C's implementation of free(). > OK, I'll stop torturing you and me now. likewise-ly y'rs - tim From dreed at capital.edu Fri Jul 5 12:25:34 2002 From: dreed at capital.edu (Dave Reed) Date: Fri, 5 Jul 2002 12:25:34 -0400 Subject: Math irregularity ... is this normal? In-Reply-To: (message from Some One Else on Fri, 05 Jul 2002 00:54:56 GMT) References: Message-ID: <200207051625.g65GPYf14711@localhost.localdomain> Learning Python is based on python 1.5 which only prints0.4; as someone else pointed out, somewhere in Python 2.x this behavior changed: $ python1.5 Python 1.5.2 (#1, Apr 3 2002, 18:16:26) [GCC 2.96 20000731 (Red Hat Linux 7.2 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> 2/5.0 0.4 $ python2.2 Python 2.2.1 (#1, May 7 2002, 17:07:14) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2/5.0 0.40000000000000002 Dave > From: Some One Else > > Thank you Richard & Emile for your speedy responses! > > Still strange that a great book like LP showed a clean calculation ... > > Thanks! > -s.o.e. > > Richard Jones wrote: > > > On Fri, 5 Jul 2002 10:10 am, Some One Else wrote: > >> Hello! > >> > >> I just compiled and installed Python 2.2.1 on Linux-Mandrake 8.0. When I > >> > >> do the following: > >> >>> 2/5.0 > >> > >> 0.40000000000000002 > >> > >> In 'Learning Python', a similar example says I should get the more > >> logical > >> answer of 0.4. Did I install something wrong? I can see where this could > >> result in creeping math errors. > > > > Yes, this is normal :) > > > > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp > > > > > > Richard > > -- > > From me at michaelbauers.com Fri Jul 19 19:45:05 2002 From: me at michaelbauers.com (Michael Bauers) Date: Fri, 19 Jul 2002 18:45:05 -0500 Subject: text adventure game module for Python Message-ID: Having always been interested in languages for doing text adventures, I thought Python was the perfect match. I wrote a module that reads a file to create a parsing system, and then provides an interpreter to invoke methods based on matching input against the sentences in the file. e.g.'s "drop" object, player.drop(obj) "look", player.loc().look() "north", player.loc().move_north(player) If the user types in "drop rock", the interepreter will return a string like 'player.drop(rock)' which is then 'exec'd. Note that interperter excepts any string for object. The module also provides classes for common text adventure objects like room, and player. I post this to see if anyone finds this an interesting project, and would be interested in seeing it fully developed. Perhaps something like this would have uses beyond text adventures. Obviously they are mostly a thing of the past. From martin at v.loewis.de Fri Jul 19 12:23:11 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Jul 2002 18:23:11 +0200 Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: Johannes Graumann writes: > Basicely I have two lists, one containing the future string-names > and one containing the values I want to give them. The order is > identical in both. Right now I'm solving this by a dictionary, but > I would really prefer to have straight strings as a result of my > operation. > > Can anybody please tell me how to go about this and/or why I > totally shouldn't do this? I'm not quite sure what "this" is that you want to go about, or what "this" is that you want to solve. You say you have two lists - that, in itself, is not a problem; Python allows you to have as many lists as you want :-) If you want to know how to associate strings and values, without using a dictionary, I recommend to use a list of tuples, and the zip function >>> strings = ['a', 'b', 'c'] >>> values = [1, 2, 3] >>> zip(strings, values) [('a', 1), ('b', 2), ('c', 3)] That has the advantage of preserving the order of the strings, but the disadvantage that you can't use the string as a key easily. Regards, Martin From anton.wilson at camotion.com Mon Jul 1 14:57:39 2002 From: anton.wilson at camotion.com (anton wilson) Date: Mon, 1 Jul 2002 14:57:39 -0400 Subject: python threads and the linuxthread pthread library Message-ID: <200207011843.OAA30115@test-area.com> I've been attempting to understand how python threads will interact with my Linux system (mainly the linuxthread library and the scheduler). I've concluded that the python interpreter's context switching every 10 byte-codes will rely on the Linux scheduler to somehow switch between threads after one thread releases the global interpreter lock. However, I am a bit confused on how threads interact with the python interpreter at a low level. Is the Python Virtual Machine it's own thread? How do threads aquire the global interpreter lock once they are awoken? How exactly do the byte-codes for a particular thread get run by the Python interpreter? Does each thread run the interpreter? If anyone has any explanations, links, or pointers please let me know. Thanks, Anton Wilson -- Camotion Software Development From cliechti at gmx.net Fri Jul 19 18:18:34 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jul 2002 00:18:34 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: Rhymes wrote in news:8r1hjuk58o67amhuvfna5htpe2gtl3gnlr at 4ax.com: > When Python 2.3 will be released? > > I've read the "what's new" and i'm waiting generators and true > division :-) there is a nice little machine were using here called "guidos time machine"... ;-) just add these lines at the top of your file: from __future__ import division from __future__ import generators an you're fine with 2.2... chris -- Chris From davidccarson at hotmail.com Wed Jul 24 22:40:48 2002 From: davidccarson at hotmail.com (David Carson) Date: 24 Jul 2002 19:40:48 -0700 Subject: os.getlogin() raises OSError (errno 25) References: None <12257ec4.0207231946.583a2e93@posting.google.com> <1027489223.157336@yasure> Message-ID: <12257ec4.0207241840.409ed7c2@posting.google.com> Thanks, Donn. All I did was replace os.getlogin() with pwd.getpwuid(os.geteuid()). The effective uid is what I really wanted anyway. Cheers, David "Donn Cave" wrote in message news:<1027489223.157336 at yasure>... > Quoth davidccarson at hotmail.com (David Carson): > | Could someone please explain why the following runs fine if I type the > | input and end stdin with ctrl-D, but bombs when I pipe stdin to it. > ... > | loginName = os.getlogin() > | OSError: [Errno 25] Inappropriate ioctl for device > ... > | mandrake Linux 8.2 > > On NetBSD, it doesn't fail on a pipe, but man 2 getlogin mentions > that it used to, in some earlier version of NetBSD, specifically if > the process was not associated with a "login terminal." Details > vary from one platform to another (you don't want to know about the > setpenv business on AIX), but characteristically it's a function of > the terminal login session. In theory, you'd get at the controlling > terminal (if that's the same thing) by opening /dev/tty, and if you're > really desperate you could try that out to see if you can work around > some Linux brain damage: open /dev/tty read/write, dup unit 0/1/2 to > keep them around, dup2 the tty unit to 0/1/2, call getlogin, dup2 the > saved units back and close the dups. Of course it will be for naught > if /dev/tty isn't a terminal - I'm just speculating that the brain > damage is that GNU getlogin assumes /dev/tty is on 0 (or 1 or 2.) > > Incidentally, on NetBSD I get "root" although I am not root. That's > probably because my sshd failed to call setlogin() - I don't know, but > I've seen the same thing on other platforms for similar reasons. One > would not want to rely on this function for sensitive matters. It's > only good for a hint - if getuid() returns 0, you can try getlogin. > > Donn Cave, donn at drizzle.com From zopestoller at thomas-guettler.de Thu Jul 25 04:42:15 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Jul 2002 10:42:15 +0200 Subject: MimeType --> Full Name Message-ID: <3D3FB9E7.6010804@thomas-guettler.de> Hi! application/vnd.ms-excel --> "Microsoft Excel Sheet" I looked at the docu of the mimetype package, but did not find a function which returns the full name given an mime-type. Is something like this available? thomas From amuys at shortech.com.au Mon Jul 8 01:41:15 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 7 Jul 2002 22:41:15 -0700 Subject: COCOMO - appropriate for languages like Python? References: Message-ID: <7934d084.0207072141.17c249d@posting.google.com> Skip Montanaro wrote in message news:... > For example, in C I can write > > if ((c = gets(s)) == EOF) { > ... > } > > while in Python, even though I have to express that concept in two lines: > > s = sys.stdin.readline() > if s == "": > ... > > you can argue the Python code is less likely to contain a bug. Together, > the cost to create those two (fully debugged) lines of Python code may well > be less than the cost to create the one line of C code, not twice the cost > of the one line of C code, as COCOMO would estimate it. Of course you can argue that the Python code is definately less likely to contain a bug, as you can reasonably argue that the C code most definately does ;) Hint: Do-not use gets()!!! #include "buffer.h" /* Handles char* buffers, includes BUFFER_SIZE */ #include "list.h" /* Standard Linked List impl, used for vector scatter gather on input */ #include #include char *readline(FILE *in) { List *buffers = newList(); List *currBuffer = buffers; List *prevBuffer = NULL; int totalLength = 0; char *result = NULL; char *head = NULL; buffers->data = newBuffer(BUFFER_SIZE); buffers->data[0] = '\0'; while (fgets(currBuffer->data, BUFFER_SIZE, in) != NULL) { totalLength += strlen(currBuffer->data); if (currBuffer->data[strlen(currBuffer->data) - 1] == '\n') { break; } currBuffer->next = newList(); currBuffer = currBuffer->next; currBuffer->data = newBuffer(BUFFER_SIZE); } if (buffers->data[0] == '\0') { return NULL; } result = newBuffer(totalLength + 1); head = result; currBuffer = buffers; while (currBuffer != NULL) { strcpy(head, currBuffer->data); head = head + strlen(currBuffer->data); prevBuffer = currBuffer; currBuffer = currBuffer->next; delBuffer(prevBuffer->data); delList(prevBuffer); } return result; } if ((s = readline(stdin)) == NULL) { ... } So the actual C code equivalent is ~30 lines (I personally prefer to include whitespace) compared to 2. So a 15:1 cost factor is suddenly more reasonable. Note I haven't even attempted to compile the readline() function, and it assumes the existence of suitable buffer/list libraries (and accompaning logging/error functionality, readline() will be longer if error-recovery is required). However the really important thing to notice is that the language has very little to do with the number of lines. In fact for this trivial example C and python are equivelent in almost all meaningful measures once you have access to a decent IO library! This agrees with my personal experience and annocdotal evidence, that the libraries and frameworks used are at least as important as the language itself when determining programmer productivity. Hence the signifigant impact of Python's 'Batteries-included' approach (and I personally believe a signifigant part of the continued success of Perl courtesy of CPAN). Andrae Muys From pecora at anvil.nrl.navy.mil Wed Jul 24 17:28:27 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 24 Jul 2002 17:28:27 -0400 Subject: Numeric Q: How to get DBL_MAX, etc. in Python? Message-ID: <240720021728273627%pecora@anvil.nrl.navy.mil> In C there are platform-specfic, floating-point constants as follows defined in float.h, /* The largest double precision # */ DBL_MAX (* (double *) __double_max) /* The accuracy of double precision */ #define DBL_EPSILON (* (double *) __double_epsilon) /* The smallest double precision # */ #define DBL_MIN (* (double *) __double_min) Where do these reside in Python? I have looked over my Python manuals and done a Google search, but can't find any reference to them or float/double limits outside of some threads online that are requesting the same as me, but no answers. Are there standard Python functions or globals that return these values for the platform one is operating on? Any help appreciated. Thanks. (I am posting this on the Python Mac Sig list and the Python NG, so sorry if you are seeing it twice.) -- Lou Pecora - My views are my own. From mgilfix at eecs.tufts.edu Fri Jul 26 11:12:40 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Fri, 26 Jul 2002 11:12:40 -0400 Subject: how to count lines in a file ? In-Reply-To: ; from tdelaney@avaya.com on Fri, Jul 26, 2002 at 01:06:28PM +1000 References: Message-ID: <20020726111240.A3461@eecs.tufts.edu> Ok. That cleared it up. Thanks. I can't say that I've used the __del__ method in a long time but I do remember that when I had used it, I expected that python would always invoke it at some point, even at shutdown of the interpreter. It seems the only really useful thing for __del__ is if someone wants to explciitly 'del object' instead of something like 'object.shutdown()'. But I'm sure you can give me a better use case at any rate. But for the most part, gc semantics mean that __del__ loses its usefulness. -- Mike On Fri, Jul 26 @ 13:06, Delaney, Timothy wrote: > Do you gain anything? Decreased performance perhaps. Some flexibility if you > want to intercept some method calls, etc. For the stated purpose though, no. > > Refcount system: > > Proxy object is created and assigned to a name > proxy refcount incremented > File object is assigned to field of proxy object > file refcount incremented > Proxy deleted > proxy refcount decremented > proxy collected > file refcount decremented > file collected (and closed) > > Non-refcount system: > > Proxy object is created and assigned to a name > proxy is referenced > File object is assigned to field of proxy object > file is referenced > Proxy is deleted > proxy not referenced - candidate for collection > Time passes > Proxy is collected > file is not referenced - candidate for collection > Time passes > File is collected > > In a refcount system (with no cycles), you have a reasonable guarantee that > all the garbage will be collected (there are cases where it will not happen, > but they are all due to abnormal termination). > > In a non-refcount system, garbage will hang around for an indeterminate > period of time. If your program finishes before that garbage is collected, > it may never be collected (and any code in the finaliser will not be run). > > CPython uses refcounts for everything, but if an object is involved in a > cycle there is an indeterminate period of time before cycles are broken, > meaning that they will not be collected when the last non-cyclic reference > is removed. > > This did not affect files, because files could not become involved in > cycles. There was a proposal which would have involved every file being in a > cycle. Files would then have not gone away when people expected (luckily for > people with such broken code, the devs care about them). > > In Jython (and JPython) it has always been the case that you can't rely on > things going away immediately, since they use Java garbage collection. Now > it's starting to become an issue in CPython. The only reason it *is* an > issue in CPython is because many people don't clean up the resources they > use when they're finished with them, counter to the strong recommendation in > the Python documentation. > > Tim Delaney > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (tdelaney) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From aleax at aleax.it Sun Jul 14 04:23:32 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 14 Jul 2002 08:23:32 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d30999a_4@news.newsgroups.com> Message-ID: <8yaY8.64509$Jj7.1677484@news1.tin.it> JB wrote: >> I bet you >> can do better by exploiting the specifics of this case!-) > > Well, I can use the fact that I know the maximal sorting key > in advance. So I can append sentinel entries to both lists > and this makes things much easier. Yes. While this may not be the optimal solution to your actual problem (as I notice the thread is now exploring quite different architectures), it's getting better as a solution to the problem you originally expressed about "moving list entries", as per subject. Untested code below, but getting a bit more readable, I hope...: au = [None] * 2 def prepare(au, alist, idx): alist.append(sentinel) it = iter(alist) au[idx] = [ it.next(), idx, it.next, [] ] prepare(au, list1, 0) prepare(au, list2, 1) # naming the items of au's items helps readability: ITEM, INDX, ITER, LIST = range(4) # writing complicated expressions as functions also helps: def moredata(au): return au[0][ITEM} != sentinel or au[1][ITEM} != sentinel while moredata(au): m = min(au) i = m[INDX] if i and f(m[ITEM]): i = 0 au[i][LIST].append(m[ITEM]) m[ITEM] = m[ITER]() # now, both lists are exhausted, so just copy the results back list1[:] = au[0][LIST] list2[:] = au[1][LIST] sentinel is any value > max(max(list1), max(list2)). Alex From j_r_ashley at MAKGifts.com Thu Jul 4 05:35:48 2002 From: j_r_ashley at MAKGifts.com (James Ashley) Date: Thu, 04 Jul 2002 09:35:48 GMT Subject: Efficient python programming... References: <3D00A456.4315EDA3@engcorp.com> <3d238f6b.579164824@news.dsl.pipex.com> <3D23D092.4E3AD523@engcorp.com> Message-ID: In article <3D23D092.4E3AD523 at engcorp.com>, Peter Hansen wrote: > Simon Foster wrote: >> >> On Fri, 7 Jun 2002 21:03:08 +0100, "James Kew" >> wrote: >> >I favour Kent Beck's aphorism: "Make it work, make it right, make it fast." >> > >> I prefer this one: >> >> "You can have it right" >> "You can have it cheap" >> "You can have it now" >> >> Pick any two. > > Interestingly, XP provides a way to have all three... Arguably. To an extent. More or less. Maybe. XP is interesting, for a particular software environment. Its basic truths (as I understand them) seem worth researthing. It seems like a more efficient way to develop software than trying to get the customer to make any actual decisions before-hand. But does that discussion belong here? Seems to me that there are plenty of python-specific theads going on. There seem to be many other places to examine this forum. Then again, just because this is c.l.py: TRUE=-1 FALSE=0 { right: (TRUE, FALSE), cheap: (TRUE, FALSE), quick: (TRUE, FALSE) } What's a pythonic way to compare that dict? Or would it make more sense to make a list of classes? class right: pass class cheap: pass class quick: pass if isinstance( a, ... ): ... elif instance( a, ...) : No, that's not right either. Any suggestions? (Including, of course, those which make me feel stupid...those are actually preferable) TIA, James From phr-n2002b at NOSPAMnightsong.com Wed Jul 10 20:45:22 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 10 Jul 2002 17:45:22 -0700 Subject: List assignment, unexpected result References: Message-ID: <7xptxv5bz1.fsf@ruckus.brouhaha.com> "Steve Coates" writes: > Thanks for the help. I think my favourite solution was > > grid = [['.' * 4] for i in range(4)] > > but I'll need to read up on the syntax. I haven't seen this > use of a for loop before. That's not a for loop, it's a new Python gizmo called a list comprehension. List comprehensions were introduced in Python 2.0. You can find more info about list comprehensions in the Python docs. But if your script has to work under earlier Python versions than 2.0, don't use them. From aahz at pythoncraft.com Sun Jul 14 13:33:31 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Jul 2002 13:33:31 -0400 Subject: Running multiple functions with Python 1.5 References: <20020714113045.08255.00000535@mb-fj.aol.com> Message-ID: In article <20020714113045.08255.00000535 at mb-fj.aol.com>, Musicmaker1118 wrote: > >I am trying to make a simple windowing system in python 1.5 that can >run using minimal memory. I would like for it to be able to display >icons, and to be able to run programs assosciated with them when you >click on them. I would also like it to be able to run simple programs >inside of a window. To do this this, I need to be able to run programs >and monitor the movements of the mouse to display the cursor. I plan >on using a C extension for the graphics and monitoring the mouse. The >functions it defines will be run by the python code. But I am not sure >if Python 1.5 can be running different functions at the same time, and >if it is possible, how to do it. Does anyone know how this could be >done? If so, I would like to know. What are you defining as "minimal memory"? Why do you want to use Python 1.5 instead of a newer version? What's wrong with using one of the existing graphics libraries available for Python? What OS are you targeting? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From tim.one at comcast.net Mon Jul 22 17:52:23 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 22 Jul 2002 17:52:23 -0400 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: <7xfzybii29.fsf@ruckus.brouhaha.com> Message-ID: [Paul Rubin] > Ouch!! That doesn't sound so good for the Zaurus. > > Is the idea here to discover if a*b overflows 32 bits, if a and b are > 32 bit ints? The idea is to discover whether Python int * int overflows, which translates to whether C long * long overflows a C long, regardless of its size. > On compilers supporting 64-bit (long long) ints, it may be faster to > use them instead of floating point for this check. You're welcome to pursue it. Note that on platforms where sizeof(long) == 8 (like 64-bit Linux, but not 64-bit Windows), sizeof(long long) is usually 8 too. > I think that includes GCC and current Microsoft compilers among others. Yes, although MS doesn't spell it "long long". > It may even be ok to synthesize 32-bit multiplication from several > 16-bit multiplications, to avoid these overflows. A generalization (without the bogus 32-bit assumption) is what the 2.1 int mult overflow-checking code tried to do. It almost always worked; IIRC, it raised a bogus OverflowError if the true product was exactly -sys.maxint-1. It was also responsible for the infamous "LONG_BIT definition appears wrong for platform" bug when building Python on an old Linux release that shipped with a bad set of header files. Note that it's faster to use a few float operations on a modern Pentium, and that's overwhelmingly Python's most popular HW platform. From musicmaker1118 at aol.com Sun Jul 14 13:53:41 2002 From: musicmaker1118 at aol.com (Musicmaker1118) Date: 14 Jul 2002 17:53:41 GMT Subject: Running multiple functions with Python 1.5 References: Message-ID: <20020714135341.14980.00000518@mb-mc.aol.com> What I mean by minimal memory is a computer with somewhere between 7 and 8 megabytes of ram. I am targetting Linux. I am using python 1.5 because I am running a version of linux based on slackware 3.5 on the computer I am making this for. It was one of the packages for Slackware 3.5. The computer has no internet connection and the only way I can transfer files to it is using a 1.44 megabyte floppy disk. Most graphics libraries I have seen for python seem to require that you already have a windowing system, which seem to be big and require alot of memory. I am trying to make my own minimal windowing system to use on this computer besause all other ones I have seen probably won't work on it. Plus I could get more practice writting in C that way. I am sorry I was not clear on some points. If you know of anything that could make this easier please tell me. Anyway, can Python 1.5 run multiple functions at the same time? From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 09:56:27 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 08:56:27 -0500 Subject: map del efficiency python2.2 and 2.1 References: Message-ID: >>>>> "Tim" == Tim Peters writes: Tim> This is exactly the kind of "seemingly random disaster" we Tim> see when the platform free() goes nuts, although it's usually Tim> much more pronounced than a measly factor of 2. If so, Tim> rebuilding with pymalloc is likely to fix it, while if you Tim> don't you'll never answer "why?" without a deep understanding Tim> of your platform C's implementation of free(). pymalloc to the rescue. I rebuilt 2.2 --with-pymalloc and the interminable delay was vanquished. Now where do I go to get a deep understanding of my platform's (glibc 2.2.2) implementation of free and why it behaves so badly? Thanks for the help John Hunter From brueckd at tbye.com Mon Jul 22 15:07:37 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 22 Jul 2002 12:07:37 -0700 (PDT) Subject: setting the screen resolution In-Reply-To: <6edeb2ff.0207220845.86b6ebd@posting.google.com> Message-ID: On 22 Jul 2002, Chad Haynes wrote: > i am currently working on a program using wxPython which requires the > screen resolution to be 1024x768. is there a way to set this from > python? Why not just scale to fit inside the app's window? I'd be ticked if an app changed my screen resolution! -Dave From huaiyu at gauss.almadan.ibm.com Fri Jul 12 13:45:15 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 12 Jul 2002 17:45:15 +0000 (UTC) Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: Fran?ois Pinard wrote: >[Peter Hansen] > >> XML was adapted from SGML to meet several key goals. Among those was >> the desire to make a format which was easily human-readable and editable >> using simple tools like text editors. > >I do not think so. SGML already has these virtues, and much more than XML. >The main goal of XML was to please machines, because full SGML is so >difficult to parse. The price to pay to please machines was a loss of >readability for humans. XML is so verbose that real information gets >overwhelmed under tags. The fish often gets drawn in practice. Readability for machines does not have to come at the expense of readability for humans. A few years back I experimented with an indentation based data format that is: - as readable as emacs's outline mode - reduce to common conventions like this paragraph for simple cases - allow mixed nested structures of set, sequence, dictionary, and seqdict - can include binary data - can handle different encodings/encryptions in different elements - with average less than 5% bloat, in contrast to XML's over 100% bloat Then I learned that there was something called XML which was already (going to be) wide-spread, and somehow put off my own data format for some later date. However, the more I learn about XML, the more I find it badly designed as a universal data exchange format. > This being said, XML has been immensely successful, at least in the >democratic fields, because it is so easier to implement. Moreover, many >people consider it is an acceptable compromise between humans and machines. >But at least compared to SGML, we have to remember that it is a compromise >away from humans and towards machines, and never turn the argument around. As with many other inventions in the history, the success of XML is more of a result of some opportune associations than of a result of its internal strength. Huaiyu From marklists at mceahern.com Fri Jul 19 00:02:03 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 18 Jul 2002 23:02:03 -0500 Subject: Nested scopes question In-Reply-To: Message-ID: > In the following code: > > def foo(): > def bar(): > print 'x from foo',x > x+=1 > > x=0 > for i in range(5): > bar() > > foo() This seems to me a clearer statement of what I think you're trying to do: def make_bar(x): def bar(): print x x += 1 return bar def foo(): x = 0 bar = make_bar(x) for i in range(5): bar() foo() ** This is the result: $ python junk.py Traceback (most recent call last): File "junk.py", line 13, in ? foo() File "junk.py", line 11, in foo bar() File "junk.py", line 3, in bar print x UnboundLocalError: local variable 'x' referenced before assignment You might want to read this thread: http://groups.google.com/groups?selm=3B98F3B0.53AC2524%40swiftview.com As Frederik Lundh points out: http://groups.google.com/groups?selm=Eo7m7.53652%24e5.2684084%40newsb.telia. net once you bind x in bar(), it is considered local. End of story. If I remember correctly, this is the example Paul Graham used to make fun of Python as not yet quite having evolved into Lisp. ;-) // mark - From debl2nonospammyyy at bellatlantic.net Thu Jul 11 21:49:31 2002 From: debl2nonospammyyy at bellatlantic.net (David Lees) Date: Fri, 12 Jul 2002 01:49:31 GMT Subject: How to replace multiple-line text References: <3D2D0782.45FCEC98@bellatlantic.net> Message-ID: <3D2E35C6.5B2612CF@bellatlantic.net> Thank you kindly Alex for this solution. This is the problem that I had in mind. You also taught me something rather basic about Python that I misunderstood I thought that to use string methods I needed to import the string class and then use it like this: >>> import string >>> x='this is junk' >>> string.replace(x,'junk','stuff') 'this is stuff' Time to do some more reading on classes, since I don't understand why it is not necessary to import string here. Alex Martelli wrote: > > David Lees wrote: > > > I would like to process a code file and substitute one multiline block > > of code for another. I know how to do this in Python by brute force > > scanning through on a line by line basis until the first line of the > > pattern is found then looping over the rest of the lines in the target > > pattern for a match, then substituting in an output string multiline > > substitution. But I am sure there is a neater solution, perhaps using > > regular expressions. Could someone point me towards sample code or > > something similar that I could modify. > > The simplest approach, a step-by-step example for clarity: > > old_lines = """Tyger, tyger, burning bright > in the forests of the night, > what immortal hand or eye > dare frame thy fearful symmetry?""" > > new_lines = """Do not go gentle into that good night, > Old age should burn and rave at close of day; > Rage, rage against the dying of the light.""" > > old_file = open("oldfile.txt") > old_text = old_file.read() > old_file.close() > > new_text = old_text.replace(old_lines, new_lines) > # other changes to new_text, if needed, go here > > new_file = open("oldfile.txt") > new_file.write(new_text) > new_file.close() > > The only possible problem with this approach is that if the files > involved are truly huge you might not have space in memory for the > text involved (about twice as much as the file's size plus a little). > > For a "code file" this is quite unlikely -- how many megabytes of > code will there be even in a large such file, after all? So, in > practice, for the need you've expressed, this approach is almost > surely the best one. > > The theoretical problem in terms of substituting substreams of > input streams on the fly is also interesting, but I doubt it's of > much actual applicability to your case. > > Not sure what regular expressions would have to do with the case. > I see it as a case of bunching. Matching multiline text, as long > as you manage to get it in memory, is just as easy with string > operations as with re's if it's an exact match you're lookin for -- > re's would be useful if you needed more sophisticated matching, > but they still need the file's contents to be in memory. > > Alex From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 17:04:25 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 14:04:25 -0700 Subject: performance problem in python 2.2 References: Message-ID: <7xznweurom.fsf@ruckus.brouhaha.com> Jeff Davis writes: > c = long(sys.argv[1],10) > > for i in range(1,c): > n = (n * (p-i)) / p > print 1-n The problem is range(1,c) builds up a c-element list in memory. Use xrange instead, which makes an object holding only the current iteration value. For extra credit, solve the problem without a computer. E.g., suppose you want to know the sum 1+2+3+...+999+1000. You can add it up with a program or you can do it without a computer with a little cleverness. Solving your birthday paradox problem needs a little bit more math than 1+2+3+...+1000, and the answer you get will be a close approximation rather than exact, but with similar cleverness you should be able to get a fairly simple formula. From rnd at onego.ru Tue Jul 30 08:10:33 2002 From: rnd at onego.ru (Roman Suzi) Date: Tue, 30 Jul 2002 16:10:33 +0400 (MSD) Subject: Unicode classes of characters in Pythons' re's like in Perl? In-Reply-To: Message-ID: On 30 Jul 2002, Martin v. [iso-8859-15] L?wis wrote: > Roman Suzi writes: > So far, nobody has proposed to support Unicode categories in SRE. You > can easily implement this yourself by means of using > unicodedata.category, e.g. OK. Thanks. Probably, there should be pre-compiled categories somewhere in the standard library... Say, in RE module. > It turns out that those categories are useless for XML, since the XML > character classes (in XML 1.0) have been defined using a different > Unicode versions (XML uses the Unicode 2.0 database). The same appears > to be the case for XML Schema: They use the Unicode 3.1 database; > Python 2.2 has the Unicode 3.0 database. Isn't Python one of the best choices for XML processing ;-) > So to implement XML Schema, you probably have to parse the specific > version of the Unicode database yourself, and construct the re class > from that. > Regards, > Martin Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From kristian.ovaska at helsinki.fi Sat Jul 27 05:10:07 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Sat, 27 Jul 2002 12:10:07 +0300 Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: <8ro4ku4v5lc3u66quet6ieg8m18boc4bq5@4ax.com> bokr at oz.net (Bengt Richter): [f.readlines(N)] >That bothers me. ISTM it should return as many lines as >will fit in N bytes, but no more. Otherwise you have no >memory use protection against a single monster line You can't have complete protection in any case: what if there is a line of length > N? (Or length >> N...) -- Kristian Ovaska From barry at zope.com Mon Jul 29 13:53:24 2002 From: barry at zope.com (Barry A. Warsaw) Date: Mon, 29 Jul 2002 13:53:24 -0400 Subject: RELEASED Mailman 2.0.13 Message-ID: <15685.33044.698790.315924@anthem.wooz.org> I've released version 2.0.13 of Mailman, the GNU Mailing List Manager. Mailman is released under the GNU General Public License (GPL). Version 2.0.13 fixes some incompatibilties with Python 1.5.2 that crept into Mailman 2.0.12. This also fixes a minor configure incompatibility on Solaris platforms (and possibly others). If you're using Python 1.5.2 with Mailman 2.0.12 you should definitely upgrade. The upgrade is safe if you're using newer Python versions too. See the NEWS file excerpt below. GNU Mailman is software to help manage electronic mail discussion lists. Mailman gives each mailing list a unique web page and allows users to subscribe, unsubscribe, and change their account options over the web. Even the list manager can administer his or her list entirely via the web. Mailman has most of the features that people want in a mailing list management system, including built-in archiving, mail-to-news gateways, spam filters, bounce detection, digest delivery, and so on. Mailman is compatible with most web servers, web browsers, and mail servers. It runs on any Unix-like operating system. Mailman 2.0.13 requires Python 1.5.2 or newer. To install Mailman from source, you will need a C compiler. For more information on Mailman, including links to file downloads, please see any of the Mailman mirror web pages: http://www.gnu.org/software/mailman http://mailman.sourceforge.net http://www.list.org Patches and source tarballs are available at http://sourceforge.net/project/showfiles.php?group_id=103 There are email lists (managed by Mailman, of course!) for both Mailman users and developers. See the web sites above for details. Cheers, -Barry -------------------- snip snip -------------------- 2.0.13 (29-Jul-2002) - Fixed some Python 1.5.2 compatibility problems that crept into Mailman 2.0.12. - Fixed some configure script incompatibilities on certain platforms. From andymac at bullseye.apana.org.au Fri Jul 5 06:01:28 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 5 Jul 2002 21:01:28 +1100 (edt) Subject: Threads, signals, and fork In-Reply-To: Message-ID: On Thu, 4 Jul 2002, Michael Hudson wrote: > Interestingly, the behaviour on FreeBSD was deemed to be a bug in > their libc_r, but this only helps people who are running versions of > FreeBSD that haven't been released yet... Been meaning to let you know that that fix is in the FreeBSD 5.0 (aka -CURRENT) development branch and is expected to be backported to the -STABLE branch for 4.7 (nominally due Oct/Nov this year). -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From tismer at tismer.com Mon Jul 29 07:09:00 2002 From: tismer at tismer.com (Christian Tismer) Date: Mon, 29 Jul 2002 13:09:00 +0200 Subject: Guide to the python interp. source? References: <1027848147.20536.125.camel@vaio2> <15684.23324.498143.792539@localhost.localdomain> Message-ID: <3D45224C.8050208@tismer.com> Skip Montanaro wrote: > >> I noticed, but thought that I just had missed it. I thought there > >> must be some where for such a large project. But the problem is > >> ofcourse ever present, "nobody likes to do documentation" > > Something occurred to me last night... How about a PyVM Wiki? Once the > content is there we could see about organizing it in a suitable form for > inclusion in the standard document set. > > I started things off with some notes I wrote a few months ago: > > http://manatee.mojam.com/pyvmwiki/ Nice starter! I'd like to contribute. Looking into the HTML I saw you are using moinmoin :-) Just a remark: All the icons appear to be broken, for example: 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 shagshag13 at yahoo.fr Mon Jul 8 09:28:00 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 8 Jul 2002 15:28:00 +0200 Subject: Memory ? References: Message-ID: I have a data structure like this : key_0 -> value_0_? -> value_0_? -> ... value_0_m key_i -> value_i_? -> value_i_? ... key_n -> value_n_? -> value_n_? -> value_n_? -> value_n_? where : - key are characters, - value are float - n > 2,500,000 - value "list" can have length from 1 to m = ~1,000,000 (values from key_i could be 1 long, while key_i+1 could be 1,000,000) - i didn't knew exact value for n (it depends on input data) - i can guess m by now i use a dict index for key, which give me access to a queue (list) containing my values. that's really to slow !!! with your helps, i think i should use a numeric.array for my values list, but i even wonder if i shouldn't use a matrix (2,500,000 * 1,000,000) even if it should be quite empty. Which one do you think is best (memory & time -- i do some others calculations by line ) ? > Function Numeric.concatenate, which you mention, also returns a new copy, > and thus is similarly free from any worry. my needs for concatenate is just to add a new value (one at a time) at the end of my values list (which could be 1 long and possibly grow to m). thanks, s13. From sadams123 at optushome.com.au Mon Jul 8 12:27:17 2002 From: sadams123 at optushome.com.au (Steven) Date: Tue, 9 Jul 2002 02:27:17 +1000 Subject: Multi-threading on Multi-CPU machines References: Message-ID: <3d29bd68$0$11270$afc38c87@news.optusnet.com.au> "Garry Taylor" wrote in message news:f0fd5987.0207080702.407100ec at posting.google.com... > Hello, > I am attempting to make a multi-threading function in one of my > programs in an effort to gain a speed increase, but I'm getting quite > the opposite, even on a dual-CPU Intel/Linux box. Can anyone enlighten > me as to why, my code is below: ..... > > This does the same thing, threaded and then not, but on all of my > machinbes, the multi-threaded is slower, what can I do about this? does the Python interpreter run on both CPU's? that is, do you have the Python threads executing concurrently on both CPU's, I'd imagine that they would be, but just wondering... I tested on my machine, which is a single AthlonXP 1900, and get times of about 3.6 and 3.4 for the Threader and NoThreader versiosn respectively, and I'd attribute a fair bit to the creation time for a thread, though I don't have any real timing to back that up. I did change it slightly so that the function passed did no work, so it was basically just the overhead of setting up and finishing a thread, and the threaded version took much longer than the non-threaded (as you'd expect on a single CPU machine). As it is, although you can have a CPU running each tasks, you still do very frequent checking of variables that are global to the whole thing, so that constant checking of the THreadCounter is going to introduce an overhead that isn't present on the non-threaded, as is the increment operation in each thread, the non-threaded version doesn't have the overhead of changing the variable on whatever CPU its sitting. If there were a method running half the threads on one CPU, and half on the other, and not communicating with that 'parent' until the very very end, when all of each thread-spawners threads had completed, then you might see a performance increase. I'm sure someone with a better knowledge of threading on Python can give you a better answer... Steven From gerhard.haering at gmx.de Mon Jul 22 14:04:52 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 22 Jul 2002 20:04:52 +0200 Subject: correct syntax for db api.. In-Reply-To: <3D3C43C3.6090605@sschwarzer.net> References: <3D3C43C3.6090605@sschwarzer.net> Message-ID: <20020722180452.GC980@lilith.my-fqdn.de> * Stefan Schwarzer [2002-07-22 19:41 +0200]: > Hi Eugene Kim > > eugene kim wrote: > >import pgdb > > > >db=pgdb.connect(user='postgres',database='test') > >cursor=db.cursor() > > > >----------------- > >cursor.execute('select url, visits from history where url= %s', > >(self.url)) ------------- > > As a side note, (self.url) is an expression, not a tuple. Both should work. Only the tuple form is guaranteed to work with the DB-API. Though most modules implement the nonstandard extension of a single argument as the value paramater. You can make a tuple of length one like so: (1,) > >or > >----------------- > >sqlselect = 'select url, visits from history where url = %s ' > >cursor.execute(sqlselect % self.url) > >---------------- > > Perhaps you have to use quotes: > > sqlselect = "select url, visits from history where url='%s'" > cursor.execute(sqlselect % self.url) No! Definitely not. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From aahz at pythoncraft.com Mon Jul 29 12:00:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2002 12:00:13 -0400 Subject: Python design failures (was Re: Let's Talk About Lambda Functions!) References: <3d455445_9@news.newsgroups.com> Message-ID: In article <3d455445_9 at news.newsgroups.com>, JB wrote: >Tim Peters wrote: >> >> two language features are mentioned as being "failed >> experiments" that only compatibility prevents throwing >> away: >> >> `back ticks` >> lambda > >(1) Why are back ticks a failure? I love them. If you're using backticks frequently, you're probably not programming Pythonically. There's already repr() to produce the same result as backticks, and backticks have the problem that in many fonts they're nearly indistinguishable from single quotes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From shagshag13 at yahoo.fr Wed Jul 24 11:32:54 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 24 Jul 2002 17:32:54 +0200 Subject: xml processing : too slow... References: Message-ID: "Alex Martelli" a ?crit dans le message de news: xDz%8.132158$vm5.4351067 at news2.tin.it... > Shagshag13 wrote: > > > hello, > > > > i need to process *each line* of many huge files (> 2 million lines) with > > xml processing, by now i do it with parseString from xml.dom.minidom and > > it's work. > > *shudder* don't use minidom except on SMALL files!!! yes, but i use minidom on a small amount of data at once because i do something like : f = file(filename) while 1: line = f.readline() if line.find(' Message-ID: <8H909.142832$vm5.4656397@news2.tin.it> Michael Hudson wrote: > Alex Martelli writes: > >> Other smart editors such as SciTE (a tiny elegant wrapper on the >> Scintilla component that IDLE and others use) > > I thought IDLE used Tk's Text widget. Sorry, you're right -- it's PythonWin that uses Scintilla, not IDLE. Alex From christophe.delord at free.fr Fri Jul 19 02:31:05 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Fri, 19 Jul 2002 08:31:05 +0200 Subject: Recursion References: Message-ID: <20020719083105.5c01b6a4.christophe.delord@free.fr> Try this: def bits(x): return (x!=1 and bits(x>>1) or "") + "01"[x&1] The idea is to return the string instead of printing it. or this if you prefer: def bits(x): if x != 1: s = bits(x>>1) if x & 1: s = s+"1" else s = s+"0" return s On Fri, 19 Jul 2002 05:55:53 +0000 (UTC) Abhijit Soman wrote: > In the recursive function below i want to add the individual bits to a > string and return that string to the caller > Can anyone tell me how to do that > > > def showbits(x): > if x != 1: > showbits(x >> 1) > if x & 01: > print 1, > else: > print 0, > -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From not.this at seebelow.org Fri Jul 19 15:24:08 2002 From: not.this at seebelow.org (Grant Griffin) Date: 19 Jul 2002 12:24:08 -0700 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <190720021018041866%pecora@anvil.nrl.navy.mil> <3D385A46.6DC47857@astro.cornell.edu> Message-ID: In article <3D385A46.6DC47857 at astro.cornell.edu>, Tom says... > >"Louis M. Pecora" wrote: >> >> Many people have suggested doing something like the following (which is >> reasonable) to eliminate self. from mathematical expressions: >> >> t, x, y, z=self.t, self.x, self.y, self.z >> result=sin(t)*x**y+sqrt(z) # A pretend formula > >Yes, this was suggested earlier. I don't consider it a great solution >to the problem. For example, in a current calculation I have a class >with many member variables and many member functions that use them >to return various quantities. In a language that boasts of how I don't remember any "boasting". Python is for the humble (except for maybe Tim and Fredrik ). >simple and straightforward it is, and how it shrinks code size (by >omitting braces, declarations, etc.), it is rather silly to have >lines like: > > t, x, y, z=self.t, self.x, self.y, self.z > >in every one of many member functions, often with the same variables. >You look at that code, with all those redundant lines of negligible >content, and it yells out to you: something is missing here that >should make this silly copying unnecessary in order to have expressions >that are easy to read/understand. > >The language is so great in other respects, and on a fundamental level >the arguments for "self." are so sound, that I just live with this. >But it sure is a nuisance. I was thinking about this just a few days ago. I had found a book about Ada on our "unloved software books" shelf at work. (In fact, there were six copies of it, so Ada must be pretty unloved .) I read a little of it, and it turns out that Ada provides "with", which is the one-and-only construct I missed when I moved from Pascal (Ada's daddy) to C many years ago. For example: with self: result=sin(t)*x**y+sqrt(z) # A pretend formula I don't know if there's a technical reason (in terms of either Python grammar or C implementation) why this wouldn't work, but perhaps it's not in Python because: 1) explicit is better than implicit 2) there should be one--and preferably only one--way to do things or maybe even 3) it hasn't happened yet (At one time, I used to think "augmented assignment" was left out of Python because of 1) and 2), but it turned out to be 3). Silly me .) any-construct-that's-in-pascal-and-ada-but-not-in-C -can't-be-all-bad--ly y'rs, =g2 or, as we would say in Pascal: :=g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From aahz at pythoncraft.com Thu Jul 11 14:03:34 2002 From: aahz at pythoncraft.com (Aahz) Date: 11 Jul 2002 14:03:34 -0400 Subject: Python in the enterprise: Pros and cons References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: In article , Max Ischenko wrote: > builder wrote: >> >> Python has many fans in the open source community, but is it ready for >> the enterprise? Here are the advantages and disadvantages of using >> Python in the corporate environment. >> http://builder.com.com/article.jhtml?id=u00420020709DGS01.htm > >After reading their ah...well...stupid >article about XP, I won't even bother to look at this. It's written by Dan Shafer, who actually knows something about Python; builder.com is only the publisher. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jwilhelm at outsourcefinancial.com Sun Jul 14 16:26:13 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 14 Jul 2002 13:26:13 -0700 Subject: python2 import trouble (linux - redhat) In-Reply-To: <20020714141757.128895ce.mmellor1@yahoo.com> References: <20020714141757.128895ce.mmellor1@yahoo.com> Message-ID: <1026678374.6881.6.camel@jwilhelm.ofsloans.com> On Sun, 2002-07-14 at 11:17, Mike Mellor wrote: > Hello - > > I am using RH7.2, and have the following python packages > installed: > > > I am having trouble importing modules with python2 (Python 2.2) that I think should be > there, for example, _gtk and GTK. What do I need to do to get > python (actually python2) to import these modules? > I believe, off the top of my head, that all of the Python packages you have installed are only for Python 1.5.2, since this is the default Python distribution provided in RedHat (Although this appears to have changed in the most recent beta! Woohoo!). What I have done in the past is to build the gnome-python package myself. You can get the most recent stable gnome-python packages here: ftp://ftp.gnome.org/pub/GNOME/stable/sources/gnome-python/ Right now, last I heard, they are still running on gtk1.x, but the gtk2.x port is well on its way, and should be available "soon". But that's just what I've heard. It may still be a while out. Hope that helps --Joseph Wilhelm From dcinege at psychosis.com Thu Jul 25 05:44:41 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Thu, 25 Jul 2002 05:44:41 -0400 Subject: cmd, readline, and /path/filename completion In-Reply-To: <200207250040.58148.dcinege@psychosis.com> References: <20020724175117.B3904@eecs.tufts.edu> <200207250040.58148.dcinege@psychosis.com> Message-ID: <200207250544.41572.dcinege@psychosis.com> On Thursday 25 July 2002 0:40, Dave Cinege wrote: > I'm by no means a coding novice, and I already know I (or somewhere in > readline) must walk the path and gather a list of executable files. Where > I'm lost is how to pass this to readline. (Or activate it in readline) Just needed to do more homework. The thing to do in my situation is to override the 'completenames' method of cmd. The method below completes all executeables in the path just like bash. What confused the hell out of me is I couldn't get 'completedefault' to do anything. Viewing the cmd modules showed that is only run when the completer index is > 0. Thus, 'commands' (the beginning of a line) is run against completenames... def completenames(self, text, line, begidx, endidx): l = cmd.Cmd.completenames(self, text, line, begidx, endidx) path = os.environ['PATH'].split(':') textlen = len(text) for dir in path: try: files = os.listdir(dir) except: continue for file in files: if textlen > 0 and file[:textlen] != text: continue if os.access(dir+'/'+file, os.X_OK): l += [file] return l -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From jonathan at onegoodidea.com Thu Jul 4 05:11:52 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 10:11:52 +0100 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: On 4/7/2002 8:40, in article eaef2e43.0207032340.6ccf12c3 at posting.google.com, "Robert Kuzelj" wrote: > it is implicit cause i dont want to ask what kind of > class that is but if it is an instance. I also don't think of it as implicit. It's explicit, just the other way around. If you divide the universe of objects into "class" or "instance", then "not class" is as good as "instance". > that is is is it an object > created by an instantiation-action (aka x = X()) this is very > clearly distinglishable im my code from creating a class-object > (class X:...). Unfortunately, whilst distinguishable in the code, the underlying mechanism is indistinguishable. A class declaration like this: >>> class foo( object ): ... def hello( self ): ... print 'Hello World' ... >>> foo >>> f = foo() >>> f <__main__.foo object at 0x40a810> >>> f.hello() Hello World >>> is actually executed as the (mostly) equivalent code: >>> def hello( self ): ... print 'Hello World' ... >>> foo = type( 'foo', (object,), ... {'hello':hello, '__module__':__name__} ) >>> foo >>> f = foo() >>> f <__main__.foo object at 0x40a5d0> >>> f.hello() Hello World >>> That is why you can't determine if an object is a class or not without checking to see if its type is 'type' (or 'ClassType'). A class *is* an instance - not just theoretically, but in the concrete "a constructor was called to make this thing" kind of way. If you want to work on Python's typing system you'll have to get your head around this. Jonathan From fakeaddress at nowhere.org Sun Jul 28 03:49:23 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 28 Jul 2002 07:49:23 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> <7x3cu6f8sv.fsf@ruckus.brouhaha.com> Message-ID: <3D43A241.1060207@nowhere.org> Paul Rubin wrote: > I don't see why the anti-lambda contingent doesn't want to also > get rid of anonymous scalar expressions. I mean, > > a = b + (c * d) I don't think that's really a best example. Functions and procedures are supposed to be fist-class in Python. We don't have to name lists, tuples, or dictionaries, so why should we have to name procedures and classes? Python is supposed to be regular. The inability to define procedures independently of their names is a terrible wart. It deceives people. The requirement to "def" a procedure to a name hides the fact that the procedure is truly a value, and no more limited to standing by a name than is an integer. Yes, it is often (usually) useful to assign that value to one or more names; the same may be said of lists and dictionaries. I remember the time when I thought of lambda as weird, or "arcane". I was learning Lisp, and I had already studied the fundamentals of Basic, Pascal, FORTRAN and C. Now I see that the reason I found the lambda difficult was because I was only familiar with languages in which procedures are not first-class. (Well, admittedly also because the traditional term "lambda" didn't ring like other reserved words). In those other language, the name bound to an address to which the compiler would put a jump. Anonymous function were important to my understanding of functions as values, and breaking of my FORTRAN-think. We certainly don't want to re-enforce the false notion that functions and procedures are special things with intrinsic names. They may be stored in a list as naturally as assigned to a name. And yet "def a[3](x): ..." doesn't parse. Expand lambda, maybe rename it. But do not eliminate it, because anonymous functions and functions-as-values go hand-in-hand. --Bryan From ark at research.att.com Tue Jul 9 14:37:13 2002 From: ark at research.att.com (Andrew Koenig) Date: Tue, 9 Jul 2002 18:37:13 GMT Subject: Why self? References: <090720020820257031%pecora@anvil.nrl.navy.mil> <090720021359063518%pecora@anvil.nrl.navy.mil> Message-ID: Louis> This one is lost on me. Sorry, I'm not operating at your Louis> level. What is the point? I advocated initializing object Louis> variables in a mandatory __init__ statment. So you should have Louis> added Louis> def __init__(self): Louis> name=None But that's extra code. I thought the whole point was to get rid of extra code, not move it around. >> 2) Methods are just functions that happen to be attributes. >> In other words, we could have written this: >> class Thing: >> def __init__(self): >> setname(self) >> def setname(x): >> x.name = "Thing" >> def printname(self): >> print self.name >> Thing.printname = printname >> t = Thing() >> t.printname() >> effectively transforming printname into a method, even though it >> does not have the form of a method when it is written. >> It seems to me that dropping the explicit "self" would make these >> two programs much messier. In what way then is it cleaner? Louis> Hmmm...a pretty bizzare example or else I just don't have Louis> enough programming experience. I've never done anything close Louis> to that. My experience is that ``bizarre'' is often just another way of saying ``unfamiliar.'' Louis> I will have to rely on others experience (including yours, Louis> which I know is substantial). Is this realistic or are you Louis> just pulling out a pathological example for argument? After Louis> all, I don't think it's the duty of a language design to Louis> completely protect the programmer from foolish code (for want Louis> of a better phrase). At some point the language has to just Louis> give up trying to interpret things and "raise and exception." What about someone who wants to write several classes with methods that behave exactly the same way? Doesn't it make sense to write that code once, and then install references to it in each of those classes? What about code that wants to build up objects with particular properties by installing methods dynamically in those objects according to the requested specifications? Louis> Tell you what. You're a smart guy (not sarcastic, I mean it). Louis> Why not apply your considerable knowledge to finding a solution Louis> to the issue of requiring "self." prefixes? It's apparent Louis> that lots of people would like to lose that requirement. I'm Louis> sure you can demolish my off-the-cuff suggestion at some point. Louis> I'm a bush-league amateur. But when you do that you will turn Louis> around to see that the issue itself is still there. What would Louis> you do? The point that I'm trying to make is that requiring "self" has some advantages, in that it makes certain kinds of programs easier to write than they would be otherwise. I've given two examples of such programs: those that add attributes dynamically to objects and those that define methods outside of the corresponding classes. Doubtless there are others. Because requiring "self" has some advantages, as well as the disadvantages that you and others have mentioned, it's a matter of opinion as to whether a solution to the problem would create other problems. For that reason, I'm not inclined to go looking for a detailed solution--especially as any solution would have to avoid breaking existing code. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From pecora at anvil.nrl.navy.mil Thu Jul 25 07:57:17 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Thu, 25 Jul 2002 07:57:17 -0400 Subject: Numeric Q: How to get DBL_MAX, etc. in Python? References: <240720021728273627%pecora@anvil.nrl.navy.mil> Message-ID: <250720020757175615%pecora@anvil.nrl.navy.mil> In article , Fernando Perez wrote: > In [4]: import kinds > > In [5]: kinds.default_float_kind. > kinds.default_float_kind.DIG > kinds.default_float_kind.EPSILON > kinds.default_float_kind.MAX > kinds.default_float_kind.MAX_10_EXP > kinds.default_float_kind.MAX_EXP > kinds.default_float_kind.MIN > kinds.default_float_kind.MIN_10_EXP > kinds.default_float_kind.MIN_EXP > kinds.default_float_kind.RADIX > kinds.default_float_kind.ROUNDS > kinds.default_float_kind._basic_del > kinds.default_float_kind._basic_get > kinds.default_float_kind._basic_set > kinds.default_float_kind._delete_disallowed > kinds.default_float_kind._properties_d > kinds.default_float_kind._properties_g > kinds.default_float_kind._properties_s > kinds.default_float_kind._write_disallowed > kinds.default_float_kind.get_property_d > kinds.default_float_kind.get_property_g > kinds.default_float_kind.get_property_s > kinds.default_float_kind.is_internal_attribute > kinds.default_float_kind.name > kinds.default_float_kind.set_property > kinds.default_float_kind.str > kinds.default_float_kind.typecode > > The kinds module is part of Numeric. > > cheers, > f Thanks, very much. I've used Numeric, but have completely missed this. I wonder if there are other modules I don't know about, but I'd like to in the standard distribution package. Bet my last dollar the answer is, yes. Thanks, again. -- Lou Pecora - My views are my own. From martin at v.loewis.de Thu Jul 25 04:09:02 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Jul 2002 10:09:02 +0200 Subject: UDP Multicast HELP! References: Message-ID: "Larry" writes: > I truly appreciate you taking time to respond, but I really don't understand > what you are trying to explain to me. Everything else in python seems so > easy, and creating a tcp socket and udp socket is so easy, just a few lines > of code. I am really surprised that there is no EASY way to join a group. But it is a fact. Python just exposes the socket API of the underlying operating system. Please take a moment to read the Linux setsockopt(2) man page. You notice that setsockopt takes a pointer and a length. Python currently does not "know" what all those socket options mean. It just exposes the bare setsockopt API to you. Now, IP_ADD_MEMBERSHIP requires a C structure, so you have to give it a C structure. For that, you need to understand what data to put into the C structure, *and* you have to understand how the C compiler lays out this structure in memory. Then you can construct a Python string that has the same layout. Sorry this is so complicated; if you feel it should be simplified in a future version, feel free to propose specific patches, or write a PEP. Regards, Martin From pecora at anvil.nrl.navy.mil Thu Jul 11 15:18:33 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Thu, 11 Jul 2002 15:18:33 -0400 Subject: A better self References: Message-ID: <110720021518334376%pecora@anvil.nrl.navy.mil> In article , Huaiyu Zhu wrote: > Using self is indeed the most readable most of the time. > > However, there are situations, mostly in numerical computations, where it is > necessary to have, say, a dozen variables in one expression, and a dozen > statements containing such expressions and some other statements in one > method. It is far more readable to have them all appear in one screen in a > form that resembles written equations on paper, than to dogmatically follow > a convention in a particular programming language. [cut - remainder] Huaiyu, Nicely said. -- Lou Pecora - My views are my own. From tim.one at comcast.net Wed Jul 3 00:07:01 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 03 Jul 2002 00:07:01 -0400 Subject: Comments in pickles? In-Reply-To: Message-ID: [Roy Smith] >>> Our usual practice is to imbed the CVS id string ($Id: ) in every >>> checked-in file as a comment. [Tim] >> I encourage you to question that practice. [Roy] > This is getting a little off-topic, but why do you say that? It's the > most convenient way I know of to identify a file when you're looking at > it. I would have thought the name of the file would be far more helpful . If it isn't, what does a number like 1.18.16.3 tell you that's of such compelling use you can't afford to do a "cvs stat" to get it? All it tells me is that I'm working on a branch, but if I'm working on a branch I already know that. I rarely care about who last checked the file in, or when, but those are easily obtainable too. BTW, bogus conflicts on embedded RCS Ids are going to drive you mad if you ever do significant work with branches -- they impose large artificial costs then. Before then, they're just geek fluff. Code that tries to be so clever as to *extract* pieces of embedded RCS ids for display, or to check its own version, is also notorious for breaking (producing gibberish in Python code, segfaults in C code). Indeed, Guido once cut a badly broken release of Python by "innovating" in how he checked out the source tree, breaking the few bits of clever code that try to parse embedded RCS ids in Python's source base. We purged almost all of that code then. Another problem, perhaps peculiar to open source projects, is that when a file from another code base gets checked in, the $Id expansions instantly differ radically, and people who have been lulled into trusting these expansions have been known to waste hours trying to find non-existent differences before the light dawns. In short, an embedded $Id never did me any good, but has wasted my time and tempted people to write code with severe bugs. If you just leave the $Id as a passive piece of a comment, I suppose the real damage is limited to making merges artificially painful. otoh-if-you-love-'em-go-for-it-ly y'rs - tim From gerhard.haering at gmx.de Thu Jul 18 16:15:06 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 22:15:06 +0200 Subject: safe_mode of modpython ? In-Reply-To: <20020718220026.53776b94.wilk-spamout@flibuste.net> References: <20020718220026.53776b94.wilk-spamout@flibuste.net> Message-ID: <20020718201505.GB2998@lilith.my-fqdn.de> * William Dode [2002-07-18 22:00 +0200]: > Is there an equivalent of the safe_mode and openbasedir of php in a > python module for apache ? Can you describe shortly what these do? I believe the answer will be "no" and "you'll have to fiddle with rexec/bastion", but I don't know about these PHP features, yet ;-) There might be non-Python solutions in the Apache configuration for the problem you're trying to solve (I'm thinking of mod_userdir, for example). Yet I have no idea yet what the problem to solve could be :-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From aleax at aleax.it Sun Jul 14 03:56:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 14 Jul 2002 07:56:01 GMT Subject: dictionary confusion... References: <9ef8bd6b.0207131555.73b82f57@posting.google.com> Message-ID: mirvine555 wrote: ... > statusTable[mc]=mc > statusTable[mc]={status:time} these lines are overwriting the previous entry for mc each and every pass -- change them into a single statement: statusTable.setdefault(mc,{})[status] = time The setdefault method of dictionaries is equivalent to the older idiom: d.setdefault(x, y) ... === if not d.has_key(x): d[x] = y d[x] ... except that setdefault marginally faster and more convenient. Alex From marklists at mceahern.com Fri Jul 12 17:55:56 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 16:55:56 -0500 Subject: Where can I find a good webhosting service ? In-Reply-To: <3D2F6B03.15519.1B4D696@localhost> Message-ID: http://www.python.org/hosting/ // m - From paul at boddie.net Thu Jul 11 07:26:46 2002 From: paul at boddie.net (Paul Boddie) Date: 11 Jul 2002 04:26:46 -0700 Subject: Python in the enterprise: Pros and cons References: <7xbs9fta42.fsf@ruckus.brouhaha.com> Message-ID: <23891c90.0207110326.7ac87088@posting.google.com> Paul Rubin wrote in message news:<7xbs9fta42.fsf at ruckus.brouhaha.com>... > > Regardless of that, lots of stuff has been written in Java that's > never been written in Python. Where's the Python TLS stack with > certificate management? Where are the Enterprise Python Beans? In the Python community, it's almost seen as a virtue that people don't write things that they don't need. Whilst some things held up in language comparisons aren't needed in Python because of the language's (and/or standard library's) inate capabilities, other things do apparently point to the fact that Python isn't being used in certain application areas. The subject of Enterprise Beans is a contentious hybrid of these two positions in the context of Python. Some might argue that EJB is a necessary and well-informed framework which can help significantly in the implementation of software for business; others might suggest that it's a bloated standard that few people bother to take full advantage of. Consequently, one might find Python in use either imitating EJB or instead competing with "sub-EJB" systems written in Java or other languages which don't support such frameworks. However, one thing which is, in my opinion, important about EJB and other Java technologies is the standardisation that comes with them. With Java, developers don't have to choose an application server and then use an API specific to that server; instead, they can choose an API and expect most servers to do a reasonable job of supporting it (even though the old "write once, test everywhere" curse still applies somewhat). Thankfully, Python has some standards in some technology areas, such as SQL and XML. Without even an elementary level of standardisation, Python would be as attractive as C++ for these technologies, and having done some work in C++ and XML recently, I can confirm that it isn't fun to use C++ in that area (whereas it is fun to use Python with XML) and it would be a nightmare to migrate to different libraries (whereas it would be much easier, if not completely trivial, in Python). > Java's online docs are far superior > to Python's. There are also a lot more books about Java, but I don't > care about those for the same reason I don't care about Python books. Some Java documents are very good, but other documents (in the maze of java.sun.com) are of fairly limited use. Moreover, the further one roams from Sun towards third parties, the worse the situation gets: lots of people with problems, no-one with solutions. > Python is ready for some applications and getting there for others. > It has a lot of virtues and to be clear about it, I like Python better > than Java for most purposes. However, Python's advocates often don't > acknowledge that there are still areas where Python genuinely does > fall behind. We need to stay aware of Python's shortcomings so we can > acknowledge them and/or fix them. Python is in the enterprise, even if its presence owes much to stealth, and I think many would be surprised how much usage Jython gets without much publicity in the usual Python community circles. Still, we need to be more self-critical and more committed to remove the tedious obstacles in the existing standards (portable database code is still a challenge), yet we should, in addition, continue to look for genuinely innovative solutions which don't necessarily owe a great deal to mainstream enterprise standards. Paul From b.maryniuk at forbis.lt Thu Jul 25 04:05:40 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 25 Jul 2002 10:05:40 +0200 Subject: how to count lines in a file ? In-Reply-To: <200207250936.56045.rjones@ekit-inc.com> References: <200207250936.56045.rjones@ekit-inc.com> Message-ID: <200207251005.40791.b.maryniuk@forbis.lt> On Thursday 25 July 2002 01:36, Richard Jones wrote: > What about it is broken? Why isn't it pointed out more often > that it _is_ broken? As I understood from Timothy msg, that this code does not requesting filehandler.close() or something. Dunno, Python's variables are bindings. So if no more pointers, no more variable. AFAIK... -- Sincerely yours, Bogdan M. Maryniuck "It's God. No, not Richard Stallman, or Linus Torvalds, but God." (By Matt Welsh) From mcherm at destiny.com Wed Jul 24 13:54:27 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 24 Jul 2002 13:54:27 -0400 Subject: A better self Message-ID: <3D3EE9D3.1090204@destiny.com> Michael Chermside wrote: ... > shouldn't be using Python. Yes, Python is a nice language, and yes, it > can be sped up by recoding key portions of an application in C/C++, but > it is never going to be as fast as an algorithm hand coded in assembly. Alex Martelli replies: > It may happen to be just as fast (that would be a rare coincidence) > and it may well be (more likely:-) *much faster*. > > That's because more often than not you won't be coding the SAME > algorithm in Python or assembly. ... Alex is (of course) completely correct. My true point was that Python and a mindset of "do whatever you can to save an extra CPU cycle" don't fit well together. But Python can be MUCH faster, in a lot of cases. I'll give an example. # # A program to sort lines. Takes, as command-line argument, a # filename (the file will contain one word or phrase per line), # and outputs the sorted file to stdout. # import sys filename = sys.argv[1] lines = file(filename).readlines() lines.sort() for line in lines: print line Except for some pretty strange circumstances (extremely large file, OS with really bad virtual memory), this is going to be faster than the equivalent C program. Unlike the C program, it has to set up the interpretor, do interpretation of the Python bytecodes, allocation and reference counting of Python objects, and use OS portable file reading. But all of these are dwarfed (for large file sizes... let's say 1 GB of text) by the fact that you are running a REALLY FAST sort algorithm. Of course, you could code the same sort algorithm in C yourself. Heck, for that matter, you could copy the sort algorithm (written in C) from the C source to Python (Python's liscense allows that!). But you wouldn't. Really... you wouldn't. But this is all beside the point. The **REAL** reason to use Python for a problem like this is that the Python script is only 6 lines long, and those lines are so elegant, so easy to understand, that a computer savy *middle school student* could understand them, maintain them, and perhaps even write them. The equivalent C progam would be much, much longer. Yes, there are times when Python is faster... and usually it's because a different (better!) algorithm is used (eg: use dicts instead of linear search through a list). But where it REALLY shines is in its clarity. And that clarity lets you think at a higher level (notice how I never had to stop to think about memory allocation or max line lengths?). And THAT lets you write better programs. -- Michael Chermside From oren-py-l at hishome.net Wed Jul 17 07:11:52 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 17 Jul 2002 07:11:52 -0400 Subject: simultaneous iteration of lists Message-ID: <20020717111152.GA82427@hishome.net> On Thu, Jul 18, 2002 at 02:24:46AM +1000, Dave Harrison wrote: > Evenin' all, > > Looking for advice on simultaneous iteration of two lists. > > I have two lists of equal length (guaranteed) , and I want to iterated over both at the same time without having to write myself a little counter thingo cause it seems slightly unpythonic. > Both lists are generated by seperate functions which get their input from seperate sources so using a dictionary isnt an option either. > > The syntax that is in the back of my brain looks something like > > for i,j in list1,list2: > print i > print j > > But this gives me the error : > > ValueError: unpack list of wrong size I see that a few people answered and told you to use zip. But in case you want to know what the code you wrote actually tries to do: (list1, list2) is a tuple with two lists as elements. The loop tries to iterate over this tuple and unpack each element into i and j. This will only work if the lists have exactly 2 items. >>> list1=[1,2] >>> list2=['a','b'] >>> for i,j in list1,list2: ... print i ... print j ... 1 2 'a' 'b' Using zip(list1, list2) will produce the result you were probably expecting: 1 'a' 2 'b' Oren From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 13:41:48 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 12:41:48 -0500 Subject: re/sre woes with Python 2.0 References: <2KhZ8.22$HD.214554@mencken.net.nih.gov> Message-ID: >>>>> "Jonathan" == Jonathan Epstein writes: Jonathan> Hi, Can someone please explain why the following line Jonathan> produces a regular-expression compilation error with Jonathan> Python 2.0, but not with Python 1.5? Is this fixed in Jonathan> any later versions, and/or can you describe how to Jonathan> adjust the RE to make Python 2.0 happy? Jonathan> regexp2 = re.compile Jonathan> (r"(?s)STATE\s*\"([^\"]*)\"\s*(\w*)\s*(\w*)?\s*{(.*?)\n[ Jonathan> \t]*}(?=\s*(?:$|STATE))") Your problem can be boiled down to regexp2 = re.compile(r"(\w*)?") (\w*) zero or more word chars ? optional Since zero or more is already optional in the sense of the '?', it makes no sense to add it regexp2 = re.compile(r"(\w*)") #equivalent I think what you want is regexp2 = re.compile(r"(?s)STATE\s*\"([^\"]*)\"\s*(\w*)\s*(\w*)\s*{(.*?)\n[\t]*}(?=\s*(?:$|STATE))") Take a look at http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&frame=right&th=a52889ac38a8a5be&seekm=87u2bsmhrp.fsf%40cartman.azz.net#link1 HTH, John Hunter From mgilfix at eecs.tufts.edu Sun Jul 28 11:24:50 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Sun, 28 Jul 2002 11:24:50 -0400 Subject: Which gui for slow (133 Mhz) pc In-Reply-To: <1027843391.20536.49.camel@vaio2>; from andreas@kostyrka.priv.at on Sun, Jul 28, 2002 at 04:44:58PM +0200 References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> <3d42f3dc.5866543@news.utanet.at> <3d42636b.4941993@news.utanet.at> <20020726105352.A2854@eecs.tufts.edu> <1027843391.20536.49.camel@vaio2> Message-ID: <20020728112450.A27111@eecs.tufts.edu> Heh. NM. Then realistically, you're choices are PyQT (the KDE look) and wxPython. One nice thing about wxPython though is that it looks like a native windows app since it basically wraps the native GUI libraries. Anyway, good luck :) I'm sure you can't really go wrong either way. -- Mike On Sun, Jul 28 @ 16:44, Andreas Kostyrka wrote: > Am Fre, 2002-07-26 um 16.53 schrieb Michael Gilfix: > > Agreed. PyQt is the base GUI toolkit that's used in KDE. If you've > > had some experience with different window managers, I suggest just > > deciding whether you like the look of KDE or GNOME better. If you > > like KDE, use PyQT, otherwise use GTK which is also a well > > developed toolkit. > Well, if you'd read the orginal email, you might discover that this is > about Windows developement ;) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From cliechti at gmx.net Sat Jul 27 18:10:10 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Jul 2002 00:10:10 +0200 Subject: wxPython TextCtrl overwriting References: Message-ID: Chris wrote in news:l156ku00l6tghtthgqe3a0tkvjbo0nping at 4ax.com: > BTW, any idea why python usually crashes so > horrendously while running my GUI in windows? It seems like if I > click on my python window or anything like that while the GUI is up, > everything crashes fierce; yet the GUI seems to be "bugfree" - if that > state even exists. Is there some exception handling I can insert that > will avoid this? It's a pain to have to restart IDLE and my program 9 > times out of the 10 I run it. Cuts my productivty in half. never, ever run a GUI program out of another. most GUIs only work when the main loop is stared in the main thread, but when you start it out of an other gui, you have two main loops. (ok sometimes it works, maybe tk in idle, but i don't use that) some IDEs have a way to run the application in a separate process, which solves that problem. (I have a patch for PythonWin to "run external" but it still has some small issues) chris -- Chris From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 15:43:03 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 14:43:03 -0500 Subject: expect and python References: Message-ID: >>>>> "Rajarshi" == Rajarshi Guha writes: Rajarshi> Hi, regarding my earlier post, it seems using Expect is Rajarshi> better than fiddling with pipes. Are there and Expect Rajarshi> like Python modules out there? http://expectpy.sourceforge.net From opengeometry at NOSPAM.yahoo.ca Sun Jul 7 19:14:30 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 7 Jul 2002 23:14:30 GMT Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> <3d28bdb0.71631360@news.dsl.pipex.com> <3d28c29a.72888518@news.dsl.pipex.com> Message-ID: Simon Foster wrote: > On 7 Jul 2002 22:30:55 GMT, William Park > wrote: > >>'1\n2\n3\n'.split() works as follows: >> 1\n2\n3\n -> 1\n2\n3 -> 1 \n 2 \n 3 -> 1 2 3 >> >>'1\n2\n3\n'.split('\n') works as follows: >> 1\n2\n3\n -> 1 \n 2 \n 3 \n -> 1 2 3 '' >>where the last '\n' separates '3' and '' (null). > > Still seems odd! Not if you try to go backwards: 1 2 3 -> 1 \n 2 \n 3 -> 1\n2\n3 1 2 3 '' -> 1 \n 2 \n 3 \n '' -> 1\n2\n3\n -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From fredrik at pythonware.com Wed Jul 3 12:59:18 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jul 2002 16:59:18 GMT Subject: Splitting Text files References: Message-ID: Jonathan Hogg wrote: > Given that the header was given in the body of the message, I hardly > see that it will make any difference - it won't get honoured. http://www.google.com/googlegroups/help.html#prevent "Google supports the 'X-No-archive: yes' header, and we will not archive any articles that contain this text either in the header or in the first line of the message body." From cliechti at gmx.net Thu Jul 4 14:49:06 2002 From: cliechti at gmx.net (Chris Liechti) Date: 4 Jul 2002 20:49:06 +0200 Subject: Quaternion Arithmetic Module References: Message-ID: "Dave Feustel" wrote in news:ag1iqj$oi5$1 at slb3.atl.mindspring.net: > Is there a python module for doing quaternion arithmetic? i think scientific pythonhas support for it: http://dirac.cnrs-orleans.fr/ScientificPython/ chris -- Chris From joconnor at cybermesa.com Mon Jul 29 12:51:28 2002 From: joconnor at cybermesa.com (Fearless Freep) Date: 29 Jul 2002 09:51:28 -0700 Subject: Guide to the python interp. source? References: Message-ID: <7d3dc526.0207290851.60579a87@posting.google.com> Michael Hudson wrote in message news:... > > > > Things I want to change is for example, everything should be "call by > > > > refferense", > > > That may be very hard. If you want things like this: > > > > > > def f(x): > > > x += 1 > > > > > > i = 2 > > > f(i) > > > i --> 3 > > > > > > then you have problems. > > > > That is exactly what I want to have, that is more intuitive I think and I > > don't think it must be that hard either. > > I don't want to get into an argument with you -- but you're wrong ;-) > > Have a look at this page I wrote a while's back: > > http://starship.python.net/crew/mwh/hacks/objectthink.html > > which explains how Python's object work -- I don't think you can make > call by reference work without changing this model, and then you don't > have Python any more. > > FWIW, the way Python objects work is very similar to Lisp and Scheme > (and just similar to Java). I was making the argument a few days ago that the inability to do just that was why Python was more scalable than TCL. The problem when you have something like foo (x) where x can be reassigned as above, is that you can have unintended consquences. if you have code like foo(x) print x and x does not come out with the value you expect, you know that it was not changed in foo(), so you don't have to investigate the implementation of foo() to determine if it changed x x = foo(x) It's obvious you are changing x y = foo(x) It's obvious you are not changing x if you allow def foo(i) i = i + 1 then you lose the ability to look at the clients of foo() and know what potential consequences there are. I think Ada got it right with the "in", "out" and "in out" parameter declarations; short of that, I don't think you should be able to re-assign parameters to functions, it add complexity to reading and deciphering code Take care, Jay O'Connor http://www.r4h.org/r4hsoftware From BPettersen at NAREX.com Fri Jul 26 23:04:45 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 26 Jul 2002 21:04:45 -0600 Subject: performance problem in python 2.2 Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201920125290A@admin56.narex.com> > From: Gerhard H?ring [mailto:gerhard.haering at gmx.de] > > * Paul Rubin [2002-07-26 > 18:13 -0700]: > > Jeff Davis writes: > > > > > If you read my C code, you'll see that I used the 'unsigned long > > > long type' > > > which is a 64-bit int. And I only stored 2^32 in it. When > I needed to > > > crunch the numbers, I treated 2^64 as p*p (because 2^64 == > > > sqrt(2^64)*sqrt(2^64) == 2^32*2^32), and then I commuted the > > > multiplication so it would happen in a way that wouldn't > overflow. > > > > Oh whoops, yes, I missed that. "Long long" is not part of > standard C, > > It is. C99. Moreover, it's supported by virtually every compiler except msvc (not even msvc on Win64...) -- bjorn From mwh at python.net Fri Jul 26 06:06:38 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 10:06:38 GMT Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: "David LeBlanc" writes: > I may be wrong about this, but I don't think regular expressions > qualify as turing complete. No branching for one thing... Somewhere you can find a (perl) regexp that matches prime but not composite numbers, which suggests Turing completeness -- and rather takes the mickey out of the word "regular". > Personally, I think RE's are great and ought to be fully integrated > into Python, along with a few improvements. I don't. Cheers, M. -- ARTHUR: Yes. It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard". -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From jdhunter at nitace.bsd.uchicago.edu Mon Jul 15 18:17:45 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Jul 2002 17:17:45 -0500 Subject: Python and HDF References: Message-ID: >>>>> "J" == J Li writes: J> Hi, I am looking for a way to read HDF files directly from J> Python. Could someone show me the way? http://www.met.wau.nl/index.html?http://www.met.wau.nl/medewerkers/moenea/pyhdf.html http://groups.google.com is your friend Cheers, John Hunter From aleax at aleax.it Wed Jul 24 04:51:49 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:51:49 GMT Subject: threads and Tkinter References: Message-ID: Petr Klyushkin wrote: > Hello again! > > I have one more question about Tkinter. This time it is related with > threads. I have a program which uses Tkinter as its GUI toolkit. It > runs a separate "worker" thread for doing some time-consuming > operation. Sometimes worker thread has to update GUI. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 It's also in the printed Cookbook, with some minor enhancements, but you can get the gist from the online-posted version at this URL. Alex From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 11:03:53 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 10:03:53 -0500 Subject: Searching for email address In-Reply-To: <3D46A872.55D6C3F@ilangua.com> (Graeme Longman's message of "Tue, 30 Jul 2002 15:53:38 +0100") References: <3D46A4BD.A894DC59@ilangua.com> <3D46A872.55D6C3F@ilangua.com> Message-ID: >>>>> "Graeme" == Graeme Longman writes: Graeme> Source code for the book ? What do you mean ? Some publishers make the code that appears in the book available for download, so you don't have to type in the examples from the book. I recently downloaded the code from 'Python Web Programming' (and bought the book). It's often organized by chapter. Here is O'Reilly's web site for the book http://www.oreilly.com/catalog/regex2 I don't see any links for source code, but if you go to the author's web site, you can download code from the book if you know the page number http://regex.info There is also a link on that page to a full index. John Hunter From johnroth at ameritech.net Sun Jul 7 19:05:55 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 7 Jul 2002 19:05:55 -0400 Subject: How to organize test cases with PyUnit References: Message-ID: "Roy Smith" wrote in message news:roy-F91625.14520007072002 at reader2.panix.com... > I'm looking at using unittest for a new project. This would be my first > use of unittest, although I've rolled my own test suites a few times. > How do people usually organize the test cases for a module? Offhand, I > can think of a few ways to do it. > > I could put all the test-case code in the same .py file as the module. > This seems the least complicated, but perhaps also the least efficient > since it's a lot more code to parse when the module is imported. > Possibly isolate the test cases with a __name__ == "__main__" > conditional? > > I could put the test cases for a module in another file in the same > directory, or possibly put all the test cases for all my modules in a > "test" subdirectory. This answers the efficiency question above, but > seems like it's begging to have the two files get out of sync. Also, > does the test case file import the module being tested? Is there a > common higher-level file that imports both? I usually have a test module for each production module. It has the same name as the production module, suffixed with _test. There's also a high level test module that imports all of the test modules and runs them; I call it "System_test". The skeleton for the test module is pretty standard: it imports unittest, the module under test, a package of testing subroutines I've written, and then anything else I need. It ends with the standard idiom to execute itself when invoked. The rest of the module is the invocation procedure, and then a class to test each class in the production module. You will probably want to do this differently; I don't make very much use of the set_up and tear_down methods. > > I realize none of these are absolutely critical issues, but I'd be > interested to hear how othe people have done it. > > BTW, I started out with the test cases in a "test" subdirectory, and ran > into a slight uglyness. My initial idea was to just have module-test.py > do an "import ../module", until I discovered that gives you a syntax > error. I can get around it with: > > import sys > sys.path.insert (1, '..') > import module > > but that seems clumsy. Is there a cleaner way to do that? From usenet at REMOVETHISPHRASEblacklettersoftware.com Wed Jul 3 11:00:02 2002 From: usenet at REMOVETHISPHRASEblacklettersoftware.com (Richard Biffl) Date: Wed, 3 Jul 2002 11:00:02 -0400 Subject: what's up with 'patterns'? References: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> Message-ID: Bruce Eckel is rewriting his "Thinking in Patterns" book using Python, as "Thinking in Python." A draft is available online at http://www.mindview.net/Books/TIPython. Richard From aleax at aleax.it Sun Jul 7 11:49:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 15:49:16 GMT Subject: a nice metaclass example (was Re: structs in python) References: Message-ID: <0qZV8.51942$vm5.1927874@news2.tin.it> Alex Martelli wrote: ... > amount of memory consumed don't interfere. __slots__ is OK, to save > memory, when you have many instances with just a few data fields each > (and the same field names in each instance), but it does admittedly > demand more sophisticated implementation than Bunch, presumably via a > metaclass. Ah, forget the "presumably", here's a simple example. I've been looking for good and simple custom metaclass examples for quite a while, after all, so it would be silly to miss this occasion just because I SHOULD be finishing the draft of Python in a Nutshell...!-). import warnings class metaMetaBunch(type): """ metaclass for new and improved "Bunch": implicitly defines __slots__, __init__ and __repr__ from variables bound in class scope. An instance of metaMetaBunch (a class whose metaclass is metaMetaBunch) defines only class-scope variables (and possibly special methods, but NOT __init__ and __repr__!). metaMetaBunch removes those variables from class scope, snuggles them instead as items in a class-scope dict named __dflts__, and puts in the class a __slots__ listing those variables' names, an __init__ that takes as optional keyword arguments each of them (using the values in __dflts__ as defaults for missing ones), and a __repr__ that shows the repr of each attribute that differs from its default value (the output of __repr__ can be passed to __eval__ to make an equal instance, as per the usual convention in the matter). """ def __new__(cls, classname, bases, classdict): """ Everything needs to be done in __new__, since type.__new__ is where __slots__ are taken into account. """ # define as local functions the __init__ and __repr__ that we'll # use in the new class def __init__(self, **kw): """ Simplistic __init__: first set all attributes to default values, then override those explicitly passed in kw. """ for k in self.__dflts__: setattr(self, k, self.__dflts__[k]) for k in kw: setattr(self, k, kw[k]) def __repr__(self): """ Clever __repr__: show only attributes that differ from the respective default values, for compactness. """ rep = [ '%s=%r' % (k, getattr(self, k)) for k in self.__dflts__ if getattr(self, k) != self.__dflts__[k] ] return '%s(%s)' % (classname, ', '.join(rep)) # build the newdict that we'll use as class-dict for the new class newdict = { '__slots__':[], '__dflts__':{}, '__init__':__init__, '__repr__':__repr__, } for k in classdict: if k.startswith('__'): # special methods &c: copy to newdict, warn about conflicts if k in newdict: warnings.warn("Can't set attr %r in bunch-class %r" % ( k, classname)) else: newdict[k] = classdict[k] else: # class variables, store name in __slots__ and name and # value as an item in __dflts__ newdict['__slots__'].append(k) newdict['__dflts__'][k] = classdict[k] # finally delegate the rest of the work to type.__new__ return type.__new__(cls, classname, bases, newdict) class MetaBunch(object): """ For convenience: inheriting from MetaBunch can be used to get the new metaclass (same as defining __metaclass__ yourself). """ __metaclass__ = metaMetaBunch # Example use: a meta-bunch class class Point(MetaBunch): """ A point has x and y coordinates, defaulting to 0.0, and a color, defaulting to 'gray' -- and nothing more, except what Python and the metaclass conspire to add, such as __init__ and __repr__ """ x = 0.0 y = 0.0 color = 'gray' # example uses of class Point q = Point() print q p = Point(x=1.2, y=3.4) print p Apart from arbitrary ordering of the arguments, and representation of floating point numbers being not all that nice, you'll see the "print" statements emit basically the same constructors we just used. The point is: if you use a lot of "struct-like" classes, metaMetaBunch offers you a nice and convenient way to define them, with clean syntax and reasonable default semantics (__init__ and __repr__). If your application needs are slightly different, you can of course tweak this pretty easily -- it IS, after all, a modest amount of pretty simple lines of code. An instance of a metabunch class is quite memory-lean, and using it should be just about as fast as using an instance of the original Bunch class. I hope this provides a reasonable starting point in the study of "what are Python 2.2 metaclasses good for"! BTW, note that this example doesn't care about the bugfix in the current CVS 2.3 wrt 2.2 regarding the mangling of slotnames that start with '__' -- the metabunch class we build doesn't end up with any slotname with two leading underscores, anyway, and if we have something like: class thing(MetaBunch): __var = 23 the class-scope variable name is already mangled to _thing__var by the time our metaMetaBunch class gets to deal with it. Of course, this doesn't necessarily make much sense for a class meant to have no methods (!), but, hey, whatever floats your boat... Alex From hamish_lawson at yahoo.co.uk Mon Jul 22 13:33:09 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 22 Jul 2002 10:33:09 -0700 Subject: Python UDDI implementation References: <3D3C104D.1EDB2D48@xrce.xerox.com> Message-ID: <915a998f.0207220933.44a332ef@posting.google.com> David Levy wrote: > I am looking for a Python UDDI implementation. IBM alphaWorks recently released UDDI4Py: http://xml.coverpages.org/ni2002-07-17-a.html Hamish Lawson From musicmaker1118 at aol.com Sun Jul 14 11:30:45 2002 From: musicmaker1118 at aol.com (Musicmaker1118) Date: 14 Jul 2002 15:30:45 GMT Subject: Running multiple functions with Python 1.5 Message-ID: <20020714113045.08255.00000535@mb-fj.aol.com> I am trying to make a simple windowing system in python 1.5 that can run using minimal memory. I would like for it to be able to display icons, and to be able to run programs assosciated with them when you click on them. I would also like it to be able to run simple programs inside of a window. To do this this, I need to be able to run programs and monitor the movements of the mouse to display the cursor. I plan on using a C extension for the graphics and monitoring the mouse. The functions it defines will be run by the python code. But I am not sure if Python 1.5 can be running different functions at the same time, and if it is possible, how to do it. Does anyone know how this could be done? If so, I would like to know. From cliechti at gmx.net Wed Jul 31 15:04:15 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 21:04:15 +0200 Subject: a soft real-time system using python References: <20020731145848.GC1800@unpythonic.net> Message-ID: anton wilson wrote in news:mailman.1028134302.18143.python-list at python.org: > On Wednesday 31 July 2002 12:33 pm, anton wilson wrote: >> If the soft-real-time system we use makes simple function calls and >> only uses simple datatypes and possibly tuples, what are some of the >> potential pitfalls we could run into? I understand the deallocation >> issue and the garbage collection issue. (Does garbage collection have >> to be enabled?) Can we somehow get an idea on the worse case time >> delays in python using only simple function calls and assignments >> with small tuples and simple datatypes? > > > For further information, we're already having a certain problem where > python threads seem to drastically decrease performance in the middle > of the program for around a second. Garbage collection has been > disabled, but it's possible that there is some other behind-the-scenes > work that Python is doing. What other things should we be worrying > about? I need a more complete understanding of what can happen or is > happening that would affect consistent running of a python program. i've never experienced such an effect. delays of a second seem a bit high... are you doing IO? are other processes running (that possibly do lots of IO, runing a JAVA with GC or so)? then look also in the syslog if you see some activity of daemons during the time you experience the effect. from what machine are we speaking anyway? can you tell some RAM, MHz figures, OS (linux, but which)? have you tried to construct a program to show that effect? a programm that does the least possible but still having that effect, that should help to identify the problem. chris -- Chris From aleax at aleax.it Sat Jul 6 17:30:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Jul 2002 21:30:18 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> Message-ID: Thomas Jensen wrote: ... > I've heard that Python threads don't scale (well?) to multiple CPUs ? > Maybe that's only on Windows? No, it's true on all platforms: Python threads only use one CPU. There is a global interpreter lock (GIL) to ensure only one Python bytecode is being executed at any given time, except for those which call out to C-coded parts (e.g. for blocking I/O) which explicitly release the GIL. With Python, you can exploit multiple CPUs only by multi-*processing* -- and here, it's possible that Windows' multi-processing inefficiencies may byte you (with Unix-like systems, often multiple processes or multiple threads in one process have quite comparable performance). Alex From aldo at nullcube.com Tue Jul 30 18:44:27 2002 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 31 Jul 2002 08:44:27 +1000 Subject: Python Cookbook dict problem In-Reply-To: <200207302001.g6UK1Rc07994@localhost.localdomain> References: <200207302001.g6UK1Rc07994@localhost.localdomain> Message-ID: <20020730224427.GA14027@nullcube.com> Thus spake Dave Reed (dreed at capital.edu): > > I'm trying the following Python Cookbook recipe with python2.2 > > > def makedict(**kwargs): > return kwargs > data = makedict(red=1, green=2, blue=3) > def dodict(*args, **kwds): > d = {} > for k, v in args: d[k] = v > d.update(kwds) > return d > tada = dodict(*data.items(), yellow=2, green=4) > > > but I get an error with the last line: > >>> tada = dodict(*data.items(), yellow=2, green=4) > File "", line 1 > tada = dodict(*data.items(), yellow=2, green=4) > ^ > SyntaxError: invalid syntax > > What's wrong? Dave, Python expects you to do positional and keyword argument unrolling at the end of the function argument list (i.e. after all "normal" arguments). Change the last line to: tada = dodict(yellow=2, green=4, *data.items()) and Bob should be your metaphorical uncle. Aldo -- Aldo Cortesi aldo at nullcube.com From shagshag13 at yahoo.fr Tue Jul 9 11:24:53 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 17:24:53 +0200 Subject: sorting many arrays from one... References: Message-ID: "Alex Martelli" it's ok for everything. but i should have writed DISK storage :o) that's why i use the int id - string mapping... s13. From juanm.casillas at eresmas.com Tue Jul 16 06:55:36 2002 From: juanm.casillas at eresmas.com (Juan M. Casillas) Date: Tue, 16 Jul 2002 12:55:36 +0200 Subject: Different execution Message-ID: <15667.64424.713766.486453@eresmas.com> Hello Folks ! I have big problems :) I use an ebbeded python interpreter, and when I try to do things like: string.split("x|x|x","|") (obviously, I import string before) or call some functions with defaults arguments foo(arg1='this',arg2='more') It fails (If I exec this code from the command line interpreter, it works fine!). The error code is some "generic" one: AttributeError: 'int' object has no attribute 'data' but, if I sighly rewrite the things, they works: x = "x|x|x" x.split("|") # works foo('this','more') # works Also I have some type errors .... f type(x) == type(''): s = x Anybody has any ideas ? Thanks In advance Juan M. Casillas From aahz at pythoncraft.com Wed Jul 31 13:19:04 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Jul 2002 13:19:04 -0400 Subject: Understanding properties References: Message-ID: In article , merman wrote: >> >> class MyObject(object): > >Why it needs the inheritance from object - I don't understand. >Can you enlighten me please? This is almost a month late, but in case anyone hasn't seen it, new-style classes are documented in http://www.python.org/2.2.1/descrintro.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From nickone at 263.net Wed Jul 3 08:42:54 2002 From: nickone at 263.net (nicholas wang) Date: Wed, 3 Jul 2002 20:42:54 +0800 Subject: How to triger a timer/signal to a running program References: Message-ID: Thanks, Lee. I missed the Signal Module. I find the "alarm" function. Another problem, does somebody know how to get the PID while keep waiting for the program finish. I used spawn* , but when I get PID, I'll get returned right now. When I get Wait, I can't get PID. Any method to get PID and Wait both? Thanks. "Lee Harr" wrote in message news:ui1qkshndg995b at corp.supernews.com... > In article , nicholas wang wrote: > > Hi,all > > My task is to kill a program when it runs more than a limited time. > > My plat is Linux7.1; I've tried Csh to make it using ps ... ; then kill > > this program. But it will get extra messages to stdout. Of course, use > > "limit" command also works. But both are not perfect. > > I know Perl get a command "alarm" will do such a job > > I'm searching a Python counterpart. Does anyone know what it is? > > My idea about this job is: ( in a python shell ) > > 1. mark a signal to a specific program. > > 2. run this program > > 3. if time exceeds limit(set before run), the shell will kill it. > > 2. continue to run the remained commands. > > > > Maybe something in the signal library can help. > signal is a module in the standard library. > From sarmstrong13 at mac.com Tue Jul 9 15:08:46 2002 From: sarmstrong13 at mac.com (SA) Date: Tue, 09 Jul 2002 14:08:46 -0500 Subject: CGI Help Please. References: Message-ID: Ok. I 'hacked' at the code for awhile and have finally figured it out. For anyone that wants to see the results, check my test program below: On 7/9/02 11:51 AM, "SA" wrote: #!/sw/bin/python import cgi import cgitb cgitb.enable(display=0, logdir="/Users/montana/Temp") QueryString = cgi.FieldStorage() for pageID in QueryString.keys(): QValue = QueryString['pageID'].value body = open(QValue, "r") for line in body.readlines(): print "Content-Type: text/plain\n\n" print line body.close() print "Finished!" The line in the testtext file is of course "Hello World!" So clicking the Test link on the first webpage sends the querystring (filename of the text file) to the python cgi script, and the script translates the data and displays the following on a new web page: Hello World! Finished! So everything is groovy now and I can start developing my own website. Thank You all for your help. Thanks. SA -- "I can do everything on my Mac I used to on my PC. Plus a lot more ..." -Me On 7/9/02 11:21 AM, in article B95077C0.924E%sarmstrong13 at mac.com, "SA" wrote: > I've been working on a little test script so I can understand the > functionality of the cgi module when writing a python cgi script. The goal > is to redirect a page from a link o the stored value in a query string. > (ex. title="TestFile">TestFile). > > I've now managed to get my script to work part way. I got rid of the server > error I was getting by changing: > #!/usr/bin/env python > > To > > #!/sw/bin/python > > sw/bin is the directory where my default python is located. For some reason > my Apache setup chokes on the /usr/bin/env executable. > > So this fixes the server error. I then set the program to display the value > for the key "pageID", but what I get is: > > The test file is: > > ['testtxt'] > Finished! > > > What I would like to do now is take that dictionary value(testtxt), which is > the name of the text file I would like to use, read the text in the text > file and re-display this in a new web page. Basically what I have is a html > template file and a lot of text files. My final script will take the query > string from the href as a text file name and send that to the python cgi > script. That value will then be used to look up the textfile, read it's > data, and print the file in the body section between
 tags on a
> new web page. With this script, I will have only a template file that needs
> it's links updated when I add new textfiles instead off 100+ html files
> needing to be constantly maintained.
> 
> So since I'm new to python and CGI, I've been 'hacking' around on my machine
> with different codes trying to understand how the script would function. Can
> anyone help me please?
> 
> Below is the test script I wrote:
> #!/sw/bin/python
> 
> import cgi
> import re
> 
> QueryString = cgi.parse_qs('pageID=testtxt')
> 
> for pageID in QueryString.keys():
>   QValue = QueryString[ pageID]
> #    passvalue = [Qvalue]
> #    body = open("QValue", "r")
> #    for line in body.readlines():
>   print "Content-Type: text/plain\n\n"
> #        print line
>   
>   print "The test file is:\n"
>   print QValue
> #    body.close()
>   
> print "Finished!"
> 
> Any ideas on what I'm doing wrong?
> 
> Thanks.
> SA
> 



From martin at v.loewis.de  Sun Jul  7 04:01:05 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 07 Jul 2002 10:01:05 +0200
Subject: Chinese language support of Python?
References:  <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl>  
Message-ID: 

guidance_shanghai at yahoo.com.cn (Leon Wang) writes:

> But still can not put Chinese directly as string in source, I can not
> live with so much \u... for a whole Chinese sensence/paragraph, it's
> impossible to read and edit them :(

This is a known problem, and it will be addressed with PEP 263
(http://www.python.org/peps/pep-0263.html).

Meanwhile, you have the following options:

- Don't use IDLE to edit Python source code (but, say, notepad), and
  only put Chinese text into string literals.
- Set the default encoding in site.py to the encoding you want to use.
- Apply patch 
  http://sourceforge.net/tracker/index.php?func=detail&aid=508973&group_id=9579&atid=309579

  which allows you to declare the source encoding for IDLE.

In either case, you cannot use Chinese in Unicode literals. Instead,
you should always use 

   unicode("chinese string", "chinese encoding")

For portability, and if your editors support it, I recommend to use
UTF-8 as the "chinese encoding".

Regards,
Martin


From shalehperry at attbi.com  Fri Jul 12 21:26:44 2002
From: shalehperry at attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Jul 2002 18:26:44 -0700 (PDT)
Subject: Bitshifted exit status from Popen3
In-Reply-To: <200207130046.UAA10442@arkroyal.cnchost.com>
Message-ID: 

On 13-Jul-2002 Mike Wakerly wrote:
> Greetings all,
> 
> I am encountering a peculiarity when trying to
> retreive the exit status of a command executed with
> popen2.Popen3.
> 
> The effect is that the returned object in res =
> popen2.Popen3(...) has a res.status value 256x greater
> than it should (eg, bitshited to the left eight places?!)
> 

according to the popen() man page it returns the same value as wait4.  From
that man page:

WEXITSTATUS(status)
              evaluates to the least significant  eight  bits  of
              the  return  code  of  the  child which terminated,
              which may have been set as the argument to  a  call
              to exit() or as the argument for a return statement
              in the main program.  This macro can only be evalu?
              ated if WIFEXITED returned non-zero.

in other words, this is expected behavior.  The shell knows how to interpret it
for you which is why you have never seen it before.




From donn at drizzle.com  Wed Jul 24 01:40:30 2002
From: donn at drizzle.com (Donn Cave)
Date: Wed, 24 Jul 2002 05:40:30 -0000
Subject: os.getlogin()  raises OSError (errno 25)
References: None <12257ec4.0207231946.583a2e93@posting.google.com>
Message-ID: <1027489223.157336@yasure>

Quoth davidccarson at hotmail.com (David Carson):
| Could someone please explain why the following runs fine if I type the
| input and end stdin with ctrl-D, but bombs when I pipe stdin to it.
...
|     loginName = os.getlogin()
| OSError: [Errno 25] Inappropriate ioctl for device
...
| mandrake Linux 8.2

On NetBSD, it doesn't fail on a pipe, but man 2 getlogin mentions
that it used to, in some earlier version of NetBSD, specifically if
the process was not associated with a "login terminal."  Details
vary from one platform to another (you don't want to know about the
setpenv business on AIX), but characteristically it's a function of
the terminal login session.  In theory, you'd get at the controlling
terminal (if that's the same thing) by opening /dev/tty, and if you're
really desperate you could try that out to see if you can work around
some Linux brain damage:  open /dev/tty read/write, dup unit 0/1/2 to
keep them around, dup2 the tty unit to 0/1/2, call getlogin, dup2 the
saved units back and close the dups.  Of course it will be for naught
if /dev/tty isn't a terminal - I'm just speculating that the brain
damage is that GNU getlogin assumes /dev/tty is on 0 (or 1 or 2.)

Incidentally, on NetBSD I get "root" although I am not root.  That's
probably because my sshd failed to call setlogin() - I don't know, but
I've seen the same thing on other platforms for similar reasons.  One
would not want to rely on this function for sensitive matters.  It's
only good for a hint - if getuid() returns 0, you can try getlogin.

	Donn Cave, donn at drizzle.com


From K.Rdt at TU-Berlin.DE  Wed Jul  3 12:34:23 2002
From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt)
Date: Wed, 03 Jul 2002 18:34:23 +0200
Subject: HT clear some wxPython fram?
In-Reply-To: 
Message-ID: <9753B78WQ40XV4Y1TA8IGW03Y82.3d23278f@FRITZweb>

Am 03.07.02 17:52:47, schrieb "Jon Bills" :

>"Klaus Reinhardt"  wrote in message
>> HOW I CAN CLEAR SOME FRAME?
>
>Have you tried frame.Clear()? It's a member of wxWindow, which all frames
>derive from.
---------------------------------------------------------------------
Hi

It's giving me a name error.

BTW: 
I'm a little too impatient; I've only read 2 books
(for 100 EUR), havn't yet got the OOP-FEELING,
cause my languages were for years Pascal, Assembler, C ..

Thanks anyway
		K at Rdt
---------------------------------------------------------------------







From aoeu at go.com  Sun Jul  7 13:06:23 2002
From: aoeu at go.com (Thinkit)
Date: 7 Jul 2002 10:06:23 -0700
Subject: openprojects python room is ruled by dangerous people
Message-ID: <3eeda89d.0207070906.1fa45916@posting.google.com>

These people are dangerous, and will boot you if you do not agree to
their narrow worldview.  They are an affront to the python
language--especially "dash".


From robin at jessikat.fsnet.co.uk  Thu Jul  4 16:19:38 2002
From: robin at jessikat.fsnet.co.uk (Robin Becker)
Date: Thu, 4 Jul 2002 21:19:38 +0100
Subject: replacing instance __setattr__
References: 
 
Message-ID: 

In article , Tim Peters
 writes
>[Robin Becker]
>> special methods aside I find in 'Unifying types and classes in Python
>> 2.2' http://www.python.org/2.2/descrintro.html#mro
>> that the object is always searched last for methods which seems a bit
>> daft and obviously different for non-method attributes.
>
>The builtin class named "object" is searched last for methods.  When you say
>"the object", I expect you're thinking of the x in
>
>    x.somemethod()
>
.....
that's my confusion. Also as you point out I seem to think that methods
are data attributes which are callable, obviously my failure again. I
obviously come from a more dynamic direction all these distinctions seem
pretty arcane and silly to tcler's, lispers, gpmers etc.
-- 
Robin Becker


From jb at cascade-sys.com  Thu Jul 25 15:13:57 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Thu, 25 Jul 2002 12:13:57 -0700
Subject: Numeric data question
References:  <3D3EF9AD.A0F661BC@noaa.gov> <3D3F1160.EE1C1C19@cascade-sys.com> 
Message-ID: <3D404DF5.9D45265@cascade-sys.com>

terry wrote:

> Do you know if the database internal representations of currency
> are consistent across many/most databases?

I dunno but I expect they are different.  Common encodings are as
strings, as "BCD" (2 decimal digits per byte) and "fixed point"
(integer with implied decimal point).

> It would seem like
> that would have to be true for a Python to have a chance for an
> intrinsic implementation that would be relatively universally
> useful by ODBC connections, wouldn't it?

Not really.  Each different Python <--> database interfaces would
handle conversion.

> However, interface
> packages like Pypgsql could translate from Postgres internal to
> Python internal representations without a problem - if it existed
> that is :).

I'm not sure there IS a 'Python internal representation'.  The
different interfaces handle conversions between database native
format and Python base types, such as integers, reals and strings.


--
James J. Besemer  503-280-0838 voice
http://cascade-sys.com  503-280-0375 fax
mailto:jb at cascade-sys.com





From raims at dot.com  Sat Jul 20 10:25:01 2002
From: raims at dot.com (Rhymes)
Date: Sat, 20 Jul 2002 16:25:01 +0200
Subject: Python 2.3
References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> 
Message-ID: 

On Fri, 19 Jul 2002 15:44:42 -0700, "David LeBlanc" 
wrote:

>True Division? Darn it, i'm used to false division! Where is "to __past__
>deport ..."? ;-)

LOL

--
Rhymes
rhymes at myself.com
" ride or die "


From cce at clarkevans.com  Tue Jul 30 19:04:46 2002
From: cce at clarkevans.com (Clark C . Evans)
Date: Tue, 30 Jul 2002 19:04:46 -0400
Subject: mozilla wrapper for python ?
Message-ID: <20020730190446.A83046@doublegemini.com>

Hello.  I was wondering if anyone is actively working or has
developed a python wrapper for mozilla, preferably with wxpython?
I see a few "related" projects that appear to be abandoned:

  - http://sourceforge.net/projects/pygecko/
  - http://sourceforge.net/projects/wxmozilla/
  - http://sourceforge.net/projects/pyleon/
  - http://sourceforge.net/projects/kmeleon/

To related projects which appear to be active:

  - http://aspn.activestate.com/ASPN/Downloads/Komodo/PyXPCOM/
  - http://www.iol.ie/~locka/mozilla/mozilla.htm

Thanks,

Clark




From sholden at holdenweb.com  Sat Jul 27 00:43:28 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Sat, 27 Jul 2002 00:43:28 -0400
Subject: turtle module information
References: <13285ea2.0207261327.2827b3a6@posting.google.com>
Message-ID: 

"J.Jacob"  wrote in message
news:13285ea2.0207261327.2827b3a6 at posting.google.com...
> The turtle module is very nice.  I would like to know if there is any
> more information about the turtle module available?  Of course there
> is the turtle.py file in C:\Python*\Lib\tk* but I am also interested
> in things like who wrote it and design decisions.
>
It's a long time since I wrote turtle graphics. The idea was originally
dreamed up, IIRC, by Seymour Papert for his LOGO programming language,
primarily used to investigate how easy it might be for children to absorb
programmin concepts. The idea was to give them something programmable that
provided immediate visual feedback.

A search on Google for "logo turtle graphics" will probably give you plenty
of useful data, much of it historical by now.

> Is it possible to change the font used by turtle.(Raw_Pen).write() ?

Dunno. Use the source, Luke!

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------







From francois.lepoutre at seriatim.com  Fri Jul 19 06:01:01 2002
From: francois.lepoutre at seriatim.com (François Lepoutrre)
Date: Fri, 19 Jul 2002 11:01:01 +0100
Subject: Do GUIs for DBs exist?
References:  
Message-ID: 

> the other day, and I was thinking: hey, wouldn't it be
> great if it had a GUI like MSAccess

Sure i'd like to hear about people delivering apps
such as the ones you can create with ms-access.

My understanding is that python is a wonderfull clean
environment to deliver pretty server-side servlets and
calculation-intensive apps of all kinds.

"Data-and-ui" -intensive apps are still very much of
a a win32 specialty with (not looking for flame here...)
vb6, vc,  delphi, vfp and others.

Python is possibly still missing the kind of data-driven
environment that you find in products such as ms access,
dbase, foxpro, paradox and other stuff.

Being an occasionnal user of those products i doubt that
these products could be replicabled in a python world
as they imply an intimate coupling between
the db-engine (generally a local one), a set of native
data-aware components and a scripting environment.

What would be welcome is some kind of generic model
for data-aware wxpython components including
dynamic data-grids, combos and others.

Anyone working on this?

My 2 cents.




Gerhard H?ring wrote in message ...
>* Mark Carter  [2002-07-18 12:51 -0700]:
>> I was using PySqlite (a module that interfaces Python with the SQLite
>> database ) the other day, and I was thinking: hey, wouldn't it be
>> great if it had a GUI like MSAccess.
>
>Isn't the main point of access was it's relatively easy to combine its
>SQL engine with forms and that it includes the development environment
>to do so?
>
>Is that what you were referring to or were you only thinking about an
>admin interface for the database?
>
>Gerhard
>--
>mail:   gerhard  bigfoot  de       registered Linux user #64239
>web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
>public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
>reduce(lambda x,y:x+y,map(lambda
x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
>
>




From jerf at jerf.org  Mon Jul 22 18:48:37 2002
From: jerf at jerf.org (Jeremy Bowers)
Date: Mon, 22 Jul 2002 22:48:37 GMT
Subject: Which gui for slow (133 Mhz) pc
References: <3d3b9eaa.7275472@news.utanet.at>
Message-ID: <9Z%_8.3000$uh7.206@sccrnsc03>

On Sun, 21 Jul 2002 06:46:21 -0500, Francesco S. wrote:

> Hello,
> 
> What gui can you recommend for my slow pc (win95).

I've tried Python + (wxWindows, Tk, PyGTK) and a couple of others, too,
and they're all about the same in speed. Either learn to live with it (as
I have), or move to a non-interpreted environment, which has its own
problems.

Alternatively, you may be able to largely develop your app outside of the
GUI and just put a GUI together last...


From dsavitsk at e-coli.net  Tue Jul 16 23:10:53 2002
From: dsavitsk at e-coli.net (dsavitsk)
Date: Wed, 17 Jul 2002 03:10:53 GMT
Subject: saving modules
References: <1d95285a.0207161412.5e101629@posting.google.com>
Message-ID: <1f5Z8.127$KM6.102563@newssrv26.news.prodigy.com>

in the short run, right click on the file, select rename, and remove the
".txt".  (if you cannot see the .txt in windows explorer then you will have
to go to Tools | Folder Options, click the view tab and deselect Hide File
Extensions yadda yadda ... (this is for win2k, not sure how the others
work)) or, from the DOS prompt, type

rename fibo.py.txt fibo.py

in the long run, don't use notepad to edit modules.

on win32, you are best off downloading the windows extensions.  you will
then have PythonWin, which is an excellent editor.  if you don't want to do
this, then you should have idle installed. (try Start | Programs | Python |
idle) or look in

C:\Python22\Tools\idle

and double click idle.py

-d


"Carl"  wrote in message
news:1d95285a.0207161412.5e101629 at posting.google.com...
> I downloaded the Python22 software along with the python manual.  In
> the manual it says to save the module fibo.py
> -I saved the module to c:\python22\fibo.py
> - In the DOS mode Directory it reads out as C:\Pyton22
>      -The file name reads out as fibopy~1 and the full name reads out
> as fibo.py.txt
> -The python shell does not recognize this as a module when I try to
> import it.
> -Please, what do I do now?




From guidance_shanghai at yahoo.com.cn  Sun Jul  7 08:26:08 2002
From: guidance_shanghai at yahoo.com.cn (Leon Wang)
Date: 7 Jul 2002 05:26:08 -0700
Subject: Chinese language support of Python?
References:  <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl>   <3d27de14$0$94898$e4fe514c@dreader3.news.xs4all.nl>
Message-ID: 

I installed ChineseCodecs1.2.0 into lib/encodings, it converts GB2312
(simplified Chinese) to UTF-8, and I can use this:

root.title(unicode('??',"eucgb2312_cn"))

Great! I can put whole raw Chinese string in source now!
Before that, I also tried ChinesePython, a Chinese translation version
of Python 2.1, it even enabled this:

root.title('??') #directly put Chinese in normal string! The Best!!

But a little pity, it translated all prompt/error messages into BIG5
(Traditional Chinese), I can not view them in my GB Windows
environment, and no GB version available now yet. I have to uninstall
it and adopted the first solution.

More pity: the "Python GUI" utility -- IDLE, can not handle Chinese
string in source file(seems bit7 removed), neither the Python2.2.1
from python.org nor above chinesepython versions. If I open my source
with IDLE and save back, all Chinese string will be changed, this
means I cannot use it even for edit. Then, how can I debug the script
in GUI?

Thanks!
Leon Wang

Boudewijn Rempt  wrote in message news:<3d27de14$0$94898$e4fe514c at dreader3.news.xs4all.nl>...
> Leon Wang wrote:
> 
> > Hi, I got the Chinese displayed correctly in window title without
> > change the default encoding in site.py by:
> > 
> > root.title(u'\u4e2d\u6587')
> > 
> > But still can not put Chinese directly as string in source, I can not
> > live with so much \u... for a whole Chinese sentence/paragraph, it's
> > impossible to read and edit them :(
> > However, I can print Chinese string (normal string, without u prefix
> > and \u codes) in console with command line python.exe. How can I let
> > Tkinter accept that?
> 
> I don't think that's going to work (caveat: I use PyQt which has different
> conventions). If you absolutely want to have Chinese characters in your
> source files*, you can do something like the following**:
> 
> root.title(unicode('???', 'utf-8')
> 
> Note that you _will_ have to construct a unicode object, not an ordinary
> string, since ordinary strings are just containers for bytes, one character
> per byte. If you want the system to understand what you mean.
> 
> You can find out which encodings are available by inspecting the 
> python/lib/encodings directory (or, python\lib\encodings): you can use
> any encoding instead of the 'utf-8'. Of course, the string must then
> be in the right encoding, too.
> 
> There are some errors in my handling of this topic in my book, but it might 
> still be useful to you:
> 
> http://www.opendocspublishing.com/pyqt/index.lxp?lxpwrap=c2029%2ehtm
> 
> errata:
> 
> http://www.valdyas.org/python/book.html
> 
> The paper version has nice pictures that are quite useful in this chapter.
> 
> * Actually I still think it would be great to be able to have sourcefiles
> in utf-8, not limited to unicode strings. I want to type:
> 
> def ??():
>     pass
> 
> That this would make my source code unreadable for a lot other people, tant
> pis, I still would like the power. Just as I want the power to do a quick
> sys.setAppDefaultEncoding('utf-8') to make sure this application sees all
> its strings as encoded in utf-8.
> 
> ** Note that this posting is encoded in utf-8. If you see gibberish instead
> of a friendly greeting, then either the message is mangled, or your 
> newsreader can't handle the encoding, or you don't have the fonts to show
> Chinese.


From aahz at pythoncraft.com  Fri Jul 19 18:37:27 2002
From: aahz at pythoncraft.com (Aahz)
Date: 19 Jul 2002 18:37:27 -0400
Subject: Python 2.3
References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com>
Message-ID: 

In article <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr at 4ax.com>,
Rhymes   wrote:
>
>When Python 2.3 will be released?

In case anyone cares about this specifically, it's supposed to be
"before the end of 2002".
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From kevin at koconnor.net  Sat Jul  6 23:12:00 2002
From: kevin at koconnor.net (Kevin O'Connor)
Date: Sat, 6 Jul 2002 23:12:00 -0400
Subject: structs in python
Message-ID: <20020706231200.A25295@arizona.localdomain>

Hello,

I often find myself using Python tuples in the same way I might use C
structs.  For example, I might store a "point" as "p = (x, y, color)".

Unfortunately, this quickly becomes cumbersome when the code starts to make
frequent references to tuple positions instead of member names.  For
example, one would see code like "delta = (p1[0] - p2[0], p1[1] - p2[1])".
Ideally, this code would read something more like "delta = (p1.x - p2.x,
p1.y - p2.y)".

Clearly, the use of classes makes the code much more readable, but
unfortunately the declarations necessary to instantiate a class is often
too much of a hassle for small and infrequently used objects.

It would be useful if there were a simple way of declaring a class with
only member variables (and no methods); an object more akin to a C struct.

What if a syntax like the following were permitted:
>>> p = ( .x = 10, .y = 11, .color = 'blue')
>>> print p.x
10
>>>

- a mix between python tuples and C99 struct initializers.  This type of
declaration would provide a convenient way of naming the parts of small
stand-alone objects - the objects that typically use tuples today.

I know this concept is not unique - I've seen implementations of a "class
Struct" that implements the above using Python's **kw syntax (Eg. "p =
Struct(x=10, y=11, color='blue')" ).  However, I have not seen wide spread
adoption of it, and I have not seen an attempt to standardize an
implementation.

My intention here is not really to propose any changes, but instead to
query the community's feelings on this topic.  Do other people find code
that uses tuples a bit cryptic?  Would others like a named initializer?  Is
this a recurring request with obvious problems?

Thanks,
-Kevin

-- 
 ------------------------------------------------------------------------
 | Kevin O'Connor                     "BTW, IMHO we need a FAQ for      |
 | kevin at koconnor.net                  'IMHO', 'FAQ', 'BTW', etc. !"    |
 ------------------------------------------------------------------------




From sjmachin at lexicon.net  Wed Jul 10 00:24:35 2002
From: sjmachin at lexicon.net (John Machin)
Date: 9 Jul 2002 21:24:35 -0700
Subject: Unicode utf-8 doesn't do back-and-forth?
References:   
Message-ID: 

martin at v.loewis.de (Martin v. Loewis) wrote in message news:...
> sjmachin at lexicon.net (John Machin) writes:
> 
> > 4 more bits? It needs 21 bits to encode the 2**20 possible
> > surrogate-described characters plus the basic 64K characters.
> > assert 21 - 16 == 5
> 
> Not really. This makes a total of 2**20+2**16 = 1114112
> characters. Now, math.log(1114112)/math.log(2) is 20.087462841250343,
> so it is rather 4.09 additional bits.
> 

Martin,]

(1) Shouldn't you deduct the 2048 surrogates from the count?
(2) Why did you round up to two decimal places and not zero decimal
places? Can you buy 4.09 cans of beer?

Cheers,
John


From erict at millfilm.co.uk  Fri Jul 19 04:31:30 2002
From: erict at millfilm.co.uk (Eric Texier)
Date: Fri, 19 Jul 2002 09:31:30 +0100
Subject: raw_input
References: <3D36C5F1.9C966A8F@millfilm.co.uk>   <3D36F9C4.A23D481A@millfilm.co.uk> <%rDZ8.16497$p56.5361636@newsb.telia.net>
Message-ID: <3D37CE62.CD1A42CE@millfilm.co.uk>

Thanks, with the import of 'readline' , raw_input
does exactly what I need. It feel a little bit strange
to me that the behavior of a command depend on
a module being loaded. It there any other case like this?

Eric


Fredrik Lundh wrote:

> Eric Texier wrote:
>
> > Yes this is not what I am looking for. I was just hoping that it was
> > a little module somewhere that will let me edit a line of command
> > in the console, you know a bit like tcsh.
>
> sounds like you want raw_input:
>
> http://www.python.org/doc/current/lib/built-in-funcs.html
>
>     raw_input([prompt])
>     ...
>   If the readline module was loaded, then raw_input() will use
>   it to provide elaborate line editing and history features.
> (but if this doesn't work for you by default, chances are that
> your Python install doesn't support readline)
>
> 



From martin at v.loewis.de  Tue Jul 16 14:30:59 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 16 Jul 2002 20:30:59 +0200
Subject: inheriting from C types
References: <878dc260.0207161005.6fec78ec@posting.google.com>
Message-ID: 

renzo.tomaselli at tecnotp.it (Renzo Tomaselli) writes:

> import ype
> class k(ype.ype):
> 	pass

What is k.__mro__?

Regards,
Martin


From sjoshi at ingr.com  Mon Jul 29 09:05:21 2002
From: sjoshi at ingr.com (Sunit Joshi)
Date: 29 Jul 2002 06:05:21 -0700
Subject: Help! Python to compare dates in diff. timezones
References: <8f8ffe67.0207280817.6fc327b8@posting.google.com> 
Message-ID: <8f8ffe67.0207290505.3f9c4682@posting.google.com>

Gerhard H?ring  wrote in message news:...
> * Sunit Joshi  [2002-07-28 09:17 -0700]:
> > Hello All
> > 
> > I have problem which is like this: 
> > I have two sites A & B which are in diff. countries in diff.
> > timezones.
> > Now both sites have same drawings (Microstation files with same names)
> > whose revision dates (as integer since epoch) are stored in a table in
> > database at both sites. The database structure is same on both sites
> > with identical table names.
> 
> Is there some sort of replication taking place?
> 
> > Now since the sites are different timezones, I was wondering what
> > would be the best way to compare drawings, using Python, that have
> > changed between two sites; for e.g. if site A wants to gets a list of
> > all models that have changed at site A.
> 
> Just normalize the dates to use GMT, so that you can compare them.
> 
> > I'm open to any suggestion like using a query over HTTP, using XML,
> > etc.
> 
> It sounds easiest to just make both db servers accessible at sites A and
> B and let that do somebody who knows their stuff about security (I'm not
> saying you don't). Another transport layer like HTTP doesn't add any
> value for database access, IMO.
> 
> Gerhard


Like I mentioned, the time is stored in the table as long secs, so
converting to GMT is basically, time.gmtime([secs]). I guess I can do
this for both the sites and just compare(A, B). A +ve would then mean
A's changed, -ve B's changed otherwise both are the same.

Does this sound right....


thanks
Sunit


From aleax at aleax.it  Tue Jul  9 08:48:19 2002
From: aleax at aleax.it (Alex Martelli)
Date: Tue, 09 Jul 2002 12:48:19 GMT
Subject: sorting many arrays from one...
References: 
Message-ID: 

Shagshag13 wrote:

> hello,
> 
> i'm looking for an "efficient" way of sorting many arrays driven by one,
> for example
> 
> drive = [1, 4, 2, 3]
> other1 = [a, b, c, d]
> other2 = [ k, j, h, l ]
> other3 = [14, 18, 19, 11]
> 
> and i get :
> 
> drive = [1, 2, 3, 4]
> other1 = [a, c, d, b]
> other2 = [ k, h, l, j]
> other3 = [14, 19, 11, 18]

aux_list = zip(drive, other1, other2, other3)
aux_list.sort()

for i in range(len(drive)):
    drive[i], other1[i], other2[i], other3[i] = aux_list[i]


Alex



From juneaftn at REMOVETHIShanmail.net  Fri Jul 26 10:35:21 2002
From: juneaftn at REMOVETHIShanmail.net (Changjune Kim)
Date: Fri, 26 Jul 2002 23:35:21 +0900
Subject: [Re] euid/egid eaten up by os.popen
References:  
Message-ID: 

"Donn Cave"  wrote in message
news:ahptae$22qg$1 at nntp6.u.washington.edu...
> Quoth janeaustine50 at hotmail.com (Jane Austine):
> | >I bet you're running Linux.  My suggestion is to try popen2, and
> |
> | Yes, Red Hat 7.3
> |
> |> specify the command as a list of arguments.  For example, if you
> |> have been writing
> |>    fp = os.popen('id')
> |> then try
> |>    fp, ignore = popen2.popen2(['id'])
> |
> | Have done that and it didn't work still.
> ...
> | It seems like when popen forks for a new shell, euid is all cleared.
>
> Yes, I think it's the shell, all right.  All I can say is, popen2()
> works for me - *IF* I use the list of parameters as above.  It doesn't
> help to just use popen2 instead of popen, and give it the same command
> string.
>
> Donn Cave, donn at u.washington.edu

You can pass parameters for the /bin/sh with popen2 in posix.

Try this:

import popen2
cmd="id"
cmd=['/bin/sh','-pc',cmd]
f,ign=popen2.popen2(cmd)

The parameter "-p" tells sh not to reset euid as to ruid.



From aleax at aleax.it  Fri Jul 26 04:28:59 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 26 Jul 2002 08:28:59 GMT
Subject: how to count lines in a file ?
References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com>   
Message-ID: 

Fredrik Lundh wrote:

> Alex Martelli wrote:
> 
>> > (does anyone here even know that readline takes an optional
>> > integer argument, and what it does? ;-)
>>
>> I would hope so, given that
>> http://www.python.org/doc/current/lib/bltin-file-objects.html
>> documents it so clearly.
> 
> does anyone here think that when I asked that question, I did
> that because I didn't know, and wanted someone to look it up
> for me? ;-)

"look it up"...?  You asked, or rather wondered with a smilie,
whether anybody knew.  I opined some did, explained the reason
for my opinion, and, as I was at it, took the occasion to remind 
some of those who didn't.  Not you, for sure, o mighty exhalted
uppercasedbot, but, last I checked, you're not the only one
reading this thread.

And as it happens some _other_ readers did NOT know about the
differences between the seemingly-identical numerical parameter
to readline and readlines, witness the grumbling about it in
follow-ups.  Now, why the BDFL things the (strict) numerical
parameter to *readline* is the design error, rather than the
(advisory) one to *readlines*, which is the one which attracted
the grumblings, might perhaps be interesting to discuss.  But
(my bias) discussions are often more interesting when various
discussants and onlookers share some fundamental knowledge.


Alex



From peter at engcorp.com  Tue Jul 16 18:13:52 2002
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 16 Jul 2002 18:13:52 -0400
Subject: starting other programs from within python
References: <20020716.171155.619290071.333@beer.com>
Message-ID: <3D349AA0.1AE34452@engcorp.com>

hejduk wrote:
> 
> However, when I monitor the memory usage of the interpreter it appears
> that when this outside application is closed that not all the memory resource is
> returned, ie:
> 
> before: 7248 k
> during: 18624 k
> after:  12284 k

Analysing memory usage like this with a single run is never a good
idea.  Run it multiple times (start, exit, start, exit) and monitor
the usage.  You may find that it "settles out" after two times and
does not, in fact, leak resources.  You may also find it climbs and
falls in a cycle, which is one of several possible effects you might
see, since the operating system is probably doing an awful lot of
sophisticated stuff you aren't even noticing.

In any event, you didn't mention a number of important facts, like
what operating system you are using, how you are monitoring memory
usage, what version of Python you have, and so on.  Without that
it may be difficult to draw any useful conclusions.

-Peter


From python at dohao.org  Thu Jul 11 08:31:54 2002
From: python at dohao.org (Wenshan Du)
Date: 11 Jul 2002 05:31:54 -0700
Subject: New IDLE with unicode support
Message-ID: 

I improved IDLE, it supports unicode or multibyte character. You can
find, replace or find in files with multibyte character in IDLE now. I
like it.

http://www.dohao.org/python/download/idle.zip

Enjoy!

Wenshan Du
python at dohao.org


From phoebe_1 at att.net  Wed Jul  3 17:17:58 2002
From: phoebe_1 at att.net (Holden Caulfield)
Date: 3 Jul 2002 14:17:58 -0700
Subject: metaclass & __slots__
Message-ID: 

Greetings,
  I am trying to get a hang of the metaclass and some new features in
v2.2. But, I am running into a problem or it is a limitation, I guess.
I just need clarification. Here is the code, it is an extension of
Guido's autoprop example.
Basically, I am trying to set "property" attributes AND also limit the
attributes set by using "__slots__".

It looks like because the Metalcass statement is executed in the end
of the class statement, hence the class methods seems to have a
"early" binding to the __slots__ variable. Is this behaviour normal?

Thanks
M

-----

class MX(type):
    def __init__(cls,name,bases,dict):
        super(MX,cls).__init__(name,bases,dict)
        props = {}
        slots = getattr(cls,'__slots__', [])
        print slots
        for v in dict.keys():
            vs = v.startswith
            if vs("_get_") or vs("_set_"):
                props[v[5:]] = 1
        for v in props.keys():
            fget = getattr(cls,"_get_%s" % v, None)
            fset = getattr(cls,"_set_%s" % v, None)
            setattr(cls,v,property(fget,fset))
        slots.append("_%s__%s" % (name,v))
        setattr(cls,'__slots__',slots) 

class X(object):
    __metaclass__ = MX
    __slots__ = ['z']
    def __init__(self):
        self.x = 1
        self.z = 2
    def _get_x(self):
        return self.__x
    def _set_x(self,v):
        self.__x = v

def Test():
    y = X()
    y.x = 4

if __name__ == "__main__": Test()

--------------
The above code fails with:
Traceback (most recent call last):
  File "__test.py", line 50, in ?
    if __name__ == "__main__": Test()
  File "__test.py", line 43, in Test
    y = X()
  File "__test.py", line 34, in __init__
    self.x = 1
  File "__test.py", line 39, in _set_x
    self.__x = v
AttributeError: 'X' object has no attribute '_X__x'


From peter.schwalm at epost.de  Mon Jul  1 17:18:22 2002
From: peter.schwalm at epost.de (Peter Schwalm)
Date: 1 Jul 2002 14:18:22 -0700
Subject: Testing self-written imported Modules in a Zope python external method
Message-ID: <5cf809e9.0207011318.3965d29d@posting.google.com>

I have a written a Python external script in Zope. It uses a small
self-written helper module producing a page header. Naturally the
first version of this module is not error free. During testing I
discovered that Zope never refreshes the version of this imported
module. Zope even doesn't care, if I delete the generated .pyd-File.

Does this mean I always have to completely shutdown Zope if I want to
test a new version of the module?


From kdart at kdart.com  Wed Jul 31 06:57:52 2002
From: kdart at kdart.com (Keith Dart)
Date: Wed, 31 Jul 2002 10:57:52 GMT
Subject: SNMP module in python
References: <3d329ac0.330042218@news.skynet.be> 
Message-ID: 

In article , "Roy Smith"
 penned these words:

> pixie888 at hotmail.com wrote:
>> I am looking for a module written in Python to perform SNMP
>> communication. Can anyone tell me where I can find one?
> 
> I've been using PySNMP, http://sourceforge.net/projects/pysnmp, which is
> written entirely in Python.  Because it's 100% Python (all the way down
> to the messy BER stuff), it's very portable.  On the other hand, I
> suspect performance is poor.  I havn't pushed the corners of the
> envelope much, but so far it seems to work for basic stuff.
> 
> The other alternative is yapsnmp, http://yapsnmp.sourceforge.net, which
> is a SWIG wrapper around the net-snmp (nee ucd-snmp) package.  In
> theory, I like yapsnmp's approach better, but as a practical matter,
> getting it to compile and run has been problematical; I don't have
> exactly the same version of net-snmp installed as the author and ran
> into compile problems with mis-matched headers.



There is also extensive SNMP support in the pyNMS package. 

http://pynms.sourceforge.net/

There is an SNMP package in that collection of stuff. It used "compiled"
MIBs (MIBs converted to Python source code) that allows for easy
scripting. Or you can just use OID objects. 

This started out as an extension to the pysnmp package, but ended up
being an almost total re-write. Many bugs in the ber module were also
fixed. 

It was designed to be easy to use, and flexible. 

I like the programmer's interface (API) to this package much better than
the others. But that stands to reason since I wrote it. ;-) Please tell me
what you think if you use it. 


There is also XML and XHTML support in that package, among other things. 


 
--                           ^
                           \/ \/
                           (O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart
 
  
----------------------------------------------------------------------------
Public key ID: B08B9D2C Public key: 
============================================================================


From mcherm at destiny.com  Thu Jul 18 16:00:57 2002
From: mcherm at destiny.com (Michael Chermside)
Date: Thu, 18 Jul 2002 16:00:57 -0400
Subject: Apply and map function
Message-ID: <3D371E79.2010605@destiny.com>

> I want to implement the apply or map function into the following code:
> 
>         initmethods = InitMethods()
>         methods = {
>             'SiteNav_OpenTreeLevel': initmethods.init_opentreelevel(),
>             'SiteNav_LinkTreeItem': initmethods.init_linktreeitem(),
>             'SiteNav_ActiveTreeItem': initmethods.init_activetreeitem(),
>             'SiteNav_CloseTreeLevel': initmethods.init_closetreelevel(),
>             'local_css': initmethods.init_localcss()
>             }
>         for (methodname,method) in methods.items():
>             self.createDTMLMethod(methodname, '',method)
> 

I'm not certain I understand what you want, but is this it?

# Untested code
some_method_name_here(self):
     initmethods = InitMethods()
     methods = {
         'SiteNav_OpenTreeLevel': initmethods.init_opentreelevel(),
         'SiteNav_LinkTreeItem': initmethods.init_linktreeitem(),
         'SiteNav_ActiveTreeItem': initmethods.init_activetreeitem(),
         'SiteNav_CloseTreeLevel': initmethods.init_closetreelevel(),
         'local_css': initmethods.init_localcss(),
         }
     def createDTMLMethod( (methodname, method) ):
         self.createDTMLMethod(methodname, '', method)
     map( createDTMLMethod, methods.items() )

The only trick I used here is to write a function that expected the pair 
of arguments methods.items() provides (instead of two separate items). 
If that wasn't your problem, try explaining your question again.

-- Michael Chermside







From whisper at oz.net  Tue Jul  2 23:55:13 2002
From: whisper at oz.net (David LeBlanc)
Date: Tue, 2 Jul 2002 20:55:13 -0700
Subject: GoTo considered missing
In-Reply-To: <002901c2222c$100a2180$289dfea9@t9k2t3>
Message-ID: 

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Harvey Frey
> Sent: Tuesday, July 02, 2002 17:54
> To: python list
> Subject: GoTo considered missing
>
>
>     OK. I'm a spaghetti-coder from way back, new to Python.
> I didn't even realize there was no "goto" till I tried to rewrite a big C
> program in Python.
>
>     Breaks and Continues are fine for single loops, but:
> What is the approved Python method for getting from the bottom of a set of
> nested loops to the top?

Return works well. So would an exception. However, if you're writing python
code that uses nested loops like that, it's possible you're not taking good
advantage of Python's features.

>     Maybe I could rewrite the big loop with function calls, but I'd be
> knee-deep in recursion.

Care to share what you're working on? It might be that you're using "basic
think" and not considering Python's advanced features.

> Harvey
> =========================
> Harvey S. Frey MD PhD Esq.
> hsfrey at harp.org  www.harp.org
> C'est Vrai. C'est Frey!
> =========================

Dave LeBlanc
Seattle, WA USA





From pinard at iro.umontreal.ca  Tue Jul 30 07:40:46 2002
From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard)
Date: 30 Jul 2002 07:40:46 -0400
Subject: lexing nested parenthesis
In-Reply-To: 
References: 
	
Message-ID: 

[Kristian Ovaska]

> The language category you're dealing with is called context-free grammars.
> It's more expressive than regular languages, and it can parse any
> programming language.

Any? :-)

I would not go that far.  There are strange beasts out there.  Moreover,
people usually throw good parts of the complexity in "semantic analysis"
passes.  In the caricatural case, your grammar may parse individual
characters and leave it all to later compilation stages, so a fortiori, any
kind of parser will do.  We are diving in the complex art of compromises! :-)

> Yacc is a classic C tool for this. PLY is a Lex+Yacc implementation in
> pure Python. SPARK is another Python tool, and there are some others.

I found SPARK and PLY to be interesting for parsing, as Yacc replacements.
Scanning with these tools falls back to building big regular expressions,
and relying on the `re' module.  I just tried Greg Ewing's PLEX yesterday,
which for a scanner, is much closer to Lex.

John Aycock's SPARK is surprisingly elegant, powerful and compact.
PLEX and PLY are not so compact, they also require some more work to use,
but they reward us with speedier analysis, especially for bigger grammars.

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



From dyoo at hkn.eecs.berkeley.edu  Mon Jul  8 04:47:34 2002
From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo)
Date: Mon, 8 Jul 2002 08:47:34 +0000 (UTC)
Subject: Is there a re guru out there?
References: 
Message-ID: 

Krzysiek Czarnowski  wrote:
: I try to convert some LaTeX constructs to "plain" equivalents like \(,\) -->
: $, \[,\] --> $$
: and \frac{...}{...} --> {...\over ...}. The \frac bit appeared not to be
: trivial since ... should be balanced with respect to { }.

Hello!

Ah, a LaTeX to TeX converter.  Cool!


If you can guarantee that there isn't any nested braces within the
"frac" groups, then you can probably do this by making your regular
expression "non-greedy".

For example, let's say that we'd like to transform:

    {a}{b} --> (a b)


Here's an initial shot at it:

###
>>> re.sub(r'\{(.*)\}\{(.*)\}', r'(\1 \2)', '{foo}{bar} {baz}{boo}')
'(foo}{bar} {baz boo)'
###

The problem here is that the regular expression '.*' is too greedy: it
tries to eat as much as it can, and doesn't stop at the first closing brace.


To fix this, we can tell the regular expression to not be so greedy
about things, making it a little more indecisive by using the '?'
modifier:


##
>>> re.sub(r'\{(.*?)\}\{(.*?)\}', r'(\1 \2)', '{foo}{bar} {baz}{boo}')
'(foo bar) (baz boo)'
###

You can probably do a similar regular expression, as long as there
aren't groups nested within groups.



However, if there are groups within the frac groups, like:

    \frac{e^{42}}{\pi}

then that will cause problems.  This kind of pattern is something that
regular expressions alone won't be able to cope with, because the
grammar is recursively defined.  You'll need something more powerful
than a regular expression --- you'll need a parser.



Parsing is a large topic, so someone more competent than me should
handle it.  *grin*.  But here's an article that talks about parsing
with Python:

    http://www-106.ibm.com/developerworks/linux/library/l-simple.html?dwzone=linux



Best of wishes!


From shagshag13 at yahoo.fr  Thu Jul 25 14:22:48 2002
From: shagshag13 at yahoo.fr (Shagshag13)
Date: Thu, 25 Jul 2002 20:22:48 +0200
Subject: xml processing : too slow...
References:     
Message-ID: 

"Alex Martelli"  a ?crit dans le message de news: CPV%8.118293$Jj7.2763401 at news1.tin.it...
> Shagshag13 wrote:
>
> >> p.parse('%s' % line, 1)
> >>
> >> should be satisfactory for checking this kind of "sort of
> >> well-formedness", unless there are yet more specs as yet
> >> unexpressed.
> >
> > that's why i had done :
> >>>> anotherline = '' + line + ''
> >>>> p.Parse(anotherline, 1)
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >     p.Parse(anotherline, 1)
> > ExpatError: junk after document element: line 1, column 0
> >
> > but it still don't work, as much has:
>
> But ARE you making a new parser object p for each line you
> have to parse?  I don't see the expat.ParserCreate call here.
> I've already indicated a few posts ago that you need that.

GREAT THANKS !!!

>>> p = expat.ParserCreate(); p.Parse('%s' % line, 1)
1

s13.




From shalehperry at attbi.com  Fri Jul 12 11:47:52 2002
From: shalehperry at attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Jul 2002 08:47:52 -0700 (PDT)
Subject: Making code 2.1 compatible
In-Reply-To: <3D2EF644.256999D1@tds.net>
Message-ID: 

On 12-Jul-2002 Edward K. Ream wrote:
> Thanks for the reply Mark,
> 
>> did you know that 2.2 has been deemed the release targeted for stability by
>> the pbf?
> 
> pbf? Is that Guido?  Oh, Google tells me it's the Python Business
> Forum.  Ok, so pbf likes 2.2...
> 
> I'm happy with 2.2.  However, having 2.1 code in Leo would make Leo a
> bit more available to people until everybody changes over.  Maybe
> everyone should just convert to 2.2...And Leo for that matter :-)
> 

The only way to support interoperability is to actually test it.  You need a
copy of python 2.1 SOMEWHERE.  Another machine, your friend, a client, somebody.

I must be spoiled by Debian making this easy (-:  I have 1.5.2, 2.1, and 2.2
installed.




From aldo at nullcube.com  Mon Jul  1 04:08:42 2002
From: aldo at nullcube.com (Aldo Cortesi)
Date: Mon, 1 Jul 2002 18:08:42 +1000
Subject: stream to string-question
In-Reply-To: 
References: 
Message-ID: <20020701080842.GA5084@nullcube.com>

Thus spake Klaus Reinhardt (K.Rdt at TU-Berlin.DE):

> ---------------------------------------------------------------------
> Hi
> 	y=os.popen( 'netstat -a -n','r').read()
> # Aktive Verbindungen
> # 
> #   Proto  Lokale Adresse         Remote-Adresse            Status
> #   TCP    0.0.0.0:1171           0.0.0.0:0              LISTENING
> #   TCP    130.149.164.212:1171   130.149.4.11:110       ESTABLISHED
> 	print y
> 	for i in y: 
> 		print "--------: ", i
> The last is outputting each character in a single line. Is
> there a function to convert this stream in the text-rows?


The variable "y" above is a single, long string with some
embedded newlines. When you iterate over a string you get
its component characters one by one. 

What you really want to do is to split the string up into a
list of lines. Luckily, the string type has a method that
does exactly that... Try:
	
	lines = y.splitlines()
	for l in lines:
		print "---: ", i



Cheers,



Aldo



-- 
Aldo Cortesi
aldo at nullcube.com




From fakeaddress at nowhere.org  Mon Jul 29 10:29:43 2002
From: fakeaddress at nowhere.org (Bryan Olson)
Date: Mon, 29 Jul 2002 14:29:43 GMT
Subject: How to detect the last element in a for loop
References:    <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net>
Message-ID: <3D455198.509@nowhere.org>

Tom Verbeure wrote:
[...]
 >> > Given that you have an explicit iterator, wouldn't it be trivial to
 >>add an
 >> > 'end()' method to this iterator to indicate the end of the sequence
 >>(just
 >> > like C++ iterators) ?
 >> >
 >> > This would result in:
 >> >
 >> > for item in iterator:
 >> >     if iterator.next().end():
 >> >         do_something_special
 >> >
 >> >     do_something_for_all
 >>
 >>I think you've misunderstood the end() value in C++ STL iterators.  It
 >>is not the last item, but one past the last item.  The iterator can take
 >>the end value, but dereferencing the end value is illegal.
 >
 >
 > That would be the case if I would check for iterator.end(), but I 
check for
 > iterator.next().end() !

For a given C++ STL iterator, end() will return the *same* value no
matter how many times you advance the iterator.  It looks like you
wanted:

     ...
     if iterator.next() == iterator.end():
         do_something_special


--Bryan




From david.levy at xrce.xerox.com  Wed Jul 24 04:39:52 2002
From: david.levy at xrce.xerox.com (David Levy)
Date: Wed, 24 Jul 2002 10:39:52 +0200
Subject: SOAP.py and complex types
References: <3D3BDD02.3997B185@xrce.xerox.com> <3d3e076c.596010898@news.wlg.ihug.co.nz>
Message-ID: <3D3E67D8.E27B4B96@xrce.xerox.com>

thanks !

that helps me indeed !
I could call the Amazon web service :)

is there any python library to handle XML Schemas ?

Thanks



Culley Angus wrote:

> I had some issues with this as well...
>
> My problems were solved using by including the typename in the
> structType.
>
> soapobj=SOAP.structType(data=structdat, name=(namespace, myname))
>
> where 'myname' is the type name of the object to pack, i.e. "Details"
>
> Hope this helps.

--
_____________________________________________________________
David Levy                       Xerox Research Centre Europe
6, ch. de Maupertuis             F - 38240 Meylan
Email david.levy at xrce.xerox.com  http://www.xrce.xerox.com





From akhar at videotron.ca  Mon Jul 22 02:21:07 2002
From: akhar at videotron.ca (akhar)
Date: Mon, 22 Jul 2002 01:21:07 -0500
Subject: openning links from python?
Message-ID: 

is it possible to have a url load inside the OSes preferred browser?




From gerhard.haering at gmx.de  Sat Jul 20 10:51:33 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 20 Jul 2002 14:51:33 GMT
Subject: Python 2.3
References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <1027175934.94979.0@iris.uk.clara.net>
Message-ID: 

Richard Townsend wrote in comp.lang.python:
> "Rhymes"  wrote:
>>
>> When Python 2.3 will be released?
> 
> Also, is there likely to be a 2.2.2 ?

Yes.

Btw. to look what the Python developers are up to, you can read the
python-dev archives (http://mail.python.org/pipermail/python-dev/).

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))


From brueckd at tbye.com  Tue Jul 30 19:18:11 2002
From: brueckd at tbye.com (brueckd at tbye.com)
Date: Tue, 30 Jul 2002 16:18:11 -0700 (PDT)
Subject: global interpreter lock not working as it should
In-Reply-To: <200207302143.RAA26002@test-area.com>
Message-ID: 

On Tue, 30 Jul 2002, anton wilson wrote:

> Maybe I am not being clear enough. I am concerned with a multi-threaded 
> program that does not do any form of blocking on a Linux/Unix box.

Quick tangential question: if there's no blocking of any kind, why are you
using threads, anyway? Off the cuff thinking says this seems like a misuse
of them.

> I have proven this by even examining what happens within the interpreter with 
> this code in ceval:
> 
> 
>                                 oldt = tstate;    /*<---- My code*/
> 
>                                 if (PyThreadState_Swap(NULL) != tstate)
>                                         Py_FatalError("ceval: tstate mix-up");
> 
> 
>                                 PyThread_release_lock(interpreter_lock);
> 
>                                 /* Other threads may run now */
>                                 /*sched_yield();*/
> 
>                                 PyThread_acquire_lock(interpreter_lock, 1);

Note that control does not necessarily return to this thread at this 
point! An attempt is made to acquire the lock - sometimes the same thread 
will get it, sometimes not, and whether or not it does is entirely up to 
the platform's thread library.

> The great majority of the time, my print statement will be printed, meaning 
> the GIL was not released.

No! This "proves" that the GIL was released and _the same thread was
allowed to reacquire it immediately_. The difference between my statement 
and yours is where your confusion lies.

>  but the put-it-up-for-grabs-every-10-instructions functionality
> > works just fine too. Consider:

[snip my program that shows lack of thread starvation]

> There are several reasons why your program seems to work.
> The first obvious reason is that the main thread sleeps. If you remove the 
> sleep, you will see output that looks like this
> 
> [0, 0, 0]
> 
> ....(100+ times in all)...
> 
> [35499, 16419, 0]
> 
> ...(100+ times in all) ....
> 
> [35499, 16419, 11556]
> 
> This proves that the GIL does not block very often, and definitely not every 
> 10 byte codes. Think about this for a while.

 No, it doesn't "prove" anything about the GIL. Without the print
statements, the main thread is spinning like crazy - the other threads
probably aren't even getting _started_ right away. There are (at least)  
two different mechanisms at work here: the GIL-releasing code and your
OS's (or thread library's) thread scheduler. Even though the GIL gets
released, your OS/thread library may choose NOT to switch thread contexts. 
IOW, your main thread still may have lots of time left in its timeslice, 
and so the thread library is saying, "hey, keep running!". 

Note that if you try the above experiment in C (start 3 threads and 
immediately have main thread spin and print out wildly) you'll get very 
similar output (lots of [0,0,0]'s printed at the beginning, etc). In fact, 
I'd really recommend that you do this, because once you're familiar with 
how it all works in C then there's really no surprises with how it works 
in Python - IMO you've confused yourself by zeroing in on the GIL when in 
reality it's quite transparent.

If anything, the program output is "proving" that your threading library
is behaving efficiently - because there is no reason to force a context
switch (e.g. blocking I/O), it is being sensible and avoiding the
expensive switch by letting each thread use as much of its timeslice as
possible. During each timeslice the GIL is probably being released a
reacquired oodles of times, and this is correct behavior.

> So, the GIL does not blcok as intended, and this probably needs to be looked 
> into.

Just curious: how do you explain all the multithreaded Python programs 
that currently work just fine? Are these all flukes?

-Dave




From stefan.heimann at web.de  Sun Jul 21 06:16:10 2002
From: stefan.heimann at web.de (Stefan Heimann)
Date: 21 Jul 2002 10:16:10 GMT
Subject: XSLT processor
References:  <21k_8.103407$%%2.4630636@news2.east.cox.net>
Message-ID: 

thehaas at binary.net  wrote::

> Stefan Heimann  wrote:
>> Saxon - a XSLT processor written in Java - provides such an internal
>> API. Does anyone know if there is something similar for python?
> 
> I have no idea if the "pure-Python" XSLT processors (4xslt, etc.) have
> that, but you want Python and functionality in Saxon, than use Jython.
> It works great with external Java objects (I use it for that myself), and
> I have never had any Python/Jython compatibility problems.  Note,
> however, that Jython is currently at 2.1, so no generators, or
> iternators. 

that's a good idea. I thought I can find a xslt processor written in
C/C++ that is suitable for my needs, but saxon seems the only
processor that allows to register arbitrary functions as templates.

Bye Stefan


From eric.brunel at pragmadev.com  Wed Jul  3 12:18:16 2002
From: eric.brunel at pragmadev.com (Eric Brunel)
Date: Wed, 3 Jul 2002 16:18:16 +0000
Subject: Who is the user??
References: 
Message-ID: 

Kristian Sons wrote:
> Hi,
> 
> is there a possibility to find out, wich user startet the python-script??
> 
> Thanks a lot,
>   Kristian

Try:

import getpass
print getpass.getuser()

This should work everywhere.

HTH
-- 
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com


From markus.vonehr at ipm.fhg.de  Wed Jul 10 06:28:27 2002
From: markus.vonehr at ipm.fhg.de (Markus von Ehr)
Date: Wed, 10 Jul 2002 12:28:27 +0200
Subject: PDf creating with Python? Howto?
References: <3D2BE41E.3040508@weknowthewayout.com>
Message-ID: <3D2C0C4B.2F14FE95@ipm.fhg.de>

Hi Johan,

you can use a Tkinter canvas for drawing including your
images with photoimage.

To draw the canvas use (replacing mycanvas with your canvas name):

mycanvas.postscript(file="test.ps")

The .ps file can be converted to postscript either with a
command line tool or Acrobat Distiller.

Markus


From aahz at pythoncraft.com  Sun Jul 28 09:47:43 2002
From: aahz at pythoncraft.com (Aahz)
Date: 28 Jul 2002 09:47:43 -0400
Subject: Programming/Life ratio (was Re: __call__ bad style?)
References: <7xznwk1hfy.fsf@ruckus.brouhaha.com>   
Message-ID: 

In article ,
Michael Hudson   wrote:
>
>Then I'm ahead of you by ... erm ... 13 years.  Wow, I've been
>programming (admittedly only as a hobbyist) for nearly a third of my
>life.  That's scary somehow.

Heh.  For me, it's closer to 3/4 of my life, and I've been doing it for
pay more than half my life.  Then again, I'm still under 40, and I'm one
of the few people in that category who's used JCL.  (Not the only one,
from the last time we had this thread.)

On the gripping hand, I never really thought of myself as a programmer
until I learned Python.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From donn at u.washington.edu  Thu Jul 25 13:31:30 2002
From: donn at u.washington.edu (Donn Cave)
Date: 25 Jul 2002 17:31:30 GMT
Subject: euid/egid eaten up by os.popen
References: 
Message-ID: 

Quoth janeaustine50 at hotmail.com (Jane Austine):
...
| When we print out geteuid from the python code, it prints out as we
| expect. However, when we call a popen, the pipe is run without the
| effective user/group id.

I bet you're running Linux.  My suggestion is to try popen2, and
specify the command as a list of arguments.  For example, if you
have been writing
   fp = os.popen('id')
then try
   fp, ignore = popen2.popen2(['id'])

The same goes for system(), incidentally - spawnv() will work better.

The problem is evidently caused by bash.  If you contrive to run
bash to interpret the command string on some other platform, it
will happen the same way - it's only a Linux bug because Linux uses
bash here.

	Donn Cave, donn at u.washington.edu


From corrada at ciirsrv.cs.umass.edu  Thu Jul 18 11:44:01 2002
From: corrada at ciirsrv.cs.umass.edu (Andres Corrada-Emmanuel)
Date: Thu, 18 Jul 2002 11:44:01 -0400 (EDT)
Subject: How to set tempfile.tmpdir?
Message-ID: 

Hi,

I'm trying to use tempfile to generate a temporary filename in the
directory of my chossing. I thought that this would work:

import tempfile

tempfile.tmpdir = '/my/path'
temp_name = tempfile.mktemp()

However, it doesn't. I'm working on SunOS and temp_name always comes back
with /tmp/some_unique_identifier.

What am I doing wrong?

Andres Corrada-Emmanuel
Senior Research Fellow
Center for Intelligent Information Retrieval
University of Massachusetts, Amherst





From zope at thewebsons.com  Tue Jul  9 19:43:43 2002
From: zope at thewebsons.com (Ben Ocean)
Date: Tue, 09 Jul 2002 16:43:43 -0700
Subject: Open Source Metaphysics (OT)
Message-ID: <5.1.0.14.0.20020709164326.00a19140@mail.thewebsons.com>

Hi;
This is a request for help. If metaphysics interests you, read on. If not, 
you probably want to skip this email.

I'm building a Web site to create open source metaphysics. There are many 
reasons and methodologies, but here are some:
* Create a _science_ out of numerology by basing it in the study of taxonomy
* With that foundation, create a science out of all matrix-based 
metaphysical systems, including astrology, the I Ching, the Enneagram, etc.
* Enable an open source community to develop the same

There's much more to it, but I want to be as brief as possible here. What 
I'm looking for is a few competent and trustworthy programmers who would be 
willing to help me build this. There is no money involved: this is a work 
of love. If your curiosity is piqued, go here:

http://performancemarketers.com/Logos

Thanks for your time,
BenO 






From jblazi at hotmail.com  Tue Jul 16 13:07:13 2002
From: jblazi at hotmail.com (JB)
Date: Tue, 16 Jul 2002 19:07:13 +0200
Subject: Making code faster
References: <3d3445f9_7@news.newsgroups.com> 
Message-ID: <3d3450f2_6@news.newsgroups.com>

Gerhard H?ring wrote:

> JB wrote in comp.lang.python:
>> How can I make the following code faster? I open a (text)
>> file and read the lines in the file. The lines of the
>> file have the form
>> 
>> [,]
>> 
>> After the lines have been loaded, I set up a new list via
>> the function tmp1.
>> 
>>     i = -1
>>     print 'loading file'
>>     def tmp1(s):
>>       global i
>>       i += 1
>>       return
>>       QSimpleViewItem(i,self.sv.lv.newColor,eval(s))
>> 
>>     try:
>>       myfile = open(filename)
>>     except:
>>       pass
>>     else:
>>       tmp = myfile.readlines()
>>       print 'lines loaded'
>>       datei.close()
>>       self.sv.lv.rows = map(tmp1,tmp)
>>       self.sv.lv.visible = range(len(self.sv.lv.rows))
>>       print 'lines decoded',self.sv.lv.rows[0].col[0]
>> 
>> Any ideas? It is astonishing that loading the lines from
>> external storage takes much less time than the mapping
>> itself!
> 
> The line "self.sv.lv.rows = map(tmp1,tmp)" makes some call
> into an external library (PyQt?) that's likely taking up
> the whole time.

Yes, sorry. You mean the QListSimpleViewItem constructor:

class QSimpleViewItem:
  def __init__(self,id,color,tuple):
    self.id    = id
    self.col   = tuple
    self.sel   = 0
    self.color = color

It is not very time consuming.

-- 
Janos Blazi


-----------== Posted via Newsfeed.Com - Uncensored Usenet News ==----------
   http://www.newsfeed.com       The #1 Newsgroup Service in the World!
-----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =-----


From tim at zope.com  Wed Jul  3 12:15:02 2002
From: tim at zope.com (Tim Peters)
Date: Wed, 3 Jul 2002 12:15:02 -0400
Subject: Thread safetyness in Python
In-Reply-To: <15651.6532.968436.256710@12-248-8-148.client.attbi.com>
Message-ID: 

[Oren Tirosh]
> So a+=1 isn't atomic, but l+=[1] is. Interesting.

[Skip Montanaro]
> How so?
>
>     >>> def f(l):
>     ...   l += [1]
>     ...
>     >>> dis.dis(f)
>               0 LOAD_FAST                0 (l)
>               3 LOAD_CONST               1 (1)
>               6 BUILD_LIST               1
>               9 INPLACE_ADD
>              10 STORE_FAST               0 (l)
>              13 LOAD_CONST               0 (None)
>              16 RETURN_VALUE
>
> Looks to me like there's the opportunity for another thread to sneak in
> there and modify l between the LOAD_FAST and STORE_FAST instructions...

The deal is that the STORE_FAST is really a nop in this case:
list.__iadd__(obj) returns obj, and rebinding obj (the STORE_FAST) to the
same value is a semantic nop.

Another way to look at it is that

    list += iterable

is equivalent to

    list.extend(iterable)

except that under the covers the implementation makes the former act like

    list.extend(iterable)
    list = list

The bytecode for the "list = list" part has no effect in the end, so doesn't
matter.





From jerf at jerf.org  Wed Jul 24 18:10:58 2002
From: jerf at jerf.org (Jeremy Bowers)
Date: Wed, 24 Jul 2002 22:10:58 GMT
Subject: Tk Dynamic Menus problem
Message-ID: 

For the following Tk test program, I am having a problem. A dynamic menu
is being generated every time I click the "Test" menu, and three menu
options are generated, each with a different command. However, if you
click on any of the three options, the *third* command is executed, so all
menu options print 3. I expect the menu options to do what they say.

I'd rather do it this way then fiddle with the menu options on each drop
down, as that's complicated when I can't guarentee the same number of
options on each drop down. (There are good reasons for that that make UI
sense in the context of the program this is getting used in.)

I've tried a number of workarounds, but none seem to work. Is this a bug
in Tk or Tkinter? (It doesn't seem like this should be impossible...)

---------

from Tkinter import *

def printFunc(s):
    print s

class App:
    def __init__(self, master):
        self.frame = Frame(master, width = 200, height = 40)
        self.frame.pack()

        self.menu = Menu(master)
        master.config(menu = self.menu)

        self.dynmenu = Menu(self.menu, postcommand = self.updateMenu)
        self.menu.add_cascade(label="Test", menu = self.dynmenu)

    def updateMenu(self):
        self.dynmenu.delete(0, 99) # big num to get everything

        for i in [1, 2, 3]:
            self.dynmenu.add_command(label = "Print %i" % i,
                                     command = lambda: printFunc(i))

root = Tk()
app = App(root)
root.mainloop()



From plungermonkey at cox.net  Mon Jul 15 13:01:53 2002
From: plungermonkey at cox.net (Jef)
Date: Mon, 15 Jul 2002 17:01:53 GMT
Subject: Radians vs. Degrees
Message-ID: <3D33016C.8030804@cox.net>

Hi All,

   I'm new to this NG so please bear with me :-) I'm writing an addon 
for the Quake2 editor named QuArK and could use some advice from the 
math/coding gurus out there.

   My problem is that I'm trying to create a torus (donut) and the C 
code I'm looking at uses DTOR to convert degrees to radians and I see no 
mention of it (DTOR) in Python. My question is whether I need this in 
Python or does Python automatically convert to radians during 
calculations? Also, do the FOR loops work the same as in C++ (e.g. 
FOR(x=0, x<360, x++))? If not, any suggestions on how to do this?

TIA

-Jef



From thomas_sg2000 at yahoo.com  Thu Jul  4 04:09:26 2002
From: thomas_sg2000 at yahoo.com (Tan Woon Kiong)
Date: 4 Jul 2002 01:09:26 -0700
Subject: Meta Line information in Python?
Message-ID: 

Hi,

Is there a way to specify meta line information in Python? 

For instance, in C language, this can be done by writing the statement
  #line  ""

For example, the following line in a file "el2h.py"
  #line 79 "el2h.nw"
means that the next statement comes from line 79 of the file
"el2h.nw".

Such meta line information is needed when the python code is generated
from other files and not coded directly by the programmer. I need this
facility as I use noweb, a literate programming tool, to write python
code. So the python code "el2h.py" is actually generated from the
literate source "el2h.nw". I need the python interpreter to report any
error message with line number pointing to the literate source
"el2h.nw" and not the generated code "el2h.py".

Regards,
- Woon Kiong


From fredrik at pythonware.com  Sun Jul 14 13:37:00 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sun, 14 Jul 2002 17:37:00 GMT
Subject: "Tickets" and XML-RPC authentication
References: 
Message-ID: <0FiY8.16023$p56.5181944@newsb.telia.net>

Magnus Lie Hetland wrote:

> If I have only one server/service, and that service takes care of its
> own authentication (i.e. no Kerberos-like stuff), is there any point
> to using a ticket/cookie-based system?
>
> In other words, is there any point to doing this:
>
>   ticket = server.authenticate('username', 'password')
>   server.performService(ticket, some, other, params)
>
> rather than
>
>   server.performService('username', 'password', some, other, params)
>
> ?

if you assume that a potential attacker sees everything you do
all the time, and don't care about performance and complexity,
no.

tickets can make both the client and the server simpler if you
want to associate lots of content with an XML-RPC "connection";
it allows you to distinguish between different clients using the same
username/password, it makes it easier to let "connections" expire,
etc.

(and Dave Winer would never think of doing things that way ;-)

and yes, if a potential attacker doesn't see everything, it may
even be a bit safer.  why keep sending the password over and
over again, when you don't have to?






From boud at valdyas.org  Mon Jul  1 06:44:59 2002
From: boud at valdyas.org (Boudewijn Rempt)
Date: Mon, 01 Jul 2002 12:44:59 +0200
Subject: QT->XML->Pmw->GUI
References: <3D203078.577C501E@gol.ge>
Message-ID: <3d2032f8$0$94904$e4fe514c@dreader3.news.xs4all.nl>

Giorgi Lekishvili wrote:

> Hi all!
> 
> As we surely know, an excellent GUI builder, QT designer primarily
> produces XML-based UI file.
> 
> My question is:
> 
> -Is there any available script in Python transforming the .ui file in
> Tk+Pmw based .py file? And if not, what do you think, would it be
> meaningful to make such a script? E.g., sort of uip compiler along with
> the uic compiler...
> 

It wouldn't be really useful, unless you can find an accurate replacement
for all the Qt widgets, and could find a way to translate the included
signal/slot connections to something Tkinter could use. And with the current 
version, you can even include Python code in the ui files, if you want to.

There's, of course, already pyuic, which generates Python code that uses 
PyQt...

-- 
Boudewijn Rempt | http://www.valdyas.org


From sschwarzer at sschwarzer.net  Mon Jul 22 13:23:13 2002
From: sschwarzer at sschwarzer.net (Stefan Schwarzer)
Date: Mon, 22 Jul 2002 19:23:13 +0200
Subject: Callable modules?
References: <7xznwk1hfy.fsf@ruckus.brouhaha.com>  <7xr8hwnu3s.fsf@ruckus.brouhaha.com>
Message-ID: <3D3C3F81.6090001@sschwarzer.net>

Hello Paul

Paul Rubin wrote:
> Just to not have to say "foo.foo()" or "from foo import foo".
> 
> If the main purpose of the module is to provide one function, I think
> it's cleaner to be able to import the module and call the function
> without special tricks.

I consider it cleaner to be explicit, and import the module and call its function. :-)

How many actual cases do you know of where a module has a single function?
Aren't they rare?

Stefan



From imcmeans at home.com  Tue Jul  9 05:56:36 2002
From: imcmeans at home.com (Ian McMeans)
Date: Tue, 09 Jul 2002 09:56:36 GMT
Subject: making zip with list comprehensions
Message-ID: 

I was idly trying to replicate zip's (the function) behavior using list
comprehensions, but I couldn't do it.

Can anyone? I came up with these, but they're ugly.

>>> [(x,y) for x in ['a','b','c'] for y in ['d','e','f'] if
['a','b','c'].index(x) == ['d','e','f'].index(y)]
[('a', 'd'), ('b', 'e'), ('c', 'f')]

This is ugly because it loops far too many times =)

>>> [ (['a','b','c'][x], ['d','e','f'][x]) for x in range(3)]
[('a', 'd'), ('b', 'e'), ('c', 'f')]

This isn't so bad. Does anyone have better suggestions?




From piet at cs.uu.nl  Mon Jul  8 09:28:17 2002
From: piet at cs.uu.nl (Piet van Oostrum)
Date: 08 Jul 2002 15:28:17 +0200
Subject: Unicode utf-8 doesn't do back-and-forth?
References:   
Message-ID: 

>>>>> Piet van Oostrum  (PvO) writes:

PvO> Your original input string u'\ud800\udb7f\udb80\U0010fc00\udfff' wasn't a
PvO> Unicode string, because the surrogates are not Unicode characters. Worse,
PvO> it wasn't even a valid UTF-16 encoding as it contains consecutive words
PvO> from the range 0xd800-0xdbff.

PvO> The encoding (or maybe even the Python parser) should have given an error
PvO> message. Instead, it produced an invalid UTF-8 byte sequence, which then
PvO> gives an error message at decoding. 

Well, I looked into the Unicode specs and it says that even if single
surrogates appear in a string, the UTF-8 encoding should generate a valid
UTF-8 byte sequence, which on encoding should give the same surrogate. So
I would say this is a bug in the UTF-8 encoding.
-- 
Piet van Oostrum 
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl


From zopestoller at thomas-guettler.de  Wed Jul 10 11:17:33 2002
From: zopestoller at thomas-guettler.de (Thomas Guettler)
Date: Wed, 10 Jul 2002 17:17:33 +0200
Subject: Hierarchical Editor
References: <3D2C3458.1090902@thomas-guettler.de> 
Message-ID: <3D2C500D.5000100@thomas-guettler.de>

John Hunter wrote:

>>>>>>"Thomas" == Thomas Guettler  writes:
>>>>>>
> 
>     Thomas> Hi!  Does someoone know an editor for editing hierarchical
>     Thomas> text data?
> 
>     Thomas> I need it for something like a todo-list.  One task can
>     Thomas> have several subtasks.
> 
> Emacs has a number of todo modes:
> 
>  http://www.emacswiki.org/cgi-bin/wiki.pl?ToDo


I love emacs for editing source code. But I need something that
can be used by everybody. The treeview should look like in the
windows explorer.

  thomas




From brueckd at tbye.com  Sat Jul  6 03:13:17 2002
From: brueckd at tbye.com (brueckd at tbye.com)
Date: Sat, 6 Jul 2002 00:13:17 -0700 (PDT)
Subject: sending a file through sockets
In-Reply-To: <3D25E196.5090207@nowhere.org>
Message-ID: 

On Fri, 5 Jul 2002, Bryan Olson wrote:

>  > Fine if the file is all you're sending, but it's like "who needs
>  > an on-off switch on this appliance, when you can just cut the
>  > power cord with a pair of insulated wire cutters."
> 
> No, cutting the cord will not do the same thing.  You only get the zero-
> byte successful read on graceful shutdown.

Actually, you get 0-byte successful read when you simply call close() too. 
Try it. Also note that the socket object destructor calls close(), so 
those sockets also get closed cleanly. Finally, I just tried killing the 
server process and the client side immediately came back with a 0-byte 
successful read.

> That is in fact how HTTP 0.9
> handles the end of response, and one of the options in HTTP 1.0 and FTP
> data connections.

...and is not small source of errors in HTTP agents, and is also why 
HTTP 1.1 discourages this method. It's especially annoying to deal with 
if you're writing web proxies and caches and the origin server is using 
closed sockets to mean end-of-transmission.

> 
> [...]
>  > | Did you test this?  The Python library uses the empty string for
>  > | INADDR_ANY, which is fine for bind(), but I don't think it's legal for
>  > | connect().
>  >
>  > So, did you test it?  I did!  According to my results, he's right,
>  > you're wrong.
> 
> Yes, the connect() fails on my system (Win 2000, Python 2.2).
                                         ^^^^^^^^
Ahh... there's the problem. ;-)    ------'
Works on Unices..

>  > We would?  I never have, and I don't notice the standard library
>  > modules doing that.  It might something to think about, but hardly
>  > the given it would be in C.
> 
> You just wing-it and hope for the best?  The Python "standard library
> modules" for network protocols are not so good.  The need for timeouts
> has come up many times in this group.

FWIW, latest CVS version of sockets has timeout support. Yay!

> Try your pull-the-plug idea on the Python network protocol libraries.
> Most TCP stacks will detect the dead connection in about two hours.

Again, a call to shutdown is not needed to get the 0-byte successful recv
call. The other side detects it immediately, for other problems you tend
to get a socket.error exception. What you _do_ need timeouts for is when
you are reading data from a buggy sender that puts your connection on a
shelf and then forgets about it, i.e. the connection is still open and
ready for use but the sender side simply fails to send anything.

-Dave





From logiplexsoftware at earthlink.net  Tue Jul  9 15:54:58 2002
From: logiplexsoftware at earthlink.net (Cliff Wells)
Date: Tue, 9 Jul 2002 12:54:58 -0700
Subject: openprojects python room is ruled by dangerous people
In-Reply-To: <3D2A1675.4B61F2BC@alcyone.com>
References: <3eeda89d.0207070906.1fa45916@posting.google.com>
	
	<3D29F478.4528312C@alcyone.com>
	
	<3D2A1675.4B61F2BC@alcyone.com>
Message-ID: <20020709125458.6264ff70.logiplexsoftware@earthlink.net>

On Mon, 08 Jul 2002 15:47:17 -0700
Erik Max Francis wrote:

> Glyph Lefkowitz wrote:
> 
> > I would like to respond to the ageist, patronizing tone of this
> > message, and
> > let the enduring and superior maturity of the poster (who was, if I
> > recall
> > correctly, banned under the pseudonym "xihr" for spreading exactly
> > this kind of
> > FUD) speak for itself:
> > 
> >     http://www.alcyone.com/xihr/
> 
> So what's that have to do with anything?  Are adults not allowed to have
> senses of humor?


That's it - you're outta here.
 
;)

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




From pbrown74 at hotmail.com  Tue Jul  2 11:48:50 2002
From: pbrown74 at hotmail.com (Paul Brown)
Date: Tue, 2 Jul 2002 16:48:50 +0100
Subject: JARs + Jython classes
Message-ID: 

hi

i'd like distribute my jython classes along with my compiled java classes,
in the same JAR

does anyone know the syntax for loading a jython class from a JAR, or even
if this is POSSIBLE?


i'm writing java code like this, to use a jython class:

    PythonInterpreter interp = new PythonInterpreter();

    Result res = new Result();

    interp.execfile("Constraint.py");

    interp.exec("c=Constraint()");

    interp.set("res", new Result());

    interp.exec("c.apply(res)");



as you can see, the Constraint is written in jython and i'd like to
instantiate it and call the apply(r) function,

where 'r' is a java object.

i'd like to put Constaint.py in the same JAR as Result.class etc.

thanks

paul







From philippe.gendreau at savoirfairelinux.com  Wed Jul 24 13:13:07 2002
From: philippe.gendreau at savoirfairelinux.com (Philippe Gendreau)
Date: Wed, 24 Jul 2002 13:13:07 -0400
Subject: syntax questions
In-Reply-To: ; from cliechti@gmx.net on Wed, Jul 24, 2002 at 06:50:07PM +0200
References:  
Message-ID: <20020724131307.A23105@xmailer.ods.org>

* Chris Liechti  [2002-07-24 18:50]:
> you want to call "append" on the variable "self.theme" which seems to be a 
> list, therefore the outher parantheses:
> self.theme.append(...)
> 
> you want to add a tuple to the list:
> (...,)
> 
> a tuple with just one argument needs a coma at the end, otherwise it would 
> be an arithmetic expression ans no tupple.

The imbrication of those structures can sometime be confusing...
Thanks for clearing that out.

> and finaly you call a function with the name "_":
> _(dir)
> that is sometimes used to localize names i.e. the "_" function translates 
> the given string to the local language. to be sure what it does you have to 
> search for the implementation in you current sourcecode.

Ah! this is a function name?
As you say, I will have to look
into the code to see what it does...

> note that "dir" is somewhat a bad name for that variable because
> a) there is a builtin function that name that you hide
> b) its not a directory name but a filename without path in the above case

Note taken.
I know about the dir() function,  but I'm surprised that my list object
hides a function object (even if they have the same name). 
Is that how python treats names all the time? Does it mean you can't
have a class, def and variable of the same name?

> in the intercative prompt "_" is bound to the last result so that you can 
> do further calculations:
> >>> 1+1
> 2
> >>> _*3
> 6

Nice, this is probably why It seemed to be used for many purpose.
if I understand well, this behavior is just in the interactive mode.
If I use '_' in a module it is just an identifier.

Thank you.
--
Philippe Gendreau



From gerhard.haering at gmx.de  Mon Jul  8 04:54:46 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=)
Date: Mon, 8 Jul 2002 10:54:46 +0200
Subject: pythoncom from jython
In-Reply-To: <46585325.0207080040.1ac2fffd@posting.google.com>
References: <46585325.0207080040.1ac2fffd@posting.google.com>
Message-ID: <20020708085446.GB8564@lilith.my-fqdn.de>

* Daniel Pi?ol Laserna  [2002-07-08 01:40 -0700]:
> Is it possible to use pythoncom from jython?

No.

> Ideally, I'd like to build a com component in python (this works with
> win32 extensions), and from there make calls to java classes (this
> need jython).

Do you really need to combine COM and Java? Use a COM <-> Java bridge,
then. Googling with the keywords "java com bridge" finds you some
alternatives.
 
Gerhard
-- 
This sig powered by Python!
Au?entemperatur in M?nchen: 22.8 ?C      Wind: 2.1 m/s




From kristian at tycoons.de  Wed Jul  3 11:54:21 2002
From: kristian at tycoons.de (Kristian Sons)
Date: Wed, 3 Jul 2002 17:54:21 +0200
Subject: Who is the user??
Message-ID: 

Hi,

is there a possibility to find out, wich user startet the python-script??

Thanks a lot,
  Kristian




From gmfawcett at operamail.com  Fri Jul  5 14:15:19 2002
From: gmfawcett at operamail.com (Graham Fawcett)
Date: 5 Jul 2002 11:15:19 -0700
Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32
References: <3d799735.0207041113.3a830bdf@posting.google.com> <3D24FF3A.4010205@something.invalid>
Message-ID: <3d799735.0207051015.2f53b268@posting.google.com>

Greg Ewing  wrote in message news:<3D24FF3A.4010205 at something.invalid>...
> Graham Fawcett wrote:
> 
> Thanks for pointing this problem out. I'll see if I can
> do something about this in a future release.

My pleasure, Greg.

I thought it might be helpful to summarize the installation of Pyrex
on Win32 for those who are interested in using Pyrex, but are
discouraged by the setup that may be required. I've put up some notes
at

  http://cfl-x.uwindsor.ca/graham/pyrex/

that should make it a snap.

Thanks again for this great product!

-- Graham


From james.kew at btinternet.com  Sun Jul 21 19:23:57 2002
From: james.kew at btinternet.com (James Kew)
Date: Mon, 22 Jul 2002 00:23:57 +0100
Subject: XML with Python - supposed to be simple? ;)
References:  
Message-ID: 

"Martin v. Loewis"  wrote in message
news:m3it38lsxm.fsf at mira.informatik.hu-berlin.de...
> "Vladimir Cherepanov"  writes:
>
> > As a complete newbie to both XML and Python, I've been trying to
> > create (any!) XML document using DOM API in PyXML package. Very
> > simple task isn't it?

Yes. Well documented, though, it isn't. But the DOM interfaces and minidom
are documented to reasonable level in the Library Reference; much of the
rest of PyXML is sparsely documented, but it does install some reasonable
example code.

> If you insist on using the DOM, I recommend that you read the DOM spec
> first (from www.w3.org). You'll then learn that you can create
> Document instances by invoking createDocument on the
> DOMImplementation. For minidom, you get the DOM implementation by
> calling xml.dom.minidom.getDOMImplementation().

Or read the minidom documentation:
http://www.python.org/doc/current/lib/module-xml.dom.minidom.html describes
how to create a document node and populate it with children.

Once you've grokked the DOM interfaces -- xml.dom.Node as the base interface
for all nodes, specialised to Document, Element etc for specific node
types -- and that you create "floating" children by calling the appropriate
create method on the document node _then_ put them into the tree by calling
appendChild on their parent node, building DOMs does start becoming easier.

> > And what about serializing?

If you're using xml.dom.minidom: writexml(file) on the document node to
write it to an XML file; xml.dom.minidom.parse(filename_or_file) to read an
XML file and return a document node.

--
James Kew
james.kew at btinternet.com





From tim.one at comcast.net  Thu Jul 25 22:01:29 2002
From: tim.one at comcast.net (Tim Peters)
Date: Thu, 25 Jul 2002 22:01:29 -0400
Subject: how to count lines in a file ?
In-Reply-To: <200207260746.00524.rjones@ekit-inc.com>
Message-ID: 

[Richard Jones]
> I think the major problem that we're running into here is that
> before there was GC, the refcounting-based cleanup of objects was clear,
> straight-forward and reliable. Now it's not clear when objects are
> cleared up.

Then you don't understand CPython's flavor of gc:  refcounting didn't go
away in CPython.  Anything that got cleaned up by magic in Python 1.0 still
gets cleaned up by magic, and at exactly the same time it used to get
cleaned up.  In addition, many kinds of memory leaks (involving cycles) in
older CPython implementations have gone away.  CPython's cyclic gc is solely
concerned with unreachable objects in cycles; all such objects leaked
forever before CPython grew cyclic gc.  Everything else is still cleaned up
by refcounting in CPython.

> That's a fairly major problem for some of us old-timers

Yet it shouldn't be "a problem" at all.  Nothing has changed except that you
have fewer memory leaks.

> (and, quite possibly, a lot of newbies) to come to terms with. I hadn't
> realised that GC threw such a big, ugly spanner in the works :(

Did you catch that the example was run under Jython?  Jython never used
refcounting.




From pete at shinners.org  Thu Jul 25 11:35:39 2002
From: pete at shinners.org (Pete Shinners)
Date: Thu, 25 Jul 2002 15:35:39 GMT
Subject: Refer to function name (newbie ques)
References: <805bee23.0207250649.5a4d89d0@posting.google.com>
Message-ID: <3D401AF0.8090003@shinners.org>

chris ciotti wrote:
> Is there a way to get the name of the running function?  In a  script
> I'm doing some error checking and I want to be able to name the
> function that screws up.  Something like:

one problem is if the function has multiple names...

     def foo():
         print 'In Foo'
     bar = foo
     bar()

of course, this if very uncommon. i think the only way to get at this info 
would be to dig into a stack trace. this may end up being more helpful 
anyways, because you can also print out who has called your function.


     import traceback
     def foo():
         stack = traceback.extract_stack()
         print 'Inside Function:', stack[-1][2]
         print ' Called By:', stack[-2][2], ' line:', stack[-2][1]


the traceback module was added sometime around python-2.1 (i think?) so 
this won't work with older pythons. docs are here,
http://www.python.org/doc/current/lib/module-traceback.html
http://www.python.org/doc/current/lib/traceback-example.html




From jdhunter at nitace.bsd.uchicago.edu  Wed Jul 10 10:39:25 2002
From: jdhunter at nitace.bsd.uchicago.edu (John Hunter)
Date: Wed, 10 Jul 2002 09:39:25 -0500
Subject: Hierarchical Editor
References: <3D2C3458.1090902@thomas-guettler.de>
Message-ID: 

>>>>> "Thomas" == Thomas Guettler  writes:

    Thomas> Hi!  Does someoone know an editor for editing hierarchical
    Thomas> text data?

    Thomas> I need it for something like a todo-list.  One task can
    Thomas> have several subtasks.

Emacs has a number of todo modes:

 http://www.emacswiki.org/cgi-bin/wiki.pl?ToDo

John Hunter


From gmfawcett at operamail.com  Wed Jul 10 16:34:34 2002
From: gmfawcett at operamail.com (Graham Fawcett)
Date: 10 Jul 2002 13:34:34 -0700
Subject: Pyrex and Distuils: an enhanced build_ext command
References: <3D24FF3A.4010205@something.invalid>   <3d799735.0207091153.258cc430@posting.google.com> <3d799735.0207100216.4eb8a9cd@posting.google.com> 
Message-ID: <3d799735.0207101234.7ca3288d@posting.google.com>

"Thomas Heller"  wrote in message news:...
> "Graham Fawcett"  wrote in message news:3d799735.0207100216.4eb8a9cd at posting.google.com...
> >                     # compiling with mingw32 gets an "initializer not
> > a constant" error
> >                     #
> > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq03.024.htp
> >                     # doesn't appear to happen with MSVC
> >                     # so if we are compiling with mingw32, massage the
> > Pyrex-generated
> >                     # C files to compile properly
> >
>
> Isn't this problem (initializer not a constant) solved by compiling
> the file in C++ mode (with .cpp extension)?
>
> Thomas

Yes -- at first I couldn't get c++ compilation to work, so I tried the
other approach suggested in the FAQ.

I just spent some time trying again, and I think I've got the c++
approach working. I still need to massage the Pyrex-generated C files,
but the code is much cleaner.

I also saw your suggestions re: adding command classes using the
canoncial approach, and the extension point at swig_sources(), and
have simplified my code accordingly.

Here are the revised files:

#######################################
#Pyrex.Distutils.__init__.py

from build_ext import build_ext

#######################################
#Pyrex.Distutils.build_ext.py
#
# Subclasses disutils.command.build_ext,
# replacing it with a Pyrex version that compiles pyx->c
# before calling the original build_ext command.
# July 2002, Graham Fawcett
# Pyrex is (c) Greg Ewing.

import distutils.command.build_ext
import Pyrex.Compiler.Main
from Pyrex.Compiler.Errors import PyrexError
from distutils.dep_util import newer
import os
import sys

class build_ext (distutils.command.build_ext.build_ext):

    description = "compile Pyrex scripts, then build C/C++ extensions
(compile/link to build directory)"

    def finalize_options (self):
        distutils.command.build_ext.build_ext.finalize_options(self)

        # compiling with mingw32 gets an "initializer not a constant"
error
        # doesn't appear to happen with MSVC!
        # so if we are compiling with mingw32,
        # switch to C++ mode, to avoid the problem
        if self.compiler == 'mingw32':
            self.swig_cpp = 1

    def swig_sources (self, sources):
        if not self.extensions:
            return

        # collect the names of the source (.pyx) files
        pyx_sources = []
        pyx_sources = [source for source in sources if
source.endswith('.pyx')]

        extension = self.swig_cpp and '.cpp' or '.c'
        for pyx in pyx_sources:
            # should I raise an exception if it doesn't exist?
            if os.path.exists(pyx):
                source = pyx
                target = source.replace('.pyx', extension)
                if newer(source, target) or self.force:
                    self.pyrex_compile(source)

                    if self.swig_cpp:
                        # rename .c to .cpp (Pyrex always builds .c
...)
                        if os.path.exists(target):
                            os.unlink(target)
                        os.rename(source.replace('.pyx', '.c'),
target)
                        # massage the cpp file
                        self.c_to_cpp(target)

        return [src.replace('.pyx', extension) for src in pyx_sources]

    def pyrex_compile(self, source):
        try:
            Pyrex.Compiler.Main.compile(source, c_only=1,
use_listing_file=0)
        except PyrexError, e:
            print e
            sys.exit(1)

    def c_to_cpp(self, filename):
        """touch up the Pyrex generated c/cpp files to meet
mingw32/distutils requirements."""
        f = open(filename, 'r')
        lines = [line for line in f.readlines() if not
line.startswith('staticforward PyTypeObject __pyx_type_')]
        f.close()
        f = open(filename, 'w')
        lines.insert(1, 'extern "C" {\n')
        lines.append('}\n')
        f.write(''.join(lines))
        f.close()

#######################################
# a sample setup.py
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext

setup(name='foo',
    ext_modules=[ Extension("foo", ["foo.pyx"]) ],
    cmdclass = {'build_ext': build_ext}
)

#######################################

Tested on Win32, msvc and mingw32.

I'm happy so far -- the revision is shorter, cleaner and more
explicit.

Comments are welcome!

Cheers,

-- Graham


From barry at zope.com  Tue Jul 30 11:36:13 2002
From: barry at zope.com (Barry A. Warsaw)
Date: Tue, 30 Jul 2002 11:36:13 -0400
Subject: PEP 1, PEP Purpose and Guidelines
References: <15685.35726.678832.241665@anthem.wooz.org>
	
Message-ID: <15686.45677.421287.717866@anthem.wooz.org>

>>>>> "FP" == Fran?ois Pinard  writes:

    >> It has been a while since I posted a copy of PEP 1 to the
    >> mailing lists and newsgroups.

    FP> Thanks for giving me this opportunity.  There is a tiny detail
    FP> that bothers me:

    >> The format of the author entry should be address at dom.ain
    >> (Random J. User) if the email address is included, and just
    >> Random J. User if the address is not given.

    FP> This makes me jump fifteen years behind (or so, I do not
    FP> remember times), at the time of the great push so the Internet
    FP> prefers:

    FP>        Random J. User 
FP> It is more reasonable to always give the real name, optionally FP> followed by an email, that to consider that the real name is a FP> mere comment for the email address. This is a good point. Originally we thought it was more important to be able to contact the author, but there are quite a few reasons to revise this intention. As pointed out, email addresses change. Also, experience has shown that most of the discussions about PEPs are conducted on the public forums (mailing lists / newsgroups), so that's a fine way to contact the people working on the PEP. And of course, we allow the PEP authors to obfuscate or omit their email addresses altogether. FP> Could the PEP be reformulated, at least, for leaving the FP> choice opened? I'd rather have one preferred way of writing the header, so I'm going to change PEP 1 to mandate "Random J. User
" with the email address optional. However, I'm going to let the old style remain for historical purposes since I don't think it's worth changing the existing PEPs. Thanks, -Barry From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 20:06:04 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 17:06:04 -0700 Subject: performance problem in python 2.2 References: <7xn0sedslz.fsf@ruckus.brouhaha.com> <7x8z3y12uf.fsf@ruckus.brouhaha.com> Message-ID: <7xheimyqz7.fsf@ruckus.brouhaha.com> Fernando Perez writes: > I'd actually flip them in order of preference: > > 1. be smart. > 2. when you can't, at least be efficient. 1. When in doubt, use brute force. 2. If brute force doesn't work, you're not using enough. ;-) From tdelaney at avaya.com Mon Jul 22 02:34:51 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 22 Jul 2002 16:34:51 +1000 Subject: A better self Message-ID: > From: Alex Martelli [mailto:aleax at aleax.it] > > Delaney, Timothy wrote: > > >> From: Alex Martelli [mailto:aleax at aleax.it] > >> > >> The point is that SelferMeta.__new__ gets to look at all of > >> class Myself's dictionary *and tamper with it as needed* before > >> delegating the rest to class type. Specifically, it would get > ... > > Wouldn't work in Jython ... (when Jython gets to 2.2 ...). > > Or more precisely: the bytecode manipulations needed will be specific > to the underlying virtual machine. I.e., unless a VM is designed in > really crazy ways, it will probably be possible to use exactly the > same technique (metaclass computing what bytecode is needed to achieve > the desired results and substituting it in place of the bytecode as > given), but the details of the transformations will change. May I suggest that I was awed by the hack, and felt that my only possible contribution was to point out the unfeasibility of such a method in case anyone actually wanted to *do* something this perverse? I mean - it was a truly evil suggestion, well and truly worthy of the Martellibot :) Tim Delaney From skip at pobox.com Wed Jul 24 15:34:56 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Jul 2002 14:34:56 -0500 Subject: Strange Queue error In-Reply-To: <4378fa6f.0207241120.1876187b@posting.google.com> References: <4378fa6f.0207241120.1876187b@posting.google.com> Message-ID: <15679.352.230268.616270@12-248-11-90.client.attbi.com> Marc> qlist.put( (sleep, 5) ) Marc> TypeError: unbound method put() must be called with Queue instance as Sounds like you set the qlist variable like so: qlist = Queue.Queue instead of qlist = Queue.Queue() Note the difference: >>> import Queue >>> qlist = Queue.Queue() >>> import time >>> qlist.put((time.sleep, 5)) >>> qlist = Queue.Queue >>> qlist.put((time.sleep, 5)) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method put() must be called with Queue instance as first argument (got tuple instance instead) -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From b.maryniuk at forbis.lt Thu Jul 11 06:28:23 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 12:28:23 +0200 Subject: Python in the enterprise: Pros and cons In-Reply-To: References: Message-ID: <200207111228.23462.b.maryniuk@forbis.lt> On Thursday 11 July 2002 11:47, Tim Peters wrote: > > What the buzzword "the enterprise" is? > It's an especially annoying American buzzword for "business use, as opposed > to consumer, research, or educational use". Ah, Bill Gates buzzword again. Excuse me... Therefore according to this explanation, seems that LISP or Scheme are enterprise too, except of "high-phrases" AKA "...our very educated managers...", "...our high business...", "...our success in the market..." and so on. -- Sincerely yours, Bogdan M. Maryniuck We are using Linux daily to UP our productivity - so UP yours! (Adapted from Pat Paulsen by Joe Sloan) From Bill.Scherer at VerizonWireless.com Mon Jul 1 09:08:13 2002 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Mon, 1 Jul 2002 09:08:13 -0400 (EDT) Subject: Europython pictures In-Reply-To: <9ZUT8.21128$l6.4303892@newsfep2-win.server.ntli.net> Message-ID: On Mon, 1 Jul 2002, Duncan Grisby wrote: > I took lots of pictures at the Europython conference last week. If > you're interested in seeing the action, take a look at > > http://www.grisby.org/Photos/085/ > > Cheers, > > Duncan. Nice photos. Can you add some captions so we know who we are looking at? Thanks! -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From akakakhel at attbi.com Thu Jul 4 18:14:03 2002 From: akakakhel at attbi.com (Ali K) Date: Thu, 04 Jul 2002 22:14:03 GMT Subject: Making computer into server for free Message-ID: I would like to know how to make my computer into a web site host with which I can use python for making my website. Please Reply. Thank You. From mats at laplaza.nospam.org Mon Jul 22 13:32:02 2002 From: mats at laplaza.nospam.org (Mats Wichmann) Date: Mon, 22 Jul 2002 17:32:02 GMT Subject: Python very slow on the Sharp Zaurus - any idea why? References: Message-ID: <3d3c40e9.16845662@news.laplaza.org> :Note that the Arm doesn't have any floating point unit, and that the :floating point operations are all emulated. But I never use any floating :point arithmetic in my game or in my Python scripts. Note also that I :had to cross-compile the Python library myself from Python 2.2 sources, :as there is no lightweight Python distribution for the Arm. But I don't :get what's wrong. Does Python use floating point arithmetic internally? :Is there something else I missed? Did you try Riverbank Computing's port of Python to the Zaurus? I don't know that it's going to help your speed problems, that sounds like it may depend on something you're doing, but their port is an effort at a trimmed-down distribution that makes sense for that platform. Mats Wichmann From a_salnikov at yahoo.com Mon Jul 22 19:02:45 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Mon, 22 Jul 2002 16:02:45 -0700 Subject: ssh and Python References: Message-ID: "Erno Kuusela" wrote in message news:kuofd03q0m.fsf at lasipalatsi.fi... > In article , "Bo > M. Maryniuck" writes: > > | On Monday 22 July 2002 13:12, Erno Kuusela wrote: > || use a rsa key with ssh-agent (or without passphrase if you need > || it to run unattended). > > | But sometimes you just need to pass a password. > > hmm? you can always use a rsa key, unless the administrator > has disabled rsa keys (which would be silly since hardcoding > passwords is less safe). > I know one example when one has to use plain password in ssh. This is when you log on onto AFS-enabled host from non-afs machine (or using ssh without AFS support, which is standard on Windows). In this case using RSA you'll not get your AFS token and then you'll need to execute 'klog' manually an type in your password anyway. Cheers, Andy. From siegfried.gonzi at kfunigraz.ac.at Sun Jul 28 05:09:30 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sun, 28 Jul 2002 11:09:30 +0200 Subject: performance problem in python 2.2 References: Message-ID: <3D43B4CA.1020209@kfunigraz.ac.at> Jeff Davis wrote: > I wrote a small python program to help me solve a math problem. When I > tried to run it with large values, it ate all my RAM and I eventually had > to kill it. I tried writing the same thing in C and it used almost no RAM > (and had an upper limit) and finished much faster. > > Then I was talking to someone who suggested that I try perl. I have the > exact same algorithm in perl, and it doesn't eat my RAM, and executes much > more quickly (same order of magnitude as the c program). It seems almost > as if there's a memory leak in one of python's simple math operations, > because it is so much worse than the other ones I tried. If you need a good compiler but want not give up the convenience of a dynamically typed language you should take a look at Bigloo. Bigloo is a Scheme compiler which produces fast executables: == n = 1.0 p = 2.0**64 c = 1000000.0 for i in xrange(1,c+1): n = (n * (p - 1)) / p print (1 - n) == time python bench_py.py real 0m17.214s user 0m17.190s sys 0m0.000s == (module bench) (define (sum-silly1 c) (let* ((n 1.0) (p (expt 2.0 64.0))) (do ((i 1 (+ i 1))) ((= i (+ i 1))) (set! n (/ (* n (- p i)) p))) (print (- 1 n)))) (define (sum-silly2 c) (let* ((n 1.0) (p (expt 2.0 64.0))) (do ((i 1 (+fx i 1))) ((=fx i (+fx (flonum->fixnum c) 1))) (set! n (/fl (*fl n (-fl p (fixnum->flonum i))) p))) (print (- 1 n)))) (sum-silly1 1000000.0) ;;(sum-silly2 1000000.0) == bigloo -Obench bench.scm time ./a.out real 0m0.720s user 0m0.690s sys 0m0.030s or the second version with native Bigloo floating point operations: bigloo -Obench bench.scm time ./a.out real 0m0.073s user 0m0.060s sys 0m0.010se == #include #include int main() { long i,c; double n = 1.0; double p = 1.844674407370955161e+19; c = 1000000.0 for (i=1;i<=c;++i) { n = (n * (p - i)) / p; } printf("%.16e\n",(1-n)); return 0; } == gcc -O3 bench_c.c time ./a.out real 0m0.017s user 0m0.010s sys 0m0.000s Bigloo is not only good at microbenchmarks it performs well on arrays and lists too. I am about to release the DISLIN binding to Bigloo in a few weeks. S. Gonzi From aleax at aleax.it Fri Jul 5 16:36:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 20:36:36 GMT Subject: how to disable maximize button? References: Message-ID: jubafre at zipmail.com.br wrote: > how i can disable de maximise button in tkinter, i don?t want the user > modific the size of the window, i want a real size of window, how can i do > it??? You can remove all decorations: import Tkinter root = Tkinter.Tk() root.overrideredirect(1) Apart from this, you may choose to fix the size: import Tkinter root = Tkinter.Tk() root.resizable(0,0) I know of no way to affect the maximize button ONLY, without also affecting other ways to resize the window, but then from your post's text I don't see why you should ONLY want to affect said button. Alex From mcfletch at rogers.com Thu Jul 11 16:23:59 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 11 Jul 2002 16:23:59 -0400 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) References: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: <3D2DE95F.8080908@rogers.com> Hmm, strangely, I'd always thought the "sparse is better than dense" line was refering to ideas of sparse versus dense data structures and/or programs. For instance, if we have an 11-item sequence where we want to record which items are "important", we see two possibilities: filterSet = [0,0,0,1,0,0,0,0,1,0,0,0] and filterSet = {3:1, 8:1} and would choose the "sparse" matrix (the dict) instead of the "dense" one. In a more general sense, record what is important explicitly, and where it is relevant, while not recording that which is unimportant to the matter at hand. Or even more generally, make your intentions clear by coding just what you mean, not everything that could possibly be. See the use of exceptions, which encourage you to code the "positive image" in a particular function, and allow a higher-level of code to deal with the outlier cases (the 0's in the array, which we don't really have anything to say about). But, of course, I'm notoriously bad at channeling Tim, so the whitespace thing is probably it :) , Mike > Miki Tebeka wrote: > >>Although it's in the Humor section I take the Python Zen >>(http://www.python.org/doc/Humor.html#zen) quite seriously. >>However I can understand what does “Sparse is better than >>dense” means. ... From emile at fenx.com Thu Jul 4 09:16:33 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 13:16:33 GMT Subject: newbie question on PATH vaiable and running python on win xp References: Message-ID: John Boik > I would like to be able to run python from the command line from any > directory. Right now I can only run it from the Python22 directory. I > tried putting the Python22 directory in the windows PATH variable, but still > python only would run if I was in the Python22 directory. I also tried > putting Python22\python.exe in the PATH variable, but that did not help > either. Any solutions to this? Don't put the exe in the path: C:\>echo %PATH% "F:\Python21\";F:\Perl\bin\;C:\WINNT\system32;C:\WINNT C:\>PATH="" C:\>python 'python' is not recognized as an internal or external command, operable program or batch file. -- Emile van Sebille emile at fenx.com --------- From sholden at holdenweb.com Sat Jul 6 12:28:23 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 6 Jul 2002 12:28:23 -0400 Subject: Client sockets without os.fork() References: Message-ID: <_TEV8.111373$B%3.75011@atlpnn01.usenetserver.com> "Larry" wrote in message news:MDqV8.426072$cQ3.29617 at sccrnsc01... > When a client connects in unix/linux, I could simply use the os.fork() to > create a nice new process to deal with the newly requested session. > > I now have a need to do this in windows. Can anyone relay a fairly easy way > to put the newly created socket into it's own thread so that it can go about > doing it's business while the orginal daemon can sit and listen for new > connections? > Take a look a the standard library's CGIHTTPServer, which contains code to handle the OS-dependent bits of starting a subsidiary process and reading its output. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From a-steinhoff at web.de Tue Jul 2 05:59:04 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 2 Jul 2002 02:59:04 -0700 Subject: Pythoniac: Thoughts on a hardware Python processor References: Message-ID: Christopher.Saunter at durham.ac.uk (Christopher Saunter) wrote in message news:... > Dear All, > > I have seen the occasional post about creating a specific hardware 'Python > Processor', that could then be built and used in programmable logic or the > like (Valves, relays, core memory - Pythoniac ;-) - in other words, create > a processor that executes Python bytecode directly. What about an implementation of the byte code processing in micro code for a Transmeta processor? Is it possible ?? Armin just-a-wild-idee :) > There would be > various different reasons for doing this (the 'neat' factor etc...) > > Replies to these questions have been a bit scant, so I though I would > chuck something in. > > Due to Lazy Typing Syndrome I've used a couple of abbreviations: > PVM - Python Virtual Machine / Python Interpreter > PBC - Python Byte Code > > This has been done for Java, for example > http://www.xilinx.com/prs_rls/0134lavacore.htm > and I have seen a partially complete open source core out there somewhere, > but I can't find it right now. > > I have recently been looking at doing this for Python, and it seems like a > rather odd task. From playing with the 'dis' module and reading some > docs, it seems that Python Interpreter (PVM), which would be translated > into a processor, has these properties: > > > o Operates on sequential bytecode with branching / jump > instructions. > o Entirely stack based (no concept of registers / memory) > > So far, so good - a processor could be built to do these functions of the > interpreter. However, we go on.... > > o Rather than operating on 8/16/xxx bit words, as most hardware > processors do, the PVM processes objects (via pointers on the stack), > which are treated in a 'black box' fashion - i.e. they have add, subtract, > compare etc. methods that are called by the PVM, and that return a result. > These methods of objects may not actually be coded for in Python, but in > the machine language (x86, alpha etc, derived from C etc.) of the > underlying processor. > > Here, the PVM is very different from a 'typical' hardware processor, as > the later has a strictly limited number of data types, which it is able to > manipulate, whereas Python has many, built out of the basic types, and > although some may be coded in Python, they themselves are built on top of > C code (or Fortran etc.) that are all translated to native (x86 etc) > bytecode outside of Python. The upshot of this is that the PVM is > unaware, in the majority of cases, of what actually needs to be done to > manipulate objects, it just makes calls to non Python code. > > So, how to go about dealing with this in a Python processor? > > a) Create a stack based Python bytecode processor to replace the PVM, and > have this interact with another processor (x86 etc.) which stores the > objects and executes their methods. Ick. > > b) Create a stack based bytecode processor that interfaces to custom > hardware processors for each Python object. Ick. > > Neither of these are particularly nice (or for b, workable) solutions. > The one I prefer is the following: > > c) Create a processor that understands Python bytecode, using a stack for > the object pointers. However, the processor would execute a sort of > superset of PBC, call it P+. This would be fully compatible with Python, > but would include several built in types (32bit integers, 8bit integers > for strings etc,) and would have access to a memory space. The basic > Python types(1) would then be implemented using P+, and stored in the > memory available to P+. > > c Should present a processor that executes Python bytecode, manipulating > the Python stack. Then, when a method of an object is called, the > appropriate piece of P+ is called, executed by the same processor, and it > modifies the data structures of the objects, and the Python stack as > necessary, before returning seamlessly to the PBC execution. > > Python extensions would then be directly executable on this processor, if > coded in Python. If they are coded in C or some other language, a C->P+ > compiler would be needed... > > The level of abstraction caused by having to chase down function and > object pointers will be higher than for the execution of code on a more > conventional hardware processor, but this is also the case for executing > PBC with an interpreter. > > One advanced idea (not really thought about it yet!) is to store the > Python stack in main memory, but to store the top x (e.g. 32) items of the > stack in a register file to allow bytecode parallelism. I gather that > IA-64 may do something sort of similar. > > --- > > So, Pythoniac: a hardware (well, FPGA(2)...) processor that directly > executes Python bytecode. What do people think about the idea? Is it > really feasible? I have doubts it would be particularly quick (in the > same way I have my doubts about anti-gravity generators... ;-), but it > should be fun! > > I would like to try and implement this, initially in a simulation > environment, then in a real FPGA, with hooks back to a PC allowing the > loading, execution, single step execution and monitoring etc of PBC. > Ideally I would like to reach a state where an interactive interpreter > runs over a serial port... > > So, anyone else interested in this? Comments, suggestions, gaping holes > in my understanding of things as outlined above etc are welcome! > > Regards, > Chris Saunter > > > > (1) Now we have increasing type<->object integration, should we refer to > numbers, strings, lists etc as types or objects? > > (2) FPGA - Field Programmable Gate Array - a chip that consists of a > 'logic fabric' than can be configured to produce arbitrary circuit > designs. If this sounds new to you, try www.fpgacpu.org From zopestoller at thomas-guettler.de Tue Jul 9 04:05:28 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 09 Jul 2002 10:05:28 +0200 Subject: Table Widget (without Installation) Message-ID: <3D2A9948.5090304@thomas-guettler.de> Hi! I am searching for a table widget to use with python. Is it still true that tkinter has none? I need it for an application on win32 which should not be installed. All libraries will be in one directory. pyFox, pygtk, wxpython are options. pyQt not since it is not allowed for commercial applications. Which could be the easiest? thomas From wpeterson1 at socal.rr.com Thu Jul 18 13:26:51 2002 From: wpeterson1 at socal.rr.com (William Peterson) Date: 18 Jul 2002 10:26:51 -0700 Subject: Sharp Zaurus References: <1026919964.826307@irys.nyx.net> Message-ID: <3d0678bb.0207180926.4893aa31@posting.google.com> sarayu balu wrote in message news:<1026919964.826307 at irys.nyx.net>... > Hi, > Is there any Python, more appropriately Jython, for this PDA ? > Is Jython Open Source ? > Thanks, > SB Python has been ported, as another poster says. For Jython, look at http://www.jython.org/platform.html At the bottom of the page, while discussing Kaffe, it says that Jython requires a full JVM and will have problems with a VM that only implements the PersonalJava subset. I believe this is what you have on the Zaurus, so it's questionable whether Jython will work there. Bill From peter at engcorp.com Tue Jul 23 22:14:23 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Jul 2002 22:14:23 -0400 Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3AEDD6.78B39D70@engcorp.com> <3D3B4F80.B0D6BE07@engcorp.com> Message-ID: <3D3E0D7F.D13E5145@engcorp.com> Aahz wrote: > > In article <3D3B4F80.B0D6BE07 at engcorp.com>, > Peter Hansen wrote: > >I'm trying to follow Aahz' advice and avoid "reference" in favour of > >"binding" etc, but I guess I carried it too far! :) > > Your problem wasn't in your use of "binding", but in your use of > "name; I use "target" to refer to the general case of thingy that can > contain a binding, of which names are a subset. "Names" are words > attached to a namespace (i.e. function local, module global, builtin, or > object attribute). Another target is an index/key for container > objects. Hmmm... "target" sounds like the wrong direction. Shouldn't it be a "source" for the binding? Or maybe another term which doesn't have what seems to me the potential for confusion would be better. -Peter From peter at engcorp.com Mon Jul 15 19:33:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Jul 2002 19:33:21 -0400 Subject: isA function? References: Message-ID: <3D335BC1.29939ECA@engcorp.com> "Delaney, Timothy" wrote: > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > have the right signature is inadequate in this circumstance, though > > it may be acceptable for you when doing traditional unit testing, > > writing tests after the fact. > > Lovely indirect insult there Peter. Incorrect (beyond the fact that in Java, > which my current project uses, you need a minimal amount of code written > before the unit test can be completely written) but lovely nonetheless. Incorrect? Okay, if you say the signature is inadequate *even* in traditional unit testing, I'll take your word for it (as I'd never done much unit testing until learning about test-driven development). As for indirect insult -- I don't understand why you think that, unless you find "traditional" insulting -- but in any case I didn't mean it to be insulting, indirect or otherwise. Apparently my writing style frequently causes people to think that (apart from the times when I *do* intend to insult), for which I apologize. I'm trying to improve. > Agreed - in the factory case, a single test of each input -> output is > necessary (one case where a type check is a good idea - immediately > knowledge that you haven't got what you expect). Okay, so we both agree on that. I was under the impression you were adamantly against such a test in all cases, even after I first presented that example two posts back. I must have misunderstood again, and once more I apologize. > Apart from that one location though, I stick by not doing typechecks in unit > tests - objects should pass behaviour tests. It's actually a lot easier to > write unit tests that do this, rather than checking for type - it means that > your class heirarchy (if any) can change as required and your unit tests > still ensure that the behaviour is correct. Agreed! I don't believe I've ever used a type test in any of my unit tests so far, and certainly not much in real code (or perhaps at all). I doubt either Roy or I would defend such a practice in most cases, so we seem to all be in agreement after all. -Peter From grante at visi.com Wed Jul 3 14:16:43 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Jul 2002 18:16:43 GMT Subject: win32 setcommtimeouts parameter? Message-ID: The win32 extension SetCommTimeouts accepts a tuple of five values for the timeout parameters. Can anybody lend me a clue as to the order of those five values? -- Grant Edwards grante Yow! I invented skydiving at in 1989! visi.com From aleax at aleax.it Tue Jul 9 06:38:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 10:38:10 GMT Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: Tim Hammerquist wrote: ...[snipped lots of intense agreements]... > Trusting a language structure to protect against malicious or simply > incompetent users is bad design, and is likely to inhibit flexibility. Not too sure I agree fully with THIS point. The language structure PLUS a controlled runtime environment, a la JVM (as opposed to just Java as a language but with native code generation), COULD be a decent design to offer some level of protection against deliberate attacks. OK, the JVM doesn't have a great track record for its first few years, admittedly, but that's a question of careful execution as well as of whether the overall design is "bad". Oberon, I think, has a similar language+OS security strategy. Note that I _am_ talking strictly about protection against deliberate attacks. "Against stupidity, the Gods themselves fight in vain"!-) Inhibiting flexibility is a given for ANY security mechanism, alas. Python's own security architecture, based on the idea that untrusted code is a small percentage of all code you write and run and thus is best dealt with explicitly and separately from the vast mass of trusted code, is of course also quite a viable alternative design. I'm told its own track record, so far, isn't all that outstanding either -- again, particularly with security, "the devil is in the details"... I don't think, therefore, that you can judge the worth of a security _architecture_ from the dubious track record of an _implementation_ of that architecture; defects of detailed execution can obscure the architecture's worth. > To the truly intent or truly clueless, strict typechecking (a la C/Java) > protects against misuse about as much as Python's __instancevar munge > technique. "Strict typechecking" in C or Java is done badly anyway (look at Haskell for some indications of how compile-time type handling SHOULD be, if you want it!), and at least in C it has absolutely no intention to protect against any deliberate attack (the story's different in Java, with a JVM underneath, but, see above). Regarding _accidental_ misuse, i.e., errors, having the compiler do more checks does help a bit -- if nothing else, you learn about such errors a few seconds earlier, and that must be worth SOMEthing (as long as it doesn't lull you into a false belief that therefore you don't need code inspections and unittests -- of course you do, no compiler will catch a typo such as + where you meant -, and that can be a disaster!-). The problem is whether the costs (in development productivity) of such compile time checking are worth the gain (in getting a bit better error diagnostics a tad earlier, in making the compiler's life easier in generating good, fast code). I think that, in most situations, they don't. But it's a tradedoff to evaluate, not a black-and-white issue. The complication of private/protected/friendly/etc on the other hand IS an unrelieved mess. Python's '__' hack isn't much better. I do not think we have yet seen a perfectly clean and totally usable way to express the desired separation of interface from implementation, one that makes it totally clear to the author and reader of each piece of code whether it's interface, or implementation, of each given object and class, that said code is dealing with. Not in OO programming, at least, where you need to deal with (e.g.) subclassing too. For pure modular programming, Limbo (a Bell language with which they build their latest 'Inferno' OS), for example, shows an excellent way (and it's definitely not the only one). But we DO want OO for its many benefits over simple modular programming -- and how to best separate interfaces and implementation in THAT context is not obvious. Alex From rob Tue Jul 2 14:43:00 2002 From: rob (Rob Andrews) Date: Tue, 02 Jul 2002 18:43:00 GMT Subject: Where python especially good ? References: Message-ID: Python handily spanks alternative languages when it comes to the task of learning how to program! Thanks to the interactive interpreter, you can try out one line or block of code at a time, so debugging can take on a whole new meaning. Jython makes it possible to apply this same power to the business of learning your way around Java classes, as well. The Python community also rocks when you need help with something. comp.lang.python, the Python Tutor email list, and a host of other resources make it possible to get the attention of friendly humans who want your Python experience to be a better one. Rob http://uselesspython.com > What do you think, at what tasks pythons shows great benefits > comparing to other script languages ? > From gerhard.haering at gmx.de Tue Jul 9 03:29:35 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 9 Jul 2002 07:29:35 GMT Subject: Getting IDLE 0.8 to recognize Pyhthon 2.2.1 References: <115W8.7627$Xg%.3561@news01.bloor.is.net.cable.rogers.com> <9BqW8.13703$FH6.6004@news01.bloor.is.net.cable.rogers.com> Message-ID: Brad Fonseca wrote in comp.lang.python: > Gerhard H?ring wrote: >> * Brad Fonseca [2002-07-08 00:28 +0000]: >>> I've upgraded to python 2.2.1 but when I start IDLE it still starts >>> Python 2.1.1. How do I get IDLE to start Python 2.2 >> >> Two possibilites. >> [...] >> 2) A little more hackish: Find your idle: "which idle". Then change the >> first line from >> >> #! /usr/bin/python >> >> to >> >> #! /usr/bin/env python2.2 > > To be more clear, I tried the second option and it doesn't work > properly. How do I get idle to install on Mandrake. I used the > tarball to install 2.2 in my /usr/local/src directory. Well, you compiled Python yourself? Let's suppose your Python executable ended up in /usr/local/bin. AFAIK IDLE is never installed by the Python build process, but it exists in the Tools/idle in the source distribution. Just invoke Tools/idle/idle with your Python 2.2 executable. Yes, Tools/idle/idle doesn't end in .py, but this doesn't matter. If this works, you can then move Tools/idle outside of your source tree if you like, and change its shebang line to your Python 2.2 installation. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From jblazi at hotmail.com Sat Jul 13 18:23:21 2002 From: jblazi at hotmail.com (JB) Date: Sun, 14 Jul 2002 00:23:21 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308dcd_2@news.newsgroups.com> <3d309e8e_3@news.newsgroups.com> Message-ID: <3d30a68d_9@news.newsgroups.com> JB wrote: > Bengt Richter wrote: > > Your idea sound very clever. I always make the mistake of > describing my problem too abstractly. So following your > idea with the None placeholders, I simply travel through > list1. If an entry is celected by f, I copy it into list2, > otherwise I do not. At the same time I maintain a counter > for each lists for counting the entries that are not None. > Well, this will not work. Following this logic, I could use one list and have an extra attribut. This is not what I need, but thank you anyway. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From alw at gate2.dda.dk Thu Jul 11 15:25:24 2002 From: alw at gate2.dda.dk (Allan Wermuth) Date: Thu, 11 Jul 2002 21:25:24 +0200 Subject: writing output to file Message-ID: Inspired by an existing Perl script, I wrote this chunk of code, but instead of writing the result to the screen, I would like to write output to a another file. #!/usr/bin/python for line in open('/etc/passwd').readlines() : if line.strip()[0] == '#': continue temp = line.split(':') if int(temp[2]) > 100 : print "%10s %30s" % (temp[0], temp[4]) How can I do that? It's possibly quite simple, in Perl it is ;-) , but I am trying to learn Python, so I would appreciate if someone would help me out. /Allan Wermuth From jerf at jerf.org Wed Jul 24 20:11:38 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 25 Jul 2002 00:11:38 GMT Subject: Tk Dynamic Menus problem References: Message-ID: <_mH%8.156269$uw.92148@rwcrnsc51.ops.asp.att.net> On Wed, 24 Jul 2002 13:42:22 -0500, Greg Krohn wrote: > I'm not exactly sure why it's printing '3', but you do have a scoping > problem there. > Replace 'lambda: printFunc(i)' with 'lambda i=i: printFunc(i)'. Supplying i > as a keyword arg for the lambda brings i into the labmda's scope. Thanks, that did it. I would be interested in a bit more explanation though. In the "real" application, "i" were instances, not numbers (if that matters). Why would the 'i' in the previously created lambda commands "shift" to follow the outside value of i? I thought I understood Python's scoping. ;-) From ods at fep.ru Thu Jul 18 05:48:55 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Thu, 18 Jul 2002 13:48:55 +0400 (MSD) Subject: slicing and parallel assignment: inconsistent behaviour?? In-Reply-To: Message-ID: On 18 Jul 2002, Toby Donaldson wrote: TD> >>> B = range(10) TD> >>> B[1:5], B[5:10] = B[5:10], B[1:5] TD> >>> B TD> [0, 5, 6, 7, 8, 1, 2, 3, 4, 9] TD> TD> This works as I expect. But if I leave out the 10s in the TD> slice TD> indices, I get this: TD> TD> >>> A = range(10) TD> >>> A[1:5], A[5:] = A[5:], A[1:5] TD> >>> A TD> [0, 5, 6, 7, 8, 1, 2, 3, 4] TD> TD> Where has the 9 gone? I should become clear when you look how it works step-by-step: >>> A = range(10) >>> t1, t2 = A[5:], A[1:5] >>> t1, t2 ([5, 6, 7, 8, 9], [1, 2, 3, 4]) >>> A [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> A[1:5] = t1 >>> A [0, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] The length of list is now 11! >>> A[5:] = t2 >>> A [0, 5, 6, 7, 8, 1, 2, 3, 4] P.S. There is no problem when you swap two blocks with the same length. -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From aahz at pythoncraft.com Sat Jul 13 11:28:35 2002 From: aahz at pythoncraft.com (Aahz) Date: 13 Jul 2002 11:28:35 -0400 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <1026545186.810050@yasure> Message-ID: In article , James J. Besemer wrote: > >According to my Preferences settings, Netscape is supposed to wrap outgoing >messages to 66 columns. Like a lot of free software it doesn't always do the >right thing. Dunno where the 84 came from, probably the listmanager. > >On the plus side, Netscape wraps lines on incoming messages to my window width, >which is great. So I don't ever find myself in the position of complaining to >others about what amounts to a limitation of my own tools. One hopes you will be equally obliging when people ignore your posts. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From andrewm at object-craft.com.au Wed Jul 17 01:54:57 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 17 Jul 2002 15:54:57 +1000 Subject: map del efficiency python2.2 and 2.1 In-Reply-To: Your message of "Wed, 17 Jul 2002 01:16:30 -0400." Message-ID: <20020717055457.4DDA538F61@coffee.object-craft.com.au> >Under current CVS Python (what will eventually be Python 2.3), pymalloc is >tuned properly for new-style classes, and the deletion times are minor on my >home Win98SE 866MHz box (the del times below are 100x smaller than you were >seeing with 221+pymalloc); they should become minor on your box too, as >pymalloc's code is the same on all platforms, while its few hardcoded >assumptions about OS paging are geared more toward Unix than Windows: That's what I wanted to hear! I had just finished reading your CVS check-in comments and was building and testing the CVS python. Thanks for the fine work. >because it just confuses things to time explicit gc.collect() calls too >(except when you're specifically trying to time collection, as you may have >intended to do in your " del" test). I thought it only fair that explicit GC be included in the earlier tests as well - as it is when autoGC is enabled. BTW, I always ran the tests one at a time (with only one "if" selected) - running more than one test at a time resulted in wildly fluctuating times - presumably due to fragmentation of the heap. >gc is a bit zippier in current CVS too. More good news. Thanks. 8-) Here's the table again with CVS Python included, for those that care: Create and set attr Set attr Del+GC RSS -------- -------- -------- ------- py22 slots 20.3s 4.6s 19.5s 48M py221 slots 21.0s 5.0s 21.5s 48M pymalloc slots 16.2s 4.7s 0.7s 40M pyCVS slots 17.8s 5.0s 0.8s 40M py22 obj 65.9s 7.4s 401.5s 185M py221 obj 62.1s 7.3s 492.8s 185M pymalloc obj 57.9s 7.2s 125.8s 185M pyCVS obj 50.6s 6.8s 1.5s 185M py22 trad 55.8s 6.8s 275.8s 192M py221 trad 56.8s 7.1s 284.7s 192M pymalloc trad 52.6s 6.8s 115.0s 185M pyCVS trad 44.2s 6.2s 1.3s 185M py211 trad 52.6s 6.6s 239.4s 154M With gc.disable(), and explicitly calling gc.collect(): Create and set attr Set attr Del+GC RSS -------- -------- -------- ------- py22 slots 13.6s 4.6s 19.7s 48M py221 slots 14.0s 5.0s 19.4s 48M pymalloc slots 10.6s 4.7s 0.7s 40M pyCVS slots 17.8s 5.0s 0.8s 44M py22 obj 18.0s 7.3s 400.5s 185M py221 obj 18.7s 7.6s 399.0s 185M pymalloc obj 16.2s 7.2s 117.0s 185M pyCVS obj 13.8s 6.8s 1.5s 185M py22 trad 11.2s 6.8s 270.8s 192M py221 trad 12.1s 7.2s 240.7s 192M pymalloc trad 11.4s 6.8s 115.3s 185M pyCVS trad 9.2s 6.3s 1.3s 185M py211 trad 11.6s 6.5s 229.0s 154M py152 trad 7.8s 3.1s 75.5s 123M KEY ------ ----------------------------------------------------------- slots with new-style objects and using slots obj with new-style objects trad with traditional objects pyCVS Python CVS (aka 2.3, pymalloc on by default) pymalloc Python 2.2.1 compiled with --with-pymalloc py221 Python 2.2.1 py22 Python 2.2 py211 Python 2.1.1 with traditional objects py152 Python 1.5.2 with traditional objects (no cyclic-GC) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From wjdandreta at worldnet.att.net Sat Jul 27 12:43:29 2002 From: wjdandreta at worldnet.att.net (Bill Dandreta) Date: Sat, 27 Jul 2002 16:43:29 GMT Subject: Best way to populate a wxListCtrl widget from mysql References: <75f0ku48rojqeqo7bs5il2df1vf55bg5pb@4ax.com> <3d415a50.3394307@netnews.worldnet.att.net> Message-ID: <3d42ccd5.14890810@netnews.worldnet.att.net> Hi Chris, >the problems i faced with the grid was, that i had crashes when resizing a >grid. but i used a custom model for the grid, not the automaticaly >generated model. I had a crashing problem when I used the wxGridCellAttr() method. I assumed I was using it incorrectly so I found another way to accomplish what I wanted and it seems quite stable. >i have now a reasonably fast and stable solution using a virtual >wxListCtrl. >it's a bit lage to post here (10kB) but i can send it to anyone who's >interested. Thanks I would like to take a look at it, I am sure I can learn a lot from it. Bill From nhodgson at bigpond.net.au Fri Jul 26 20:07:05 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 27 Jul 2002 00:07:05 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E201922151DC@admin56.narex.com> Message-ID: Alex Martelli: > That's basically what Microsoft proposes to add in some future C# > with the same semantics, except the keyword they have in mind is > 'using' ('let' has strongly different connotations for VB users). The context of Brian Harry's article was before .NET 1.0 when Microsoft was seeing a lot of anger, particularly from VB programmers about deterministic finalization being taken away from them. There were other issues with the changes to VB but this was the one with the biggest effect on program design and potential for errors so received the most articulate howls. "using" actually made it into C# for .NET 1.0 although it was a very late addition and IIRC VB didn't get a similar feature. This mollified some of the critics although the issue still concerns some. Chris Sells (who was an influentional pro-DF voice) has a project funded by MS to incorporate ref-counting into Rotor, the somewhat-open implementation of parts of .NET. A Pythonista, Chris Tavares, is doing the implementation. http://www.sellsbrothers.com/spout/#refCountRotor Neil From roy at panix.com Sat Jul 13 17:00:34 2002 From: roy at panix.com (Roy Smith) Date: Sat, 13 Jul 2002 17:00:34 -0400 Subject: isA function? Message-ID: Is there a standard isA() function in Python? It should take two arguments, an instance and a class, and return true if the object is a member of the class or one of the class's ancestors. I know I can roll this myself with __class__.__bases__, but it seems like a common enough thing that there would be a built-in way to do it. I looked at the inspect module, and was surprised to not find it there. We're writing some unit tests, and one of the tests is "foo() returns something which isA (bar)". From ianb at colorstudy.com Fri Jul 12 03:25:48 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 12 Jul 2002 02:25:48 -0500 Subject: Python for data driven website? In-Reply-To: References: <3D2E51A0.730F521A@engcorp.com> Message-ID: <1026458749.612.34.camel@lothlorien.colorstudy.net> On Fri, 2002-07-12 at 01:42, Micah Mayo wrote: > Definatly reliabilty/scalability. We expect anywhere from 100-1000 > customers, which may or may not translate into multiple users per account. This isn't a huge number (if you don't mean concurrent users). I imagine that the accounts are going to be fairly lucrative, which is to say, if you have 1000 users you'll be able to afford a big beefy box -- and until then, you can probably get by with a smaller, cheaper box. This usage is within the performance capabilities of most things you'll look at (at least on Unix). I wouldn't put performance first -- reliability is probably much more important. If, for instance, you were running a public website with income from advertising, you'd have to be more concerned about performance, because high usage wouldn't necessarily mean high income. > Whatever we use need to be able to handle a gradual, or steep for that > matter, rise in use. I didn't mean to sound as if we were just looking for > cool technology. We have three person team. One older developer who has > years of experience with database programming, and two younger > intermediates. Me being one of the younger guys. The older guy is teaching > us the industry. The problem is almost all of his experience is with > microsoft products. When he decided that microsoft was not able to provide > an affordable solution, he started talking to us about a free/unix solution. > Of the three of us I am the only one with any real experience with unix(when > i was a luser teenager I thought I was cool because I ran FreeBSD as my > desktop), so I am the only one who is really comfortable in this area. So, I > get stuck with alot of research work of this sort. So, as far as the > application goes - the software is going to be a service for tax firms > available through the web only(unless a custom version is needed, which > would cost a pretty penny). If you want to plan for a non-web version (which would probably be appealing if there's a lot of data entry -- as I imagine there would be with a tax application), then you should consider that from the start. I would suggest building a strong, interface-neutral backend of objects and interfaces. You can then add a web interface, or a GUI interface, as you want it. Even if you only have a web interface, it's still a good design practice. This is one place where Python is considerably better than PHP or ASP -- it's a real, general-purpose language (and runs well on Windows). Of course, with ASP you'd want a COM interface to the backend, and with PHP... well, I don't know what you'd do. Perl is closer to Python than to PHP or ASP. But you'll have to decide on that yourself -- I can't say much of anything good about Perl (except library support), and you won't find many supporters in this forum. I imagine you'll want some sort of framework -- even if you use CGI, you'll just end up making your own ad hoc framework (which isn't horrible, but you should expect you'll be doing that). Configuration won't be a big deal if you are planing on running just a single instance of the program (on a central server) -- so I wouldn't worry about commercial hosting support (where Python is bad and PHP is very good). One problem you will have is that there really isn't a conventional way to do something like this in Python. In PHP or ASP, you won't be going out on a limb, you probably won't be doing anything that lots of people haven't done before -- the specifics of your application will be different, but all the parts will be things lots of people have done. Oddly enough, that doesn't mean that these repeated actions have been well factored so that they are trivial in these languages -- I am particularly unimpressed with the modularity and number of high-level abstractions in PHP. Everything about PHP seems very expedient -- which is good and bad. If you do use Python, there are a number of distinct options for what framework you'll use. I wouldn't recommend Zope, because if you aren't doing content management then it seems like a very bad fit -- there's a lot of conceptual overhead that isn't going to help you. You'll want to make a frontend right away -- that way you can see the product of your work, even if you end up throwing that frontend away. But I'd strongly advise you to spend a lot of time thinking about the objects that will represent your backend. If a framework demands that you buy-in wholeheartedly, then I don't think you should use it (which is another reason I don't think you should use Zope). -- Ian Bicking Colorstudy Web Development ianb at colorstudy.com http://www.colorstudy.com 4869 N Talman Ave, Chicago, IL 60625 / (773) 275-7241 From grante at visi.com Mon Jul 15 14:36:05 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 15 Jul 2002 18:36:05 GMT Subject: 8 Queens Problem References: Message-ID: In article , Simon.Foster at smiths-aerospace.com wrote: > Just For Fun! > > I've been working on a solution to the eigth queens puzzle. > Here is my attempt. There's a solution in Scheme in SICP > which takes only 13 lines. Can anyone come up with a shorter > solution in Python, without any of the obvious silliness? Or, if you like obvious silliness, here's one with a Tkinter user-interface that shows the chess-board as it solves the problem... ftp://ftp.visi.com/users/grante/python/queens.py -- Grant Edwards grante Yow! Is this "BIKINI at BEACH"? visi.com From mhammond at skippinet.com.au Thu Jul 4 20:34:37 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 05 Jul 2002 00:34:37 GMT Subject: COM component implementing custom interfaces References: <46585325.0207030824.7a22dfa1@posting.google.com> <3D2387EF.6020306@skippinet.com.au> <46585325.0207040825.7a5201b7@posting.google.com> Message-ID: <3D24EA63.50105@skippinet.com.au> Daniel Pi?ol Laserna wrote: > Mark Hammond wrote in message news:<3D2387EF.6020306 at skippinet.com.au>... > >>You need to check out the win32com\servers\test_pycomtest.py - this >>shows how to implement non IDispatch based interfaces. >> >>Mark. > > > When I run the example, I get > Traceback (most recent call last): > File "d:\dani\AppDev\python\APython22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 301, in RunScript > exec codeObject in __main__.__dict__ > File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\servers\test_pycomtest.py", > line 13, in ? > universal.RegisterInterfaces('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', > 0, 1, 1, ["IPyCOMTest"]) > File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\universal.py", > line 29, in RegisterInterfaces > tlb = pythoncom.LoadRegTypeLib(typelibGUID, major, minor, lcid) > com_error: (-2147319779, 'Library not registered.', None, None) > > If I comments out the offending line > (universal.RegisterInterfaces...), it runs ok and the object appears > in OLE COM viewer. But if I try to instantiate from VB, I get this > error > > Unexpected Python Error: pywintypes.com_error: (-2147319779, > 'Library not registered.', None, None) > -2147467259 > > I couldn't find any TLB or IDL to register That is a sample, and requires the PythonCOM test harness to completely work. So while you can probably not directly run the sample, you should be able to get enough out of it to make yours work. If someone would like to contribute a sample for a well-known COM object I can distribute I would be very appreciative. Mark. From baas at ira.uka.de Fri Jul 19 02:12:22 2002 From: baas at ira.uka.de (Matthias Baas) Date: Fri, 19 Jul 2002 08:12:22 +0200 Subject: ANN: Pyrex 0.3.4 References: Message-ID: On 17 Jul 2002 23:03:52 -0700, brian_l at yahoo.com (Brian Lenihan) wrote: >It's not you. MSVC doesn't like the void initprimes >prototype above the > >__declspec(dllexport) >void initprimes(void) { In what cases is the __declspec(dllexport) really necessary? This is new to pyrex 0.3.4, but I never had any problems before that (without the __declspec). I thought you only need that if you import the dll through an import library which Python doesn't do. Correct me if I'm wrong, but wouldn't the pyrex generated code be more portable if it would not contain the __declspec at all since it is a Microsoft specific extension and it's not really needed in this case. - Matthias - From gerhard.haering at gmx.de Tue Jul 9 05:08:57 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 11:08:57 +0200 Subject: [OT] Corrections about Java In-Reply-To: <200207091041.07136.b.maryniuk@forbis.lt> References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091041.07136.b.maryniuk@forbis.lt> Message-ID: <20020709090857.GA1413@lilith.my-fqdn.de> * Bo M. Maryniuck [2002-07-09 10:41 +0200]: > On Tuesday 09 July 2002 01:18, curt finch wrote: > > Issues and concerns > > ? No compiler to the native code. > Aha, sure. Java -- "write once and debug everywhere". Ask them what is JVM [...] Java compilers that output machine code exist. Even the GNU compiler family has one. I have read everything from horror stories to performance improvements for the commercial ones. > > ? Lacks native threading capabilities. > Really? Just do: > > import thread > import threading The difference is that Java has some support in the language (only the "synchronized" keyword, AFAIK) that supports synchronized methods and objects. Python's higher-level threading module was modelled after Java's and has everything Java has. It even has Queue.Queue, which Java hasn't. Python's features for thread synchronization also appear a lot more flexible than Java's to me. > > ? Python cannot write docstrings in C++. > What is this (anybody understood this?). Extension modules can of course have docstrings. > > ? Python is difficult to read. > Aha, sure: > -----------------8<----------------- > #!/usr/bin/perl -w > [...] See signature :) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From phsdv.remove at earthlink.net Sun Jul 21 00:19:05 2002 From: phsdv.remove at earthlink.net (Paul) Date: Sun, 21 Jul 2002 04:19:05 GMT Subject: maximum recursion depth Message-ID: I am just learning Python and found that the recursion depth is limited. Which is probably a good thing when you are learning ;-) The application that I am writing will recurse many times more than the 100(?) limit in python 2.2. Can I optimize my code so that there will be less recursion? yes, but my recursion depth will still be over 1000 times... Can I rewrite my code without recursion? Maybe, but I do not want to. My question to you: Is there a way to change the limit of the recursion depth? I've looked at the command line, searched the FAQ and searched the last 5000 messages in this newsgroup without luck... Thanks, Paul RuntimeError: maximum recursion depth exceeded From sholden at holdenweb.com Wed Jul 24 08:13:29 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 24 Jul 2002 08:13:29 -0400 Subject: Frame Size References: Message-ID: <9Rw%8.15371$xo1.13031@atlpnn01.usenetserver.com> "Kevin Doyle" wrote on October 22 this year ... > I have create a frame in the top right hand coner of the screen. I am > trying 2 things. > > 1) Determine the width of the screen so that I can set the width of the > frame. (For a temp solution I am harding coding) > > 2) I want to determine the height of the Frame. Note that I do get the > height using both GetSize and GetRect. All of the height properties are > for the height of the client area of the frame. I need the total height > of the frame i.e. including the Menu Bar, Toolbar, Status Bar. > > Thank you > I'm afraid I had to use the time machine to reply to this message, which should not have been posted for another three months. Please be more careful about sending mail and posting news from the future. Horse race results are usually useful. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From skip at pobox.com Thu Jul 25 12:37:58 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 25 Jul 2002 11:37:58 -0500 Subject: Speed up Python by up to 5% ? In-Reply-To: References: <15680.7634.425684.630761@12-248-11-90.client.attbi.com> Message-ID: <15680.10598.567216.695688@12-248-11-90.client.attbi.com> >> About a year ago I wrote an XML-RPC server to which people could post >> opcode frequency info (and retrieve it by version), but nobody bit on >> the idea. Here's the entire client-side code necessary to register >> this info: Sean> so we add the code below to any python apps we write and you get Sean> data based on our runtime usage? Yes, that's the general idea. You can also query for aggregate counts by Python version number. The server is currently not being run, and like I mentioned in my previous note, I'd probably require some further/different compression tricks to decrease the size of the payload. With DXPAIR you get a 256-element list of lists, each of length 257. That gets rather large when serialized as XML-RPC. Skip From donn at drizzle.com Sat Jul 13 00:55:18 2002 From: donn at drizzle.com (Donn Cave) Date: Sat, 13 Jul 2002 04:55:18 -0000 Subject: Making code 2.1 compatible References: Message-ID: <1026536116.794774@yasure> Quoth "Mark McEahern" : ... | did you know that 2.2 has been deemed the release targeted for stability by | the pbf? Where can I read about that? I'm curious to know what they mean. Thanks, Donn Cave, donn at drizzle.com From mcfletch at rogers.com Wed Jul 3 13:16:22 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 03 Jul 2002 13:16:22 -0400 Subject: Unicode utf-8 doesn't do back-and-forth? References: Message-ID: <3D233166.6010408@rogers.com> Well, and here I was believing utf was a clean and elegant format to make the best of a bad situation (I'm hoping utf-8 still is, though, of course, it will have these dang surrogates to contend with ;) ). "Nothing's clean, nothing's elegant kid. Get used to that. This is the real world, and out here, we just hack at the corpses until they give us what we want. There're no master criminals any more, just frustrated people, impossible situations, and no emotional air conditioning." Mike Tim Peters wrote: ... > The rest is history, and "surrogates" are a hack to get the effect of 4 more > bits (way more than enough to last us forever 10 times over). In > pre-Unicode-speak, you'd call them "escape codes". > > not-to-be-confused-with-escape-code-points-ly y'rs - tim ... From pecora at anvil.nrl.navy.mil Thu Jul 11 12:24:32 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Thu, 11 Jul 2002 12:24:32 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> Message-ID: <110720021224320303%pecora@anvil.nrl.navy.mil> In article <3D2CEDA1.4ACA69FE at engcorp.com>, Peter Hansen wrote: > Actually, the Morse is much easier to write, since it doesn't > require the Shift key (god how I hate underscores) Just go and design + develope your own keyboard. -- Lou Pecora - My views are my own. From franke at ableton.com Tue Jul 2 08:09:11 2002 From: franke at ableton.com (Stefan Franke) Date: Tue, 02 Jul 2002 14:09:11 +0200 Subject: Web templating/db tool with best designer/coder separation? References: Message-ID: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> On 22 Jun 2002 18:43:50 GMT, bokr at oz.net (Bengt Richter) wrote: >E.g., if you were hoping for an improvement over current practice, >which do you consider to be the tool(s) to beat, and what would >the killer improvement(s) be? TIA. [... and later] > Opinions on ZPT? I have a (vague) idea I'd like to discuss in this context. The first thing that came to my mind while reading the ZPT/TAL announcement some time ago was this: It's a brilliant idea to use attributes to specify operations on their including tags (replacement being the most important operation). Using special attributes instead of special tags increases the propability that they're left unchanged by HTML editors. But does it really go far enough? Still, the presentation logic substitution, iteration, ..) is encoded within a HTML template file with (now semantical, not syntactical) non-standard elements, which makes it hard to hand out the file to a page designer who knows nothing about programming. Can we further reduce the 'degree of intrusiveness'? (excuse my clumsy english) The set of operations we want to perform on a template is clear (see TAL spec): replacement (of tags or tag content), iteration, conditionals, adding attributes etc. But why place these operations inside the tags/template instead of finding another way of specifying the affected tags? HTML offers a standard way to address tags by using id attributes. Can't we leave the HTML alone, just mark the affected tags by giving them IDs, and put all the replacement/iteration commands into a separate place? The presentation commands could be either ordinary Python statements or some abbreviated/specialized variants of it (e.g. Quixote-like). The advantages I see here are - The template document is perfect HTML. Since we have substitution commands like in TAL, we can fill up the document with dummy data and make the template itself appear well-formed and reasonable in any browser - All the HTML designer has to respect are the IDs of certain tags ("tableLine", "customerNameCell", ..). If he knows JavaScript/DHTML he should be familiar with this anyway. - The same replacement logic could be applied to different template files, we have an additional layer of indirection here. - One presentation command file could address and assemle elements from different HTML template files Disadvantages: - One has to maintain two documents instead of one (but as I argued, I see this as an advantage) - In case of conditionals, there might be difficulties to bear up the rule that the template file is always perfect visible HTML - at least without redundancy - Scoping/local replacement within iteration might become complicated * * * What do you think about it? There might well be big things I left out of consideration, since I'm quite out of web business (my last bigger project was with Zope 1.10.2 and its DTML...). Best, Stefan Franke From tim.one at comcast.net Mon Jul 15 22:45:58 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 15 Jul 2002 22:45:58 -0400 Subject: Making code 2.1 compatible In-Reply-To: Message-ID: > | Laura Creighton wrote the FAQ: > | > | http://pbf.nuxeo.org/faq.html [Donn Cave] > Thanks. That does get fairly specific, 18 month release cycle > and limited new features. I infer from the language that they > understand that the new features part has potential problems. If they don't, we do -- the volunteer bugfix-release Patch Czars so far have taken a strong "no new features!" stance. Indeed, some members of the PBF seem less anal about that than the Czars have been (beyond that it's not always simple to distinguish bugfix from feature). ... > | What's to clarify? The 2.2 line is the most stable Python there is. > | They're business people, not Luddites . > > Matter of perspective. I would probably have picked 2.2 if it > had been left to me, just because it's current. But when I've > proposed it in the past I've suggested the recently out-of-current > release, because that makes it immediately an issue. Toward what end? They're business people, not Crusaders . > Either way, not on the basis of any technical properties of the > releases in question. I don't even know what "stable" means, rather > ambiguous if you ask me. People fielding bug reports have a good handle on relative stability, and in the cross-platform real-life senses the PBF is concerned about. The PBF build-and-test farm can only make that better. From andymac at bullseye.apana.org.au Fri Jul 12 21:09:37 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 13 Jul 2002 12:09:37 +1100 (edt) Subject: making python on Solaris 8 In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C75@hendrix.empolisuk.com> Message-ID: On Fri, 12 Jul 2002, Harvey Thomas wrote: > Solaris 8 (64-bit) > > gcc ver 2.95.3 > make ver 3.79.1 > > configure output and the make output with the error at the end are attached. > > Any ideas on what is wrong would be most welcome. You need ar to build the libraries. I would guess that either:- - your $PATH doesn't include the path to the Solaris ar (which I vaguely recall might be in /usr/ccs/bin or /usr/ucb/bin); - ar and friends weren't installed, in which case you might need the GNU binutils installed as well as gcc and gmake. HTH. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From whisper at oz.net Fri Jul 19 14:03:34 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 19 Jul 2002 11:03:34 -0700 Subject: newby's tut for tkinter? In-Reply-To: Message-ID: If you look in the tkinter doc in your pythondoc, you'll find links to several resources for tkinter, including at least one tutorial David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of netvegetable > Sent: Friday, July 19, 2002 10:39 > To: python-list at python.org > Subject: newby's tut for tkinter? > > > > Is there a nice simple tut for newby programmers to learn Tkinter? > > If not, is there any chance of somebody clever writing one? > > -- > netvegetable at excite.com > -- > http://mail.python.org/mailman/listinfo/python-list From phd at phd.pp.ru Mon Jul 1 09:52:04 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 1 Jul 2002 17:52:04 +0400 Subject: email package: call for testers Message-ID: <20020701175204.C6446@phd.pp.ru> Hello! Barry Warsaw finally merged my patches into the email package. This is the call for testers - those who use the python email package please download latest Python from CVS or latest daily snapshop and test that the patches don't break your programs. The patches implement RFC2231 parameter decoding and change interface of Message.get_param() and get_params() methods. After decoding rfc2231-encoded parameter these methods return 3-tuple (charset, language, value). Some methods that use get_param(), get_filename() for one, return unicode string, the result of unicode(value, charset) call; the language is ignored. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From zopestoller at thomas-guettler.de Wed Jul 31 11:41:57 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 31 Jul 2002 17:41:57 +0200 Subject: ZPT Was: Good XML tools? References: <3D46D1B5.248A2921@q-survey.be> <3D47C373.4040805@thomas-guettler.de> Message-ID: <3D480545.8060500@thomas-guettler.de> A.M. Kuchling wrote: > In article <3D47C373.4040805 at thomas-guettler.de>, > Thomas Guettler wrote: > >>I programmed with ZPT, but I switched back to generating HTML >>with pure python: >> >>Example: (ignore the german words) >> def editListsForm(self, REQUEST): >> > ... > > Quixote's PTL lets you make it slightly simpler, because you don't > need the res.append() calls and the ''.join() at the end; compiler > wizardry takes care of that for you. You lose the ability to have > docstrings, though, which is a minor tradeoff. > > In PTL your example would be: [cut] Does PTL *always* give me the line number where the error occured? I guess PTL uses eval() somehow. I don't mind typing ret.append(foostring) thomas From jonathan at onegoodidea.com Mon Jul 8 17:05:09 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 08 Jul 2002 22:05:09 +0100 Subject: COCOMO - appropriate for languages like Python? References: <7934d084.0207072141.17c249d@posting.google.com> Message-ID: On 8/7/2002 19:42, in article mailman.1026153791.18801.python-list at python.org, "Skip Montanaro" wrote: > Andrae> Hint: Do-not use gets()!!! > > Thanks for the elementary C security tutorial, but it really wasn't > necessary. I wanted to use gets() because it was semantically the closest > to file objects' readline() method (read a line from sys.stdin in this > case). Yes, I could have used fgets(s, 80, stdin) or something similar. > That wasn't the point of the post. I was asking about COCOMO. I thought the point was very valid. COCOMO is about fully-debugged lines of code. Andrae pointed out that your comparison was false because the lines of C code were clearly not "fully-debugged" and thus not comparable. Adding in the code necessary to implement comparable functionality results in a 30x increase in lines of code - and this doesn't even include any exception processing necessary to raise an appropriate error condition if the file isn't open or some other I/O error occurs. Comparing bits of code in-the-small almost never yields anything useful. COCOMO follows out of the ability of the brain to process and manipulate information. One can always write very sparse or very dense lines of code that break the model, but in-the-large programmers do not normally do that. They tend to write code in lines that fit easily in their head and, because of this, one line of code is pretty much comparable to another. Jonathan From donnal at donnal.net Sun Jul 21 22:10:22 2002 From: donnal at donnal.net (Donnal Walter) Date: 21 Jul 2002 19:10:22 -0700 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> <918bc22f.0207200441.7a5a130d@posting.google.com> <918bc22f.0207210552.56806903@posting.google.com> Message-ID: <918bc22f.0207211810.360860f1@posting.google.com> Syver Enstad wrote in message news:... > donnal at donnal.net (Donnal Walter) writes: > > > > > > Yes, from the responses here that does appear to be the conventional > > way of doing things, so I guess I will continue using unittest this > > way too. I had thought I might replace my batch files with a > > TestSuite, but I'm really not complaining about the way it works now. > > Thanks. > > Btw, here's some code I put in my __init__.py files to run unittest > for all modules in a package. Maybe it does some of the things your > are looking for? > > > moduleNames = map(lambda each: os.path.splitext(each)[0], > filter(lambda each: each != '__init__.py', > glob.glob('*.py'))) > > # this was the testLoader I was talking about, it makes a suite from > all TestCase derived classes in moduleNames. > > suite = unittest.defaultTestLoader.loadTestsFromNames(moduleNames) > > runner = unittest.TextTestRunner(verbosity=1) > runner.run(suite) Yes, that is what I was looking for. Thanks. From stefnin.nospam at yahoo.fr Wed Jul 3 11:33:08 2002 From: stefnin.nospam at yahoo.fr (Stephane Ninin) Date: 03 Jul 2002 15:33:08 GMT Subject: multiple inheritance & __init__ Message-ID: Hi, A small question about muliple inheritance. I am starting from: " class ExListbox(Observer,Tkinter.Listbox): def __init__(self,dl): ... " where Observer is some class... In the ExListbox.__init__ constructor, is there any reason to choose this order: Observer.__init__(self) Tkinter.Listbox(self) or this order: Tkinter.Listbox(self) Observer.__init__(self) as compared to the order in the class declaration: class ExListbox(Observer,Tkinter.Listbox) ? Thanks in advance for your help. Regards, Stephane -- Stephane Ninin stefnin.nospam at yahoo.fr From abelo at earthlink.net Tue Jul 16 18:22:23 2002 From: abelo at earthlink.net (Carl) Date: 16 Jul 2002 15:22:23 -0700 Subject: Module Problem Message-ID: <1d95285a.0207161422.54dd6956@posting.google.com> - I downloaded the Python22 software along the the Python Manuals. - I got the part where you are supposed to save the fibo.py module. - I saved the module to C:\Python22 using the notepad in windows 98. the file in that directory was saved as fibopy~1 the full file name reads as fibo.py.txt - The python shell does not recognize this as a module when I try to import it. - Please help me get around this problem. Thanks. From peter at engcorp.com Mon Jul 8 19:36:27 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 19:36:27 -0400 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> Message-ID: <3D2A21FB.C3FA21BE@engcorp.com> Roy Smith wrote: > > Peter Hansen wrote: > > Is it really important the order the tests are run in? > > I'm not sure, but it certainly *feels* like it should be important ;-) [...] > From the point of view of "it's done when it passes all the tests", then > yes, I agree with you that the order doesn't matter. But as a > diagnostic tool, it seems like order might be important. That makes a lot of sense. In that case, maybe it would be enough to organize the tests into reasonably small test cases, at which point you mostly wouldn't have to be concerned with which one actually ran first. I tend to start with a test case called something like BasicTests, and certainly if there's a failure there, I can disregard the other more sophisticated test cases that sort of build on that one. Within it I might have only four or five tests, so I don't much mind if one runs before the other. I do, however, as I said, sometimes do the same as you with the numbering, but I don't generally worry about keeping room for expansion. It's easy enough to renumber five tests if I really, really need to insert a new test01. -Peter From max at alcyone.com Sat Jul 13 17:07:29 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 13 Jul 2002 14:07:29 -0700 Subject: isA function? References: Message-ID: <3D309691.16843596@alcyone.com> Roy Smith wrote: > Is there a standard isA() function in Python? It should take two > arguments, an instance and a class, and return true if the object is a > member of the class or one of the class's ancestors. You want `isinstance'. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From krissepu at vip.fi Mon Jul 8 08:13:51 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Mon, 08 Jul 2002 15:13:51 +0300 Subject: Is there a re guru out there? References: Message-ID: <3D2981FF.E09515E9@vip.fi> Try modifing this example: ----code starts ---- >>> pattern = re.compile("(\?[^?!]+(\?[^?!]+\!)*[^?!]+\!)") >>> Line = "?AA?BB!CC!?DD!ee?EE!ff?FF?GG!HH!" >>> print re.findall(pattern, Line) >>> [('?AA?BB!CC!', '?BB!'), ('?DD!', ''), ('?EE!', ''), ('?FF?GG!HH!', '?GG!')] ----code ends ---- The code above searches strings that are between ?- and ! -signs. Only one nested level is allowed. Anyways, just add more levels inside group (\?[^?!]+\!)* and possibly change some + -signs to *?: pattern = re.compile("(\?[^?!]*?(\?[^?!]+\!)*[^?!]*?\!)") -pekka- Krzysiek Czarnowski wrote: > Hello! > And thanks for the prompt answer. > > Daniel Yoo wrote: > > > > Ah, a LaTeX to TeX converter. Cool! > > Well, rather a simple tool to reduce the amount of manual work required... > > > > If you can guarantee that there isn't any nested braces within the "frac" > groups > > > I would like to accept nested braces (at least to some extent)... > Later I will look into your examples closer. > > > > However, if there are groups within the frac groups, like: > > > > \frac{e^{42}}{\pi} > > > > then that will cause problems. This kind of pattern is something that > > regular expressions alone won't be able to cope with, because the > > grammar is recursively defined. > > That's what I was afraid of... > Probably I will have to do with a solution accepting only finite level of > nesting... > > Thanks anyway, > Krzysztof From aleax at aleax.it Sat Jul 13 12:18:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 16:18:37 GMT Subject: Tkinter Menu command References: Message-ID: Raimo Tuisku wrote: > Is it possible to pass arguments to a method which is executed after > event? I am trying to do so with add_command method from Menu widget to > avoid writing separate method for every case. I proposed what I personally consider the most elegant solution just a few days ago, I think. In your context, add (assuming Python 2.2, which you seem to have judging from your later observation): def makeColorSetter(self, color): def setcolor(): self.label.config(fg=color) return setcolor > #From class App: > self.mb = Menubutton(self.frame, text="Color") > self.mb.grid() > self.mb.menu = Menu(self.mb,tearoff=0) > self.mb['menu'] = self.mb.menu > self.colors=['red','green','blue'] > for item in self.colors: > self.mb.menu.add_command change to: self.mb.menu.add_command(label=item, command=self.makeColorSetter(item)) > (label=item,command=lambda :self.set_color(item)) > # Even this doesn't work. Apparently it always uses > # self.set_color('blue'). (self.label colors to blue) Yes, you need to take a "snapshot", which requires item be passed as an argument -- if you access the outer function value of variabie 'item', you'll always get the most recent value at the time your function run, not the value at the time the function was created. So basically you'd need: command=lambda color=item: self.set_color(color) Personally, I find lambda most often results in less-readable code, even if you assume the code reader or maintainer is fully informed regarding such refinements as 'snapshot behavior' versus 'nested scopes'. My advice is to choose a "closure" idiom, i.e., a function (or method) that contains and returns another function, like the 'makeColorSetter' in this case. This gives you the generally-needed 'snapshot' effect automatically, and lets you give names to the two functions involved, which, assuming you choose such names well, enhances code clarity. Alex From simon at uggs.demon.co.uk Wed Jul 10 13:18:49 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Wed, 10 Jul 2002 17:18:49 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <3d2b69b6.15643974@news.dsl.pipex.com> <3d2be255.329033@news.dsl.pipex.com> <37TW8.47022$n4.11329907@newsc.telia.net> Message-ID: <3d2c6526.33801443@news.dsl.pipex.com> On Wed, 10 Jul 2002 09:28:31 GMT, "Fredrik Lundh" wrote: >Simon Foster wrote: > >> Oh Fredrik, I bought your book too! > >good. > >page 12-14 should explain why eval is unsafe, I think. > >page 38 mentions ways to convert strings to numbers, and >the quote on page 39 should tell you why matt's "re + eval" >approach can be dangerous... > >the next time someone points this out, you could answer >"I know, I have the book" instead of "are you a troll"... > > > > At the risk of continuing this... The actual response I got was >Overkill. Unsafe. Ugly. Lame. Do you think that's fair? I wouldn't have worried apart from the "lame" comment. -- Simon Foster Cheltenham England From martin at v.loewis.de Wed Jul 17 14:35:32 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Jul 2002 20:35:32 +0200 Subject: inheriting from C types References: <878dc260.0207161005.6fec78ec@posting.google.com> <3D34E854.8020200@something.invalid> Message-ID: Greg Ewing writes: > > What is k.__mro__? > > > I believe it stands for Method Resolution Order, That wasn't really my question :-) I wanted to find out what the value of k.__mro__ is for this specific class k in the original article, since the OP claimed that the methods of the base classes aren't found. Regards, Martin From see_reply_address at something.invalid Thu Jul 4 21:26:02 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 13:26:02 +1200 Subject: Creating Subclassable Objects?? References: <3D232862.9030309@shinners.org> Message-ID: <3D24F5AA.2050800@something.invalid> Pete Shinners wrote: > At this point you are able to subclass the objects, the problem is they > just don't work. If my new class has an __init__ method, it seems i > cannot properly instance the objects (since it needs some args). I'm just guessing here (I haven't played with this stuff much myself) but if your subclass's __init__ takes different arguments from the base class, you may need to override the __new__ method as well as the __init__ method, e.g. class MySubclass(SomeExtensionType): def __new__(self, my_args): return SomeExtensionType.__new__(...base class args...) def __init__(self, my_args): SomeExtensionType.__init__(...base class args...) ...more init... > If I > don't have an __init__ method, i can instance the new class, but none of > the new methods i add to it work (AttributeError). I don't know what might be causing that. Are you sure you've done all the necessary things to make your extension type subclassable? Have you put PyObject_Generic{Get,Set}Attribute in the appropriate type slots? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From wilk-spamout at flibuste.net Fri Jul 19 04:33:28 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Fri, 19 Jul 2002 10:33:28 +0200 Subject: safe_mode of modpython ? References: <20020718220026.53776b94.wilk-spamout@flibuste.net> Message-ID: <20020719103328.2dc6e0ef.wilk-spamout@flibuste.net> Le Thu, 18 Jul 2002 22:15:06 +0200 Gerhard H?ring ?crivait: > * William Dode [2002-07-18 22:00 +0200]: > > Is there an equivalent of the safe_mode and openbasedir of php in a > > python module for apache ? > > Can you describe shortly what these do? > > I believe the answer will be "no" and "you'll have to fiddle with > rexec/bastion", but I don't know about these PHP features, yet ;-) > > There might be non-Python solutions in the Apache configuration for the > problem you're trying to solve (I'm thinking of mod_userdir, for > example). Yet I have no idea yet what the problem to solve could be :-) My problem is for shared web hosting, i would like to give different right access to directory by virtual hosting. Like suexec for cgi. That a script of one virtual host cannot access the directory of an other virtual host. bye -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From erno-news at erno.iki.fi Wed Jul 17 08:33:02 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 17 Jul 2002 15:33:02 +0300 Subject: Session ID & Security References: Message-ID: In article , Jan Felix Reuter writes: | Now I'm concerned about security, because with this sheme an attacker could | easily get access to a user's session by just guessing its ID. After some | research I found out about Message Authentication Codes and the hmac python | module. How does one use it? Do I apply the algorithm to every message (cgi | output?) and place the hash in another cookie or appended to the session ID | string? So, if the client sends back a hash that differs from the last hash | the server has send, the session is discarded, is that how you do it? one way to do it would be: pick a secret key (random string) that is known only to your cgi program. generate a regular session identifier (for example incrementing number, or whatever). use session-id-plaintext + hmac(key, session-id-plaintext) as session id. when you have an incoming http request, split it into the session-id-plaintext and session-id parts, and see if the hmac matches. iow, you only have to hash the session id itself. -- erno From fredrik at pythonware.com Mon Jul 1 13:26:32 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 17:26:32 GMT Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> <3D1BA535.1EE16646@engcorp.com> <4phT8.45578$n4.10822996@newsc.telia.net> Message-ID: Frank Tobin wrote: > I think the fact that the first few tries here were *wrong* about how > to implement a chomp indicates that it really should part of Python. or maybe it just says something about comp.lang.python ;-) From tim.one at comcast.net Thu Jul 4 13:31:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 04 Jul 2002 13:31:12 -0400 Subject: testing a sequence for 'identicalness' In-Reply-To: Message-ID: [Rajarshi Guha] > does anybody knwo how I can check a sequence for 'identical ness', ie > given a sequence: > > [1,1,1,1,1,1,1,1,1,1] > > it would be classified as 100% identical 100% identical to what? Itself? That's easy . > and > > [1,1,1,1,1,1,1,1,1,2] > > would be classified as 90% identical. >>> import difflib >>> m = difflib.SequenceMatcher(None, [1]*10, [1]*9 + [2]) >>> print m.ratio() 0.9 >>> Read the difflib docs for more. From brueckd at tbye.com Wed Jul 31 00:29:43 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 30 Jul 2002 21:29:43 -0700 (PDT) Subject: global interpreter lock not working as it should In-Reply-To: Message-ID: On Tue, 30 Jul 2002, Jonathan Hogg wrote: > I really do think we're singing from the same hymn sheet here. > > -no-you're-right!-ly y'rs, > > Jonathan Ok, gotcha. Sorry for the confusion! -Dave From b.maryniuk at forbis.lt Thu Jul 11 11:54:52 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 17:54:52 +0200 Subject: Hierarchical Editor In-Reply-To: <3D2DA088.10606@thomas-guettler.de> References: <3D2C3458.1090902@thomas-guettler.de> <3D2DA088.10606@thomas-guettler.de> Message-ID: <200207111754.52019.b.maryniuk@forbis.lt> On Thursday 11 July 2002 17:13, Thomas Guettler wrote: > The screenshot at treepad.com looks good. But I am addicted to > free source code I didn't find there Linux version. -- Sincerely yours, Bogdan M. Maryniuck We come to bury DOS, not to praise it. (Paul Vojta, vojta at math.berkeley.edu, paraphrasing a quote of Shakespeare) From bellman at lysator.liu.se Mon Jul 8 20:56:30 2002 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 9 Jul 2002 00:56:30 +0000 (UTC) Subject: `~/.pythonrc' `from __future__ import' References: Message-ID: Tim Peters wrote: > [Fran?ois Pinard] >> Moreover, this option only works for division, it does not apparently >> activate generators, for instance. > Yes, -Q is specific to division, as will become clear if you read the PEP > 238 "Command Line Option" section. >> I would rather have all future features available all the time when I >> write interactively, yet I guess why some people would prefer not. > There's no way to do that, short of fiddling Python's source code. Well... At least under Unix there is a way... Put this code in your ~/.pythonrc: import fcntl, termios, __future__ dels = "fcntl, termios, __future__, dels, feature, c" for feature in __future__.all_feature_names: dels += ", " + feature for c in "from __future__ import " + feature + "\n": fcntl.ioctl(1, termios.TIOCSTI, c) for c in "del "+dels+"\n": fcntl.ioctl(1, termios.TIOCSTI, c) (Unfortunately, __future__.all_feature_names isn't in Python 2.1, so if you need your .pythonrc file to be portable to 2.1 you will have to filter out the relevant names from dir(__future__). I leave that as an exercise for the readers.) Now, I didn't say it was *elegant*, but it seems to work on at least a couple of Unix dialects. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "The one who says it cannot be done should ! bellman @ lysator.liu.se never interrupt the one who is doing it." ! Make Love -- Nicht Wahr! From opengeometry at NOSPAM.yahoo.ca Sat Jul 6 22:29:33 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 7 Jul 2002 02:29:33 GMT Subject: python & web services References: <6pNV8.24555$2w.1181063@news20.bellglobal.com> Message-ID: John wrote: > What is currently available for the development of web services in > python? Everything under the sun. > Does Zope provide a complete solution? Yes, but you'll have bake a roast yourself. > (I am new to both and plan to learn them together) We can tell. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From renzo.tomaselli at tecnotp.it Wed Jul 10 06:26:35 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 10 Jul 2002 03:26:35 -0700 Subject: adding methods on the fly References: <878dc260.0207080702.2be7ba9f@posting.google.com> <878dc260.0207090321.14e06bbe@posting.google.com> <3VAW8.59624$vm5.2174084@news2.tin.it> Message-ID: <878dc260.0207100226.750b8513@posting.google.com> Alex Martelli wrote in message news:<3VAW8.59624$vm5.2174084 at news2.tin.it>... > It keeps looking to me as if you're making a lot of implicit assumptions, > and that many of them are wrong. What makes you believe, for example, > that just exec'ing "def foo(self): pass" does NOT leave you "a compiled > form" of function foo (in the locals dictionary used for executing)? > You can marshal such objects to bytestrings, too, for storing as BLOBs > or whatever. Yuup! this was the big missing point. Indeed I need to marshal all functions (user-defined methods, actually) down to my OODBMS (and the entire Python library too). Trapping/restricting import and all that stuff I know about. Now I know how to move from string methods to function objects, which can be attached as methods to classes derived from my C++ wrappers. I think I got a fairly complete picture now, so I will start to simulate something and see what happens. > > I still wonder why it's so hard (from a C/C++ perspective) to walk > > from a "def foo(self): pass" string to a callable object to be added > > to a class. > But it's not. exec that with a locals dictionary, and in the dictionary > at key 'foo' you find exactly a Python callable object (a function > object, to be precise). What IS "so hard" about this? def is an > executable statement, used to create function objects, so, if you > start with a def statement and want a function object, you, of course, > execute the statement. What COULD possibly be easier or mote natural? True but not obvious. I spent days in searching through this list on Google (and on C++ SIG as well). There are many messages about extending/embedding but none came to the above conclusions when the target is focused on methods. Thank you very much Alex, let me know if you plan to visit this area in the near future. Renzo Tomaselli --------------------------------------------------------------------------- TecnoTP s.n.c. Special Information System Design Maso Pelauchi I38050 Ronchi Valsugana, Trento TN ITALY Tel. +39 0461 773164 Fax. +39 0461 771514 e-mail: renzo.tomaselli at tecnotp.it --------------------------------------------------------------------------- From LogiplexSoftware at earthlink.net Fri Jul 19 12:43:26 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 19 Jul 2002 09:43:26 -0700 Subject: starting other programs from within python In-Reply-To: References: <20020716.171155.619290071.333@beer.com> <3D349AA0.1AE34452@engcorp.com> <20020717.123645.824272813.337@beer.com> Message-ID: <1027097007.2840.11.camel@software1.logiplex.internal> On Thu, 2002-07-18 at 17:16, hejduk wrote: > > > > If your goal is simply to execute applications from a menu, threads seem > > like overkill to me. I'd simply use the usual fork/exec methods. In > > Python, these are in the os module along with the spawn methods you refer > > to. > > > > --frank > > i thought that fork/exec involved a lot more overhead in terms of cpu > usage and memory? It depends upon your platform. On Linux fork() is very cheap. In fact, in some benchmarks I saw many years ago, Linux fork() calls were cheaper than Windows NT threads (in terms of startup times). Additionally, things like copy-on-write help keep memory usage reasonable. >From the Linux man pages: """ Under Linux, fork is implemented using copy-on-write pages, so the only penalty incurred by fork is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child. """ -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From paragate at gmx.net Fri Jul 19 16:01:01 2002 From: paragate at gmx.net (Wolfgang Lipp) Date: Fri, 19 Jul 2002 22:01:01 +0200 (MEST) Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? Message-ID: hi there, i am currently concerned with the problem of how to read temperatures from th ds182* components. unfortunately, i seem to have an older passive adapter that is neither supported by newer versions of digitemp (http://www.brianlane.com/digitemp.php) nor by pyOneWire. are there plans to extend pyOneWire so passive adapters (DS9097, DS9097E) are supported? From aleax at aleax.it Sat Jul 6 17:31:48 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Jul 2002 21:31:48 GMT Subject: Python version of STL multimap? References: <3d27636a$0$12309$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <8lJV8.40916$Jj7.1106374@news1.tin.it> Boudewijn Rempt wrote: ... > Isn't this exactly what Alex Martelli posted the other day: > > dict.setdefault(key, []).append(value) > > in answer to the thread about sorting a dictionary by its value? That's one possibility, yes -- a dict of lists. But if values are also hashable (a prereq I forgot to mention in my last post:-) and you don't care about order (and more often you don't, though sorting is an obvious exception:-), a dict of dicts may be better, as per my last post. Alex From shagshag13 at yahoo.fr Fri Jul 26 04:57:51 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 26 Jul 2002 10:57:51 +0200 Subject: redirect to > and to console ? Message-ID: hello, i use many python script like that : ./myscript.py file_in > file_out i wish i would sometimes like to force output to be redirect to console instead of file file_out, is there any way of doing that ? (for example to display errors message while file_in will contain only data processed) (or should i do ./myscript.py file_in file_out > log.file and let myscript handle i/o ?) thanks, s13. From jeffrey.b.layton at lmco.com Sun Jul 21 11:08:09 2002 From: jeffrey.b.layton at lmco.com (Jeff Layton) Date: Sun, 21 Jul 2002 11:08:09 -0400 Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> Message-ID: <3D3ACE59.1060004@lmco.com> Jeff Layton wrote: > Hello, > > If I instantiate a class in a function, > leave the function via a return and then > go back to the same function, will the > instantiation of the class still be there > or is it local to the function so it is > "destroyed"? (Does this make any sense?) > > TIA, > > Jeff > Oops, as a follow-up the function the instantiates the class and the routine it returns to are in different modules. Sorry about the confusion, Jeff From samschul at pacbell.net Tue Jul 23 00:58:58 2002 From: samschul at pacbell.net (Sam Schulenburg) Date: 22 Jul 2002 21:58:58 -0700 Subject: Problem with diferences in executinion References: Message-ID: In article , samschul at pacbell.net says... > >If I execute the following code snipit from Python it executes the way >I expected it. If I build a standalone exe with McMillan's installer >the function call to startscsi() function in MaxPTI's __init__() is >not in scope. > >Maxscsi.py is a file that initializes and loads MaxSCSI.dll which >contains startscsi(). This DLL and Maxscsi.py have been used in other >McMillan installer programs without any problems. This is the first >time I have tried to use a class to instanuate the DLL. The whole idea >behind this program is the desire to embed Python in an exe with some >added methods to allow non programmers to write an external script >file and execute it with the exe with the following call: > >"MaxPTI MyTest" > >Any Help would be appreciated >Sam Schulenburg > >======================= MaxPTI.py/MaxPTI.exe contains =============== > >from Maxscsi import * # import scsi library >from sys import * > >class MaxPTI: > > def __init__(self,Headless=0): > startscsi(1,Headless) # Start scsi initializtion setting > # Genericflag = 1,and Headless > initscsi("MaxPTI","physicaldrive",1) # Locate drives > setshowcdb(0) > setlogerror(1) > setpauseonerror(0) > ..... > ..... > def Function1() > .... > .... > > def Function2() > .... > .... > >if __name__ == '__main__': > a = MaxPTI(1) > exec("from %s import MyScript"%(argv[1])) > print 'Start Script' > MyScript(a) >=================== End MaxPTI.py ============== > >================== MyTest.py =================== >def MyScript(a): > print a.DeviceTable > for i in range(a.DeviceTableLength): > print a.DeviceTable[i] > print a.DeviceTable[2][a.pSERIALNUM] > print a.DeviceTable[2][a.pVENDOR] It has been requested that I provide a traceback to the above problem. The following traceback shows that the initial import statment is not being executed. This differs from what I reported in my first post, where I thought the problem was in the __init__() method. J:\Python22\MaxPTI>MaxPTI MyTest Traceback (most recent call last): File "", line 18, in ? File "iu.py", line 274, in importHook File "iu.py", line 357, in doimport File "Maxscsi.py", line 483, in ? from MaxSCSI import * # Import SCSI libraries File "iu.py", line 274, in importHook File "iu.py", line 357, in doimport File "Maxscsi.py", line 497, in ? startscsi(GenericOk,Headless) # Set log filename and initialize SCSI NameError: name 'startscsi' is not defined J:\Python22\MaxPTI> Sam Schulenburg From BPettersen at NAREX.com Tue Jul 23 13:02:24 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 23 Jul 2002 11:02:24 -0600 Subject: how to count lines in a file ? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> > From: Denis S. Otkidach [mailto:ods at fep.ru] > > On Tue, 23 Jul 2002, Shagshag13 wrote: > > S> hello, > S> > S> i need to count lines in a file (that i *can't* keep in memory, so > S> can't use readlines()) > > fp = open(filename) > it = iter(fp) > try: > while it.next(): > count += 1 > except StopIteration: > pass Now, why on earth would you use that monstrosity instead of: for line in open(filename): count += 1 ??? -- bjorn From tdelaney at avaya.com Mon Jul 22 19:23:15 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 23 Jul 2002 09:23:15 +1000 Subject: A better self Message-ID: > From: Delaney, Timothy [mailto:tdelaney at avaya.com] > > Do some profiling ... (untested code follows) ^^ Followed by results of a test run ... ;) Tim Delaney From aleax at aleax.it Fri Jul 26 03:18:34 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 07:18:34 GMT Subject: if(debug), optimized away? References: Message-ID: M wrote: > I would like to use something like this when running in > debug mode: > > if(debug): > if(items > 9): > print "fatal error..." > do_some_check_foo(42) > ... > > > If I set debug=0, is this code optimized away as in most > C/C++?? compilers? No, but if you used: if __debug__: if items > 9: andso(on) then running with python -O would indeed remove the code. > The reason for asking is that I would like to have A LOT of > debugging code and would like to avoid the performance penalty > when not runing in debug mode. That's exactly what __debug__ and the -O flag are for. The bytecode files produced are bleep.pyo instead of bleep.pyc, and they remove line numbers, asserts, and stuff done within "if __debug__:" guards. You can't effectively assign __debug__ at runtime of course -- by that time the bytecode has already been compiled. You need to indicate that you're running-optimized with "python -O" as the command to run your script. Note that the semantics don't change -- you only save code space by effectively removing the "if __debug__:" guarded blocks. That may indirectly translate in a little speedup if it helps your cache / VM be used more effectively. Alex From jromero at platea.pntic.mec.es Mon Jul 15 18:58:08 2002 From: jromero at platea.pntic.mec.es (Joaquin Romero) Date: Tue, 16 Jul 2002 00:58:08 +0200 Subject: maxlenght in Entry() / Tkinter References: Message-ID: ?Gracias! (=Thank you) From mhammond at skippinet.com.au Tue Jul 30 19:52:07 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 30 Jul 2002 23:52:07 GMT Subject: Error including win32net in a Python COM server References: Message-ID: <3D4726D5.7050001@skippinet.com.au> Emanuel Borges wrote: > The only difference that I have found is that in this particular COM > server, I am importing win32net. And after doing some debugging I > have found that the COM server works fine if I remove this import. > This, however I can't do because I need NetUseGetInfo, NetUseAdd, > NetUseDel & NetUseEnum for my Server to function correctly. I've win32net uses functions only available on Win NT/2k/XP - you should use win32wnet for Win9x. Mark. From tjreedy at udel.edu Sat Jul 20 11:55:26 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Jul 2002 15:55:26 GMT Subject: Using pointers References: <4210d7a2.0207200538.44a91c0f@posting.google.com> Message-ID: "Joe Krahn" wrote in message news:4210d7a2.0207200538.44a91c0f at posting.google.com... > Can I make a pointer to an object in Python? I know that all > objects/variables are references, but not in the same sense as in C. Let's reword a bit better. Objects are objects and *not* references. Variables are names associated with objects via internal references. > How do I get multiple pointers to reference and modify one variable? You mean like a = ['test'] b = a b[0] = 'done' print a ? This prints 'done', but this scheme only works with mutable objects. Terry J. Reedy PS. CPython uses the id of an object as its internal reference, but when you retrieve the id with the id() function, it becomes an external int object and useless for accessing the object (unless you subvert the interpreter by writing a custom C extension to do so). From keith_s at ntlworld.nospam.com Wed Jul 24 09:11:42 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Wed, 24 Jul 2002 14:11:42 +0100 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> Message-ID: <3D3EA78E.50303@ntlworld.nospam.com> Alex Martelli wrote: > You may have forgotten to conclude the string with a > '\n', which is typically needed from the point of view > of Python's syntax (for "dedent"...). The bit that drives Python is like this (I'm using QT for the GUI, and m_cmdview is just a pointer to the QLineEdit widget): void gld_cmdview::cmdExec() { QString s = m_cmdview->text(); char *cmd = (char *) s.latin1(); // Run the cmd (void) PyRun_SimpleString(cmd); m_cmdview->clear(); } The error message I get is like the following: File " ", line 1 for x in [1, 2, 3]: ^ SyntaxError : unexpected EOF while parsing From TomH at optiscan.com Tue Jul 9 18:03:03 2002 From: TomH at optiscan.com (Tom Harris) Date: Wed, 10 Jul 2002 08:03:03 +1000 Subject: Which OS? Message-ID: Greetings, How do I tell which OS is running from within Python? Specifically I have some test scripts that have to run under DOS rather than Windows, else the timing is dicy. They should complain if they find Windoze is running. Tom Harris, Software Engineer Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168, Australia email tomh at optiscan.com ph +61 3 9538 3333 fax +61 3 9562 7742 This email may contain confidential information. If you have received this email in error, please delete it immediately,and inform us of the mistake by return email. Any form of reproduction, or further dissemination of this email is strictly prohibited. Also, please note that opinions expressed in this email are those of the author, and are not necessarily those of Optiscan Pty Ltd. From roy at panix.com Sun Jul 14 21:06:40 2002 From: roy at panix.com (Roy Smith) Date: Sun, 14 Jul 2002 21:06:40 -0400 Subject: isA function? References: Message-ID: "Delaney, Timothy" wrote: > What would be more useful though is to simply try to use the functionality. > If it works, why is there a need for it to be a particular type? If an > attribute is missing, the unit test will fail. If the semantics are wrong, > and it passes, the unit test needs an additional case added. But, what you're arguing is that the API is defined wrong, not that the unit test is written wrong. If the API says, "foo() returns an object of class bar", then it's the right thing for the unit test to determine if, indeed, foo() returns an object of class bar. Now, if you want to tell me that I should change the definition of foo() in the API to be, "returns something which has these three methods and these seven data items", well, OK, that's might be a point worth arguing. But, it's not the job of the unit test writer to decide that the API isn't designed right. From mgilfix at eecs.tufts.edu Mon Jul 29 21:09:21 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Mon, 29 Jul 2002 21:09:21 -0400 Subject: Python design failures (was Re: Let's Talk About Lambda Func In-Reply-To: ; from shalehperry@attbi.com on Mon, Jul 29, 2002 at 05:44:55PM -0700 References: Message-ID: <20020729210921.B2141@eecs.tufts.edu> I second that. Or even more interestingly, is there a place which lists who has ownership of each module? -- Mike On Mon, Jul 29 @ 17:44, Sean 'Shaleh' Perry wrote: > lovely image there ...... > > is there a place which documents modules needing a steward? > > -- > http://mail.python.org/mailman/listinfo/python-list `-> (shalehperry) -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From gb at cs.unc.edu Sat Jul 13 19:18:12 2002 From: gb at cs.unc.edu (gb at cs.unc.edu) Date: 13 Jul 2002 19:18:12 -0400 Subject: Print a traceback from an extension? Message-ID: Can I print a traceback from within a extension written in C? I know we're supposed to just keep returning NULL until we make it back to the main loop. That normally works fine. But I'm calling Python code from a callback that is called by C code. The Python code fails so PyEval_CallObject returns NULL. I want to provide a helpful message at that point. Can this be done? If so, can someone suggest where to look for an example? Thanks gb From tjreedy at udel.edu Thu Jul 11 22:03:35 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Jul 2002 02:03:35 GMT Subject: Python to XML to Python conversion References: Message-ID: "Mark" wrote in message news:d2f5f2d.0207111608.5f58aaf2 at posting.google.com... > Hello, > > Recently my employer has asked me to do some computer work though I'm > just savvy enough to write minor programs of little significance. My > job is to write a program that will be generic enough to take any form > of Python dictionary and be able to convert it to XML and back. > Ladies and gentlemen I am completely at a loss, I'm not a good > programmer. If anyone one has any good, simple and complicated > examples, or tips I would be eternally greatful if you'd share them > with me. I have searched desperately through every posting I could > find on the subject, but to no avail. Please Help! To make a start, I believe you need PyXML plus marshal or pickle modules. However, roundtripping *any* dict to text and back means roundtripping *any* Python object to text and back. I am sure that this is not always possible. You need sensible boundaries short of *all* possible objects. With that, I am sure there is existing and available code that does such interconversions. Terry J. Reedy From gerhard.haering at gmx.de Mon Jul 8 00:24:16 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 8 Jul 2002 06:24:16 +0200 Subject: Using Python for processing of large datasets (convincing managment) In-Reply-To: <7xznx2j1qp.fsf@ruckus.brouhaha.com> References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <7xwus7n5q4.fsf@ruckus.brouhaha.com> <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> <7xznx2j1qp.fsf@ruckus.brouhaha.com> Message-ID: <20020708042416.GA4949@lilith.my-fqdn.de> * Paul Rubin [2002-07-07 21:13 -0700]: > claird at starbase.neosoft.com (Cameron Laird) writes: > > You've mentioned once already that you might do more with your SQL. > > I can imagine that much the greatest returns in performance will > > come from writing more of your algorithms in SQL. That's likely to > > be a more scalable and satisfying ap- proach than the > > multi-processing complexities at which you've hinted. -- > > Actually, SQL tends to be awful slow too. Recent Oracle versions let > you write stored procedures in Java, Certainly sounds like a good deal for Oracle, Sun and the chip producers. I'm not sure if it solves any real problem. > which are orders of magnitude faster than PL/SQL procedures. MySQL > also has some alternate language interfaces for stored procedures now > but I'm not up on them. PostgreSQL allows you to write stored procedures in Python (and Tcl, and Perl, and PgSQL). Now that's useful. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cliechti at gmx.net Fri Jul 26 06:50:48 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jul 2002 12:50:48 +0200 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> <3D3EADD1.4020400@ntlworld.nospam.com> <3D3EFC18.30705@ntlworld.nospam.com> <3D412292.1030608@ntlworld.nospam.com> Message-ID: "Keith S." wrote in news:3D412292.1030608 at ntlworld.nospam.com: > Chris Liechti wrote: > >> this class isn't what you want... you need to supply a callable >> either name that method __call__ and add a "return" of the result, or >> much simpler, leave it away and use your "input" directly below. > > OK, so now I do: > > PyRun_SimpleString("interact('---Starting Python---', input)\n"); > > where my input function looks like: > > static PyObject * input(PyObject *self, PyObject *args) > { > char *string; > if (!PyArg_ParseTuple(args, "s", &string)) > return 0; > gld::gMsgView()->printf(MSG_NONE, "%s", string); > return PyString_FromString(""); > } > > (I'm returning an empty string just to test the above). This goes > into an infinite loop - I'd have expected it to output the prompt > '>>>' once, then wait for a non-null string. wrong expectation ;-) it reads from the input until it gets something usable. it should print the prompt once indeed, but then its calling your input over and over as you return only "". code.interact expects that you block until input s available. (you can try that out at the interactive prompt too, playing with code.interact) > Any ideas what's wroong? I've looked at the implementation of > builtin_raw_input() and can't find any clues to help. just return some real data, "print 'hello'\n" or so. and i think you can exit the interactive loop by raising an EOFError exception. -- Chris From wdraxinger at darkstargames.de Wed Jul 10 09:12:03 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 10 Jul 2002 15:12:03 +0200 Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> <3D2C2BEB.2040803@darkstargames.de> Message-ID: <3D2C32A3.6040505@darkstargames.de> Gerhard Haering wrote: > In article <3D2C2BEB.2040803 at darkstargames.de>, Wolfgang Draxinger wrote: > >>Michael Hudson wrote: >> >>>For getting rid of builtin functions, why bother? >> >>Because some of them can mess up all. > Don't you provide the Python scripts yourself? If you want to expose your > app to users and you want to restrict what they can do with the > interpreter, you can check out the rexec and Bastion modules. Of course games developed by me will contain error free scripts. However my engine is called even. extendible virtual environment (e)ngine. That means, that every user can build own things. Onother thing is, that I provide a console running in python interactive mode. If there were all python modules open cheating would be the easiest thing to do. And another important thing is security: Players are allowed in multiplayer environments to pass their own equipment, player models etc. together with the scripts to the server. Thus limiting access to game specific tasks is a must! > Basically forking the Python source sounds like overkill. I don't want to fork whole python, just some builtin modules. -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From sarmstrong13 at mac.com Tue Jul 9 15:12:02 2002 From: sarmstrong13 at mac.com (SA) Date: Tue, 09 Jul 2002 14:12:02 -0500 Subject: New newbie question. Message-ID: Can you read a pdf with Python? I know you can read a text file with: Inp = open("textfile", "r") Will the same thing work on pdf files: Inp = open("pdffile", "rb") ? Anyone know of a module that parses pdf files in python? Thanks. SA -- "I can do everything on my Mac I used to on my PC. Plus a lot more ..." -Me From b.maryniuk at forbis.lt Tue Jul 9 05:37:11 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 11:37:11 +0200 Subject: [OT] Corrections about Java In-Reply-To: <20020709090857.GA1413@lilith.my-fqdn.de> References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091041.07136.b.maryniuk@forbis.lt> <20020709090857.GA1413@lilith.my-fqdn.de> Message-ID: <200207091137.11467.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 11:08, Gerhard H?ring wrote: > Java compilers that output machine code exist. Yes, people espesially need Java COMPILER for CROSSPLATFORMING... > Even the GNU compiler > family has one. Has few. But no one use. Java "feature" (five years ago) was crossplatforming. But today it isn't feature, IMHO. The coolest feature of Java is bloatty code, 100% system language, multiple inheritance absence, licenses and stuff, that Java is a _closed_ system. For example, this goes loop forewer: for (;;) { try { break; //^^^^^ continue; } finally { lalala... } } Hall of shame, IMHO. > > > ? Python cannot write docstrings in C++. > > What is this (anybody understood this?). > Extension modules can of course have docstrings. But why they wanna write it in C++, not in English? :) > See signature :) reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) Well... Seems like Python. :))))))) -- Sincerely yours, Bogdan M. Maryniuck "Oh, I've seen copies [of Linux Journal] around the terminal room at The Labs." (By Dennis Ritchie) From dpinol at hotmail.com Thu Jul 4 12:25:49 2002 From: dpinol at hotmail.com (=?ISO-8859-1?Q?Daniel_Pi=F1ol_Laserna?=) Date: 4 Jul 2002 09:25:49 -0700 Subject: COM component implementing custom interfaces References: <46585325.0207030824.7a22dfa1@posting.google.com> <3D2387EF.6020306@skippinet.com.au> Message-ID: <46585325.0207040825.7a5201b7@posting.google.com> Mark Hammond wrote in message news:<3D2387EF.6020306 at skippinet.com.au>... > You need to check out the win32com\servers\test_pycomtest.py - this > shows how to implement non IDispatch based interfaces. > > Mark. When I run the example, I get Traceback (most recent call last): File "d:\dani\AppDev\python\APython22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\servers\test_pycomtest.py", line 13, in ? universal.RegisterInterfaces('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1, ["IPyCOMTest"]) File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\universal.py", line 29, in RegisterInterfaces tlb = pythoncom.LoadRegTypeLib(typelibGUID, major, minor, lcid) com_error: (-2147319779, 'Library not registered.', None, None) If I comments out the offending line (universal.RegisterInterfaces...), it runs ok and the object appears in OLE COM viewer. But if I try to instantiate from VB, I get this error Unexpected Python Error: pywintypes.com_error: (-2147319779, 'Library not registered.', None, None) -2147467259 I couldn't find any TLB or IDL to register From mday at apple.com Fri Jul 26 20:25:07 2002 From: mday at apple.com (Mark Day) Date: Fri, 26 Jul 2002 17:25:07 -0700 Subject: performance problem in python 2.2 References: Message-ID: <260720021725073781%mday@apple.com> In article , Fernando Perez wrote: > As you see, perl/python are in the same league, even though perl is a factor > of 2 faster. Maybe you missed Tim's comment about putting the loop in a function to make it faster. Using that trick made the Python version as fast as Perl on my machine. -Mark % time ./p1.py 1000000 2.71050724088e-08 ./p1.py 1000000 2.76s user 0.06s system 83% cpu 3.375 total % time ./p2.py 1000000 2.71050724088e-08 ./p2.py 1000000 1.88s user 0.07s system 82% cpu 2.369 total % time ./p3.pl 1000000 2.71050724087729e-08 ./p3.pl 1000000 1.90s user 0.01s system 85% cpu 2.246 total % cat p1.py #!/usr/bin/env python import sys n = 1.0 p = 2.0**64 # making p a float for fariness of comparison, not correctness c = int(sys.argv[1]) for i in xrange(1,c+1): n = (n * (p-i)) / p print 1-n % cat p2.py #!/usr/bin/env python import sys def foo(arg): n = 1.0 p = 2.0**64 # making p a float for fariness of comparison, not correctness c = int(arg) for i in xrange(1,c+1): n = (n * (p-i)) / p print 1-n foo(sys.argv[1]) % cat p3.pl #!/usr/bin/perl $p = 2**64; $c = $ARGV[0]; $n = 1; foreach $i (1..$c) { $n = ($n * ($p-$i)) / $p } print 1-$n, "\n"; From gerhard.haering at gmx.de Thu Jul 18 16:09:28 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 18 Jul 2002 22:09:28 +0200 Subject: Do GUIs for DBs exist? In-Reply-To: References: Message-ID: <20020718200928.GA2998@lilith.my-fqdn.de> * Mark Carter [2002-07-18 12:51 -0700]: > I was using PySqlite (a module that interfaces Python with the SQLite > database ) the other day, and I was thinking: hey, wouldn't it be > great if it had a GUI like MSAccess. Isn't the main point of access was it's relatively easy to combine its SQL engine with forms and that it includes the development environment to do so? Is that what you were referring to or were you only thinking about an admin interface for the database? Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From jwilhelm at outsourcefinancial.com Mon Jul 8 19:35:28 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 08 Jul 2002 16:35:28 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <96c7f32.0207081518.52ea644a@posting.google.com> References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <1026171328.15295.2.camel@jwilhelm.ofsloans.com> Wow... that is the funniest thing I have read in a long time. Thank you for the good laugh! Whoever was saying that obviously did no research. Well, maybe 2 minutes worth. Just enough to see that Python exists. I'll let the rest of the group rip up every statement in that list and rip your competitors a new arse hole. I just though I would thank you for helping me laugh. :) --Joseph Wilhelm From shalehperry at attbi.com Wed Jul 17 10:59:44 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 17 Jul 2002 07:59:44 -0700 (PDT) Subject: better 'splice' function In-Reply-To: <4620daca.0207170508.7820b059@posting.google.com> Message-ID: On 17-Jul-2002 gyromagnetic wrote: > Hi, > I have written a function that essentially 'splices' together a number > of tuples in a list, and I would appreciate any suggestions that you > might have on how to make the code or algorithm better. > > Each tuple in the input list comprises three strings, e.g. > ('A','k1,'B'). > The splice function should exhaustively try to match the 'end' (last > element) of one tuple with the 'beginning' (first element) of another > (eliminating the duplicate string) to create the longest tuples > possible. > something A LOT like this was discussed within the last two months at length. Many, many, many implementations were presented. Have a search through the archives. From wdraxinger at darkstargames.de Wed Jul 10 07:56:51 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 10 Jul 2002 13:56:51 +0200 Subject: Embedding Python the extreme way Message-ID: <3D2C2103.3020706@darkstargames.de> For my current 3D engine project I decided to use Python as a important part of the whole design. And it works well. However, now I want to make python an integal part of the engine, not just a external lib. And I not want to statically link it with the engine. My goal is, to discard all modules and builtin functions that I don't need, e.g. sys. It's intended to control the 3D engine, not to write complex scripts. Can anybody give me some advice for that. Embedding Python and writing extension modules is no problem at all, just "cleaning" the python sources. My base is Python 2.2.1 -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From dreed at capital.edu Sun Jul 14 14:08:07 2002 From: dreed at capital.edu (Dave Reed) Date: Sun, 14 Jul 2002 14:08:07 -0400 Subject: Pros/cons of various PostGres modules In-Reply-To: <20020714005307.GA4849@gargamel.hqd-internal> (message from Gerhard =?unknown-8bit?Q?H=E4ring?= on Sun, 14 Jul 2002 02:53:07 +0200) References: <545cb8c2.0207130852.74d88a5@posting.google.com> <20020714005307.GA4849@gargamel.hqd-internal> Message-ID: <200207141808.g6EI87r30238@localhost.localdomain> > From: Gerhard =?unknown-8bit?Q?H=E4ring?= > > * Jim Hefferon [2002-07-13 09:52 -0700]: > > Hello, > > > > I'm starting on a project that will have Python interfacing with > > PostGres. I see that there are now four modules listed on the Python web > > site. I'd be very interested in any suggestions as to which ones are > > best. > > > > I've used PyPgSQL with good luck in the recent past. But there are two > > that are newer > > Newer? AFAIK pyPgSQL and psycopg are the youngest projects of the four > DB-API adapters (pyPgSQL, psycopg, PoPy, PyGreSQL). And the latest > pyPgSQL release was on 2002-06-04, so I don't quite understand what you > mean here :) > > > that are thread safe. > > pyPgSQL has a threadsafety of 1, which means you can't safely share > connections among threads, but you can use the module in a multithreaded > application. I'd never do otherwise, anyway. psycopg, however, is > /designed/ for heavily multithreaded apps, and has threadsafety=2 (can > share connections among threads), IIRC. > > > Will I notice on a moderately-loaded application? > > In my experience, the only solution to get a sensible answer is to fire > use the time, hotshot or profile profile modules yourself to find out. > > > Are they debugged? > > AFAIK pyPgSQL and psycopg are both relatively bugfree and well > maintained. I can't speak for PoPy, except that they haven't got around > to republish at their new website for over a year now. > > PyGreSQL is IMO very badly maintained: there was a serious bug with > cursor.fetchone() always returning the first row of the resultset, which > made cursors basically unusable. It was known for over a year until > somebody (me) got annoyed enough to take the half-an hour to look into > the Python and C code, write a patch and submit it to the PostgreSQL > developers. Thank you! I've been bit by this bug. PyGreSQL is the one that comes with postgresql - correct? I found it worked fine on my Red Hat 7.3 system with their python 1.5.2 rpm, but as soon as I tried to get it working with my installation of python2.2 I had this problem. Can you tell me where the source for this patch is so I can make certain it's included in any postgresql installations I make? > > Is one faster than the others? > > psycopg is faster than pyPgSQL in my benchmarks. The bottlenecks in my > apps, however, were never the overhead of the database interface. I'd > suggest to profile the usage of the modules you consider in a real app. > > You can use code like this to do so: > > from pyPgSQL import PgSQL as mydbmodule > #import psycopg as mydbmodule > conn = mydbmodule.connect("") > # ... > > > Any other experiences? They all look good to me! > > As one of the pyPgSQL developers, I'm not unbiased, but I'd stay with > pyPgSQL and only consider psycopg as an alternative :-) As I understand it - please correct me if I'm wrong - I could install pyPgSQL and it would work w/o any changes to my code (other than importing that module) if I've stayed with the DB-API. Is this correct? Thanks, Dave From loewis at informatik.hu-berlin.de Thu Jul 4 05:56:30 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Jul 2002 11:56:30 +0200 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: robert_kuzelj at yahoo.com (Robert Kuzelj) writes: > one could imagine an object that is a mix between a factory and > a prototyperegistry. > > class ProtoFactory: > def __init__(self): > self.SourceObjects = {} > def register(self, name, source): > self.SourceObjects[name] = source Explicit is better then implicit. There should be two functions: register_factory, and register_prototype. It would be reasonable to pass functions to such a registry as well, which then typically qualify as factories. Regards, Martin From grante at visi.com Mon Jul 15 15:55:21 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 15 Jul 2002 19:55:21 GMT Subject: 8 Queens Problem References: Message-ID: In article , Grant Edwards wrote: > Or, if you like obvious silliness, here's one with a Tkinter > user-interface that shows the chess-board as it solves the > problem... > > ftp://ftp.visi.com/users/grante/python/queens.py It also allows you to start with a partial solution if you want. One thing it doesn't do is discard solutions that are rotations and/or mirror-images of each other -- that's been on my list of things to do for years. -- Grant Edwards grante Yow! HELLO, everybody, at I'm a HUMAN!! visi.com From erno-news at erno.iki.fi Tue Jul 23 03:14:15 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 23 Jul 2002 10:14:15 +0300 Subject: ssh and Python References: Message-ID: In article , "Andy Salnikov" writes: | "Erno Kuusela" wrote in message || hmm? you can always use a rsa key, unless the administrator || has disabled rsa keys (which would be silly since hardcoding || passwords is less safe). || | I know one example when one has to use plain password in ssh. | This is when you log on onto AFS-enabled host from non-afs machine | (or using ssh without AFS support, which is standard on Windows). | In this case using RSA you'll not get your AFS token and then you'll | need to execute 'klog' manually an type in your password anyway. oh, right. i suppose it would be the same with many of the other non-unix-password based authentication methods. -- erno From chris.gonnerman at newcenturycomputers.net Mon Jul 15 23:05:40 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 15 Jul 2002 22:05:40 -0500 Subject: Base-class method access References: Message-ID: <003001c22c75$b43eb740$0101010a@local> ----- Original Message ----- From: "Joseph Barillari" Hi. > Is it possible for a derived class to access overridden methods of its > base class? For example: > > > class Foo: > def frob(): > print "Spam" This is an error; frob() needs self declared. Same error below. > class Bar(Foo): > def frob(): > print "Eggs" > # In C#, the syntax to call Foo's frob() would be > # base.frob() > > > >> a = Bar() > >> a.frob() > Eggs > Spam > > Is there a means of doing this in Python? Coded like this: class Foo: def frob(self): print "Spam" class Bar(Foo): def frob(self): print "Eggs" Foo.frob(self) >> a = Bar() >> a.frob() Eggs Spam works just fine. Note that you *must* pass self if you call a class method directly. > Thanks in advance. > > --Joe Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From fredrik at pythonware.com Tue Jul 2 15:23:42 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Jul 2002 19:23:42 GMT Subject: Python needs better error reporting References: <6e990e29.0207020305.76551dcb@posting.google.com> Message-ID: <25nU8.46033$n4.10990753@newsc.telia.net> Hans-Joachim Widmaier wrote: > Instead of listing all the legitimate tokens that may follow, why not > just give something like "Incomplete 'if' statement?" of course, if you bother to read the *entire* error message, that's not too far from what it says today: File "", line 1 if s == "" ^ SyntaxError: invalid syntax (and the fact that your typical Python autoindenter refuses to indent the next line if you leave out the colon may also help; I usually discover mistakes like this long before I run the code...) From david.evans at ittransition.co.uk Fri Jul 26 15:12:34 2002 From: david.evans at ittransition.co.uk (david evans) Date: Fri, 26 Jul 2002 20:12:34 +0100 Subject: global param to exec (on win32) Message-ID: <1027710735.14561.0.nnrp-07.3e314eb6@news.demon.co.uk> I'm using win32 and I can't work out how "globals()" and the global param to "exec" relate to each other I'll be really grateful if anybody takes time to read to the end of this rather long description of my problem Thanks in advance David Evans ----- I've read the spec for exec at www.python.org and I think I can use the global/local params in the same way as I would use "env" when exec'ing C program but I can't make it work like I expect. >From VB, I'm successfully calling functions from within a class that is registered as an COM object (as per Ch5 PPW32). This class contains a variable representing the "mx.ODBC" connection that I need to share with other code (because of a restriction in the underlying ODBC implementation I cant create multiple connections). This variable is "self.sdk" within the class. The client VB code successfully calls many functions from within the class but I also want to be able to execute (user definable) functions from an external .py file such that these functions can also use the mx.ODBC connection and there seems to be a catch 22: with the external .py file containing: def outside_func(): xxx = sdk * if I run: from external_file import * exec "outside_func()" , {'sdk':self.sdk} the call fails because it can't find outside_func() * if I run: from external_file import * exec "outside_func()" the call works but the called function complains that it can't find global 'sdk' * if I run: # construct "my_dictionary" variable containing outside_func and sdk exec "outside_func()", my_dictionary the call works but the called function complaiss that it can't find global 'sdk' and when I print globals() from within the called function, its the same as globals() from within the caller, but I expect it to be the same as "my_dictionary" within the caller. Whatever I specify for the "local" param in my exec call, the target sees "locals()" as its param list. Have I misunderstood the way that global/local params to exec work? ------ (thanks again if you got this far!) From jepler at unpythonic.net Wed Jul 3 18:24:09 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 3 Jul 2002 17:24:09 -0500 Subject: Thread safetyness in Python In-Reply-To: References: <15651.6532.968436.256710@12-248-8-148.client.attbi.com> Message-ID: <20020703172403.A1008@unpythonic.net> On Wed, Jul 03, 2002 at 12:15:02PM -0400, Tim Peters wrote: > Another way to look at it is that > > list += iterable > > is equivalent to > > list.extend(iterable) > > except that under the covers the implementation makes the former act like > > list.extend(iterable) > list = list > > The bytecode for the "list = list" part has no effect in the end, so doesn't > matter. However, you could notice something awry in the following case: Thread 1 Thread 2 _temp = l _temp.extend(iterable) l = 37 l = _temp if the += was atomic, then the order would have to be Thread 1 Thread 2 _temp = l _temp.extend(iterable) l = _temp l = 37 or Thread 1 Thread 2 l = 37 _temp = l _temp.extend(iterable) [exception raised, no 'extend' attribute] But since the operation is not actually atomic, you can end up with 37 not actually stored in 'l'. Jeff From b.maryniuk at forbis.lt Tue Jul 9 09:23:49 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 15:23:49 +0200 Subject: Converting a hex string to a number In-Reply-To: <0017278C.C22236@smiths-aerospace.com> References: <0017278C.C22236@smiths-aerospace.com> Message-ID: <200207091523.49252.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote: > eval! Overkill. Unsafe. Ugly. Lame. -- Sincerely yours, Bogdan M. Maryniuck Anyone who thinks UNIX is intuitive should be forced to write 5000 lines of code using nothing but vi or emacs. AAAAACK! (Discussion in comp.os.linux.misc on the intuitiveness of commands, especially Emacs.) From edream at tds.net Fri Jul 12 11:12:56 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 12 Jul 2002 15:12:56 GMT Subject: Making code 2.1 compatible References: <3D2EED98.BD59D615@tds.net> Message-ID: <3D2EF1F3.4B18FAEB@tds.net> >Is there a way to ask Python not to allow 2.2 constructs? >Having Python complain when producing .pyc files would be good enough. Perhaps I should add, using Python 2.2 itself. One way would be to install Python 2.1, but I'd rather not do that :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From barr at cs.cornell.edu Mon Jul 1 01:06:39 2002 From: barr at cs.cornell.edu (Rimon Barr) Date: Mon, 1 Jul 2002 01:06:39 -0400 (EDT) Subject: spyce v1.1.13 Message-ID: There have been quite a number of changes, improvements since the prior wide annoucement. Refer to: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/spyce/spyce/CHANGES?rev=HEAD&content-type=text/vnd.viewcvs-markup for a summary. ---------- SPYCE - Server Python Pages SPYCE is a drop-in Apache module that supports simple and efficient Python-based dynamic HTML scripting. Those who like Python and are familiar with JSP, or PHP, or ASP, should have a look at this engine. It allows one to generate dynamic HTML content just as easily, using Python for the dynamic parts. Its modular design makes it very flexible and extensible. It can also be used as a command-line utility for HTML pre-processing, and also via CGI on any other server. v1.1.13 released on 1 July 2002. Get it at: http://spyce.sourceforge.net ---------- Your comments and suggestions are welcome. Enjoy, Rimon. -- * Rimon Barr Ph.D. candidate, Computer Science, Cornell University | barr at cs.cornell.edu - http://www.cs.cornell.edu/barr - Y!IM: batripler | | Understanding is a kind of ecstasy. +---- -- Carl Sagan From mwh at python.net Tue Jul 30 08:38:58 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 12:38:58 GMT Subject: ICQ package anywhere ? References: Message-ID: "Gillou" writes: > I'm actually building a monitoring system that sends mail alerts to > sysadmins. > I'd like to add ICQ messages and didn't find python packages (google, > parnassus, sourceforge) to send alerts to ICQ recipients. > Any hint ? > Thanks in advance ! Well, there's my icqlib wrapper: http://starship.python.net/crew/mwh/hacks/pyicqlib.html which works to the point of sending messages. Dunno what happened to icqlib development; either it stalled or it's gone somewhere else and left me in the dark... Cheers, M. -- One of the great skills in using any language is knowing what not to use, what not to say. ... There's that simplicity thing again. -- Ron Jeffries From sholden at holdenweb.com Mon Jul 1 11:26:08 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 11:26:08 -0400 Subject: Newbie that don't understand References: <3d1e262f.3755054@news.clara.net> <3D1E4F80.D8EFBB3E@engcorp.com> <3D1E56EC.7080203@SPAMnwinternet.com> <3D1E5BE9.86189DA9@engcorp.com> Message-ID: "Peter Hansen" wrote ... > Jim wrote: > > > > Peter Hansen wrote: > > > Just a dude wrote: > > > > >>My son is an electronics > > >>design engineer, and I still can't get my head around negative > > >>voltages, how the hell do you get a -12 V supply... to him it's basic > > >>but to me.............. > > > [snip my own reply which rather missed the mark this time, > because it's too embarrassing to leave in :-)] > > > While this is way off topic and way pedantic, electrons > > always leave and enter the same terminals (think electro- > > chemistry, like a battery). > > D'oh! What was I thinking? And they call me an engineer. :( > > Jim is quite right of course. Grumble grumble. > And here's me, thinking what an excellent joke we were having at the expense of all the reader who didn't understand you were pulling their legs. I'm really disappointed in you, Peter :-) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From LogiplexSoftware1 at earthlink.net Fri Jul 12 16:14:52 2002 From: LogiplexSoftware1 at earthlink.net (Cliff Wells) Date: 12 Jul 2002 13:14:52 -0700 Subject: switch recipe? In-Reply-To: References: Message-ID: <1026504892.3407.40.camel@software1.logiplex.internal> On Fri, 2002-07-12 at 13:05, Mark McEahern wrote: > > out of curiosity, what happens when n reaches the end of the > > int/long/whatever that stores it? > > My guess is this will run forever--if you let it. > > Perhaps it should allow an optional sentinel? The assumption is the caller > is responsible for using it wisely. Or you could just change it to (untested): def make_color_switch(color1, color2): def color_switch(): i = 0 while True: if i: yield color2 else: yield color1 i = not i return color_switch Cliff From cliechti at gmx.net Sun Jul 7 18:07:47 2002 From: cliechti at gmx.net (Chris Liechti) Date: 8 Jul 2002 00:07:47 +0200 Subject: Splitting lines in a file References: <3d28b895.70324260@news.dsl.pipex.com> Message-ID: simon at uggs.demon.co.uk (Simon Foster) wrote in news:3d28b895.70324260 at news.dsl.pipex.com: > How come when I split a file on arbitrary whitespace I get one fewer > lines then when I split on end of line? In the case when I split on > the \n the last line has zero length. 'cause split() drops the empty part at the end: >>> '1\n2\n3\n'.split() ['1', '2', '3'] >>> '1\n2\n3\n'.split('\n') ['1', '2', '3', ''] split() works on different whitespace characters at the same time and removes them more agressively (see below). when you specify a split character like split('\n') only that character matters. split() is more agressive in removing empty parts (note the two spaces between a and b): >>> 'a b'.split() ['a', 'b'] >>> 'a b'.split(' ') ['a', '', 'b'] chris -- Chris From dcinege at psychosis.com Mon Jul 29 12:04:25 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Mon, 29 Jul 2002 12:04:25 -0400 Subject: What is a glue language? In-Reply-To: References: Message-ID: <200207291204.25184.dcinege@psychosis.com> On Monday 29 July 2002 10:33, Jens Kubieziel wrote: > Hi all, > > the word 'glue language' is mentioned in the FAQ. I have no clue :-) > what this could mean. Could someone explain this (also a german > translation is appreciated)? Glue, noun: To join with glue or a viscous substance; to cause to stick or hold fast, as if with glue; to fix or fasten. Glue logic is what interconnects the primary components of a large circuit. (IE the 'minor' parts inbetween the CPU and the Chipset on your motherboard.) The term 'Glue Language' in reference to Python means it's well suited at joining together (acting as 'middleware' if you will) primary software components. IMO it's well suited to creating those primary components as well... Dave -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From jon_bills at hotmail.com Wed Jul 3 11:52:47 2002 From: jon_bills at hotmail.com (Jon Bills) Date: Wed, 3 Jul 2002 16:52:47 +0100 Subject: HT clear some wxPython fram? References: Message-ID: "Klaus Reinhardt" wrote in message news:mailman.1025708884.27158.python-list at python.org... > --------------------------------------------------------------------- > Hi > > When I do: > import wxPython.wx > > for i in dir(wxPython.wx): > print i > I can filter: > WXK_CLEAR > wxCLEAR > wxID_CLEAR > wxLog_ClearTraceMasks > wxResourceClear > But I can't use > wxClear(). > > HOW I CAN CLEAR SOME FRAME? Have you tried frame.Clear()? It's a member of wxWindow, which all frames derive from. Cheers, Jon. From cliechti at gmx.net Tue Jul 23 13:06:32 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 19:06:32 +0200 Subject: how to count lines in a file ? References: Message-ID: "Shagshag13" wrote in news:ahk1nk$3v7tf$1 at ID-146704.news.dfncis.de: > > "Chris Liechti" a ?crit dans le message de news: > Xns9254BFA8ABAABcliechtigmxnet at 62.2.16.82... >> "Shagshag13" wrote in >> news:ahk020$tl4ue$1 at ID-146704.news.dfncis.de: >> >> > i need to count lines in a file (that i *can't* keep in memory, so >> > can't use readlines()) >> >> but you can use xreadlines, or a bit nicer in Py2.2 where "file" is >> an iterator. > > i use file because i read this in documentation : > > open(filename[, mode[, bufsize]]) > An alias for the file() function above. > > does xreadlines will speed my function ? xreadlines does read lines on demand, instead of loading the entire file. (like range and xrange). and yes "file is open" i think it was introduced because of the "for line in file(...)" idiom, it sound better so than with open... you don't need "wc" or "wc -l" when you use the bit i posted before. chris -- Chris From whisper at oz.net Thu Jul 4 15:16:54 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 4 Jul 2002 12:16:54 -0700 Subject: Metakit help Message-ID: Working more with Metakit, i'm finding that there is some information not in the documentation, so I have a few questions: I think I figured out how to create a nested schema, but not how to insert or append a row with nested data - how is that done? How do you get a view from a pre-existing database? Can you modify the schema of an existing database? How? How do you put a pickle in a database? Are the various attributes of that pickle accessable while it's in metakit storage? How about the pickled object's attributes? How would you enforce a uniqueness constraint on a key field? TIA, David LeBlanc Seattle, WA USA From jb at cascade-sys.com Thu Jul 11 01:11:52 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 10 Jul 2002 22:11:52 -0700 Subject: COCOMO - appropriate for languages like Python? References: Message-ID: <3D2D1398.CD031698@cascade-sys.com> "Delaney, Timothy" wrote: > How does it deal with negative LOC? There are many cases where I consider > myself much more productive if I can *reduce* the code base. I don't know. But of course I'll hazard a guess. ;o) I imagine the cases where adding a feature or fixing a bug actually makes the overall code smaller are infrequent enough to be ignored. That is, in the overall scope of the project, the code grows by G and shrinks by S and S is much smaller than G. Again, the models apply (if at all) to projects overall and not to individual programmer tasks. Another angle here: I too can think of cases where I make the code "better" by making it smaller. E.g., replacing some hairy decision tree with a table driven approach. Or some predecessor's gunked up spaghetti code with something clean and readable. Often I am lucky in that I get paid to perform subtle optimizations like this that don't have a direct bearing on the product's overall functionality. Question is: is my productivity in this case positive or negative? If I "improve" something that does not materially affect the user, it could be argued that this is in fact negative productivity. After all, the client is paying something for nothing. At best, if you argue that the improved code reduces long-term maint costs, then the client is trading off a direct up-front cost for a long term benefit of dubious value. There are all sorts of different ways to view "programmer productivity." Regards --jb p.s. Didja get that winreg stuff to work? -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From krissepu at vip.fi Wed Jul 3 12:11:12 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Wed, 03 Jul 2002 19:11:12 +0300 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> <3D229458.719D4A7B@vip.fi> Message-ID: <3D232220.801FCD98@vip.fi> I know they are two different things, but you could provide additional tools/fixes into re-ex module to assist parser builders: 1) equal (a, b , string) Returns true is there are equal amount of non-overlapping strings "a" and "b" in "string" to be scanned. Use: parsing nested structures. Parsing is useless if text's limiters do not add up. Examples: equal ("(", ")", "aa(AA(BB))aa") returns True equal ("(", ")", "aa(AA(BB)aa") returns False 2) findall with parameter to control whether empty matches are returned. 3) recursive findall in C. Sketch in Python (not quite working, I know): result = [] parameter = re.findall("[(].*[)]", text) if count("(", text) > 1 and equal("(", ")", text) : # run findall to all parameters that have (- and ) -sign stripped (para[1:-1]) -pekka- Fredrik Lundh wrote: > Pekka Niiranen wrote: > > Please make also example of recursive decent > > parser, for example LL(k) > > regular expressions and parsers are two different things. > > you can use regexps to implement the scanner part of a > parser (see e.g. http://effbot.org/guides/xml-scanner.htm), > but they quickly break down if you try to do something > more sophisticated. > > From peter at engcorp.com Wed Jul 31 19:31:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 31 Jul 2002 19:31:26 -0400 Subject: a soft real-time system using pythonm References: <200207311359.JAA15020@test-area.com> <20020731145848.GC1800@unpythonic.net> <200207311632.MAA01291@test-area.com> Message-ID: <3D48734E.A603B5EF@engcorp.com> Jeff Epler wrote: > > Reference counting is the cause of unbounded delays for simple > assignments, as in the second statement of > x = [unique() for i in range(1000*1000)] > x = 3 > each unique() that was in x will be cleaned up by reference counting at > the time of the second assignment. There's no easy way to place a limit > on the size of containers. Sure there is! Don't create any container bigger than M items... Given that the soft realtime systems in question are likely not supposed to run code from unprotected sources, why would it be difficult to simply avoid creating really large containers? > IMO, even "soft" realtime based on Python threads is not going to fly. > These items are just off the top of my head, I'm sure there are more. > And more still in any extension module you'd like to include. Well, working in a company which has been developing soft realtime (embedded and server-based) systems based on Python threads running on Linux for quite some time, I have to disagree with you. Our products are functioning in the field with acceptable performance and we haven't had any reported cases of containers suddenly blossoming to 1000*1000 items and bringing the system to its knees. There's an expression used often in XP circles in response to people saying things like "if you create a billion instances of class Unique you might have problems". The response is something like "Doctor, it hurts when I create a billion objects" and the implied answer is of course "stop doing it". -Peter From mhammond at skippinet.com.au Sun Jul 21 19:04:47 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 21 Jul 2002 23:04:47 GMT Subject: COM server events References: <3D3B282D.6060601@paradise.net.nz> Message-ID: <3D3B3E1A.6060700@skippinet.com.au> Matthew Sherborne wrote: > Anyone know how I can write a COM server that serves events? I think > what I need is "connection points" ? > > Matthew > Check out the win32com samples - win32com\test\test*events and win32com\demos\connect.py should get you started. Mark. From mhammond at skippinet.com.au Wed Jul 31 19:02:11 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 31 Jul 2002 23:02:11 GMT Subject: ASP performance problems References: <2ec1bc1c.0207311224.62d6c8a7@posting.google.com> Message-ID: <3D486CA3.4020101@skippinet.com.au> Larry wrote: > I've implemented a web application on an NT/IIS platform using Python > and Active Server Pages. > > Most of the heavy logic and database access is contained in modules > that I import on the ASP pages, so the pages are pretty clean. It's > usually a function call that returns a list that I loop thru to build > tables and what not. > > My problem is that when heavier usage occurs the web server starts to > really bog down. It's almost like a slowly growing thing where it gets > slower and slower until it's unusable. It's not a problem with the > database because when the production web server is crawling I can > still use the development web server and everything is lightning fast. > When I look at the task manager the CPU is really pegged, jumping > around between 50% and 100%. > > Has anyone encountered this or does anyone have any thoughts? I > realize IIS/ASP isn't the optimum deployment environment but this is > killing me that vbscript app we had ran so much better. > > One question I have is the use of "del" and how important that is. I > was under the impression objects would get swept up when I exited the > function so I don't use "del" very often at all. Is it possible IIS is > somehow becoming less efficient because of this? > Are you using the 146/147 builds of win32all? There were a couple of ASP related memory leaks fixed in this version. Does the memory usage on the IIS server process show leakage? Mark. From hoel at germanlloyd.org Wed Jul 10 09:45:31 2002 From: hoel at germanlloyd.org (Berthold =?iso-8859-15?q?H=F6llmann?=) Date: 10 Jul 2002 15:45:31 +0200 Subject: Accessing Python from C++ Message-ID: Hello, I have to provide access a lot of Python classes with lots of methods from C++. Is there any tool that could help in this like boost, CXX, SWIG for the other way round? Thanks for your help Berthold -- Dipl.-Ing. Berthold H?llmann __ Address: hoel at germanlloyd.org G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 32/35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From tim.one at comcast.net Sat Jul 27 01:46:37 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 27 Jul 2002 01:46:37 -0400 Subject: extract elements of n char from a list In-Reply-To: Message-ID: [Fernando Perez, on the mysteries of time.clock() and Tim's use of "user" time in a Cookbook chapter intro] > Ahh, the beauty of vague standards :) At least POSIX doesn't contradict the C std in this area, which latter says just as little about it. > Anyway, I thoroughly enjoyed your description and it was as I > said a minor point, slightly worthy of mention. It wasn't really > misleading at all, it's just that I was sensitive to the point > because of having spent the afternoon yesterday writing 4 different > clock functions as an extension module to distinguish between system > and user time. That's very gracious of you, but if I could, I'd reword it. Your point was well taken! "User time" will have a particular meaning to many readers that I didn't intend in that sense -- I should have stuck with a vague "process time". > The book looks very nice, btw. Good job, I just got the Cookbook yesterday, and it *does* look good! I believe we can primarily thank Alex Martelli for that -- from what I saw, he put an enormous amount of work into organizing, cleaning and improving the content. In fact, I wouldn't be suprised to learn that he wrote all the chapter intros too . From jepler at unpythonic.net Mon Jul 8 14:05:12 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Jul 2002 13:05:12 -0500 Subject: Python 2.1 == Jython 2.1 != Python 2.2? In-Reply-To: <1026148476.6903.11.camel@walter> References: <1026148476.6903.11.camel@walter> Message-ID: <20020708180505.GB1605@unpythonic.net> On Mon, Jul 08, 2002 at 06:14:36PM +0100, Graham Ashton wrote: > But can you really infer that Laura didn't get it, simply because she > answered an earlier poster's question? no, but he can sure imply it. Jeff From barry at zope.com Mon Jul 8 16:03:58 2002 From: barry at zope.com (Barry A. Warsaw) Date: Mon, 8 Jul 2002 16:03:58 -0400 Subject: New Persistence SIG created Message-ID: <15657.61486.222685.665859@anthem.wooz.org> As recently discussed on meta-sig at python.org, we have created a new SIG focussed on producing a common persistence and transactional framework for Python programs. This SIG is called persistence-sig at python.org. For more information on the SIG, its mission, and deadlines see http://www.python.org/sigs/persistence-sig/ To join the mailing list see http://mail.python.org/mailman-21/listinfo/persistence-sig -Barry From jb at cascade-sys.com Wed Jul 31 16:16:05 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 31 Jul 2002 13:16:05 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitete ch.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <3D475AB5.2060207@nowhere.org> <1028096804.836.1812.camel@lothlorien.colorstudy.net> <3D47B936.1AFA8DB8@cascade-sys.com> <1028133358.578.3668.camel@lothlorien.colorstudy.net> Message-ID: <3D484585.448736C1@cascade-sys.com> Ian Bicking wrote: > Well, it looks a lot like lambda calculus, because True and False are > two different classes, with definitions like: > This should remind one of true/false in lambda calculus (though > obviously with a very different notation). Narrowly interpreted, there is a similarity, in that both systems build up their "control flow" abstractions from True and False, as opposed to, say, COND. Further, they both define True and False in terms of each language's fundamental abstraction mechanism, class definitions in Smalltalk's case and and Lambda expressions for Lambda Calculus. However, the notations and the underlying abstractions are so vastly different I find it hard to view them as anything but largely unrelated. But maybe I'll feel differently tomorrow. > The compiler specifically looks for those > methods, and turns them into traditional if statements in the bytecode. This is simply an optimization for speed. Most compilers also handle special cases for small integer arithmetic. Even newer ones compile direct to machine code instead of byte codes. These compiler optimizations are completely optional. They have nothing to do with the language design and certainly have absolutely nothing to do with any purported difficulties implementing Lambda or Smalltalk control structures. If there's a weakness in the Language, it's that the fully general hash table lookup for each and every operation (including small integer arithmetic and trivial control structures) is extremely expensive and an obvious hot spot to try to optimize. > That is, you can't (usefully) implement ifTrue: in your own custom > class. Absolutely not true. You can implement like methods in your own classes and it will work just fine. Key is that Smalltalk's block construct allows passing in as an argument unevaluated chunks of code, which the method itself controls if/when to execute. The compiler will recognize that the destination+method is not one of the patterns it knows how to optimize so it will generate a fully general message send. Ultimately your object will get the ifTrue: message with it's block argument and you can evaluate the block or not, depending on the instance's local state or whatever. E.g., you define a method for your class by a method that does a three-way branch: ifZero: z ifGreater: g ifLesser: s ( state > 0 ) ifTrue: [ ^g value ] ( state < 0 ) ifFalse: [ ^s value ] ^z value To call it: myStateObj ifZero: [ zero block ] ifGreater: [ greater block ] ifLesser: [lesser block ] You could even extend Numbers themselves to have this new control flow construct. Smalltalk's blocks ARE the language's Lambda equivalent, they work quite well, and they're implemented fully generally at the user level. They're one source of the language's incredible flexibility and power. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From jb at cascade-sys.com Tue Jul 23 17:38:05 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 23 Jul 2002 14:38:05 -0700 Subject: good books -- Python Essential Reference by David Beazley References: <20020723133309.A20383@lifebook> Message-ID: <3D3DCCBD.FEBE7086@cascade-sys.com> DIG wrote: > > If you want a book with a long shelf life, many including myself, > > recommend Python Essential Reference by David Beazley. > > I agree with that. Me too. IIRC, there's a 2nd edition just out. --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From wyojustin at hotmail.com Sat Jul 20 01:28:00 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Sat, 20 Jul 2002 05:28:00 GMT Subject: TypeError: unbound method...expected one instance, got another References: Message-ID: Hmmm, I can't repeat your error: # module1.py class Super: def __init__(self): self.a = 'string1' # module2.py import module1 class Mid(module1.Super): def __init__(self): self.b = 'string2' module1.Super.__init__(self) class Sub(Mid): def __init__(self): self.c = 'string3' Mid.__init__(self) # junk.py import module2 mid = module2.Mid() print 'module2.Mid().a', mid.a sub = module2.Sub() print 'module2.Sub().a', mid.a c:\Python\Python22> junk.py module2.Mid().a string1 module2.Sub().a string1 Did you remember to "import moudle1" in module2? Justin "David" wrote in message news:ah7ii3$atg$1 at slb3.atl.mindspring.net... > I have created a hierarchy of classes, and I am receiving an error that I > have not been able to figure out. The error message (in Python 2.2) is: > "TypeError: unbound method __init__() must be called with Super instance as > first argument (got Sub instance instead)". > > My situation is that I have three classes in a hierarchy, with the Super > living in a different module than the Mid and the Sub, as follows: > > module1.class Super: > def __init__(self): > self.a = 'string1' > > module2.class Mid(module1.Super): > def __init__(self): > self.b = 'string2' > module1.Super.__init__(self) > > module2.class Sub(Mid): > def __init__(self): > self.c = 'string3' > Mid.__init__(self) > > The curious thing to me (a newbie) is that sometimes instantiation of Sub() > works and sometimes it doesn't, depending on how I attempt it. If I am at > the interactive prompt, instantiation works (except in a special case, which > I'll come to). In other words, if I am at the interactive prompt, I am able > to create an instance of Sub() that includes the 'a' attribute from Super. > If, however, I try to create the instance in a script, I encounter the > TypeError when I run the script. If, after encountering the TypeError, I > return to the interactive prompt and again try to create an instance of Sub, > I again encounter the TypError (this is the special case). I continue to > get the error until such time as I reload module2, after which I am back > where I started, i.e., able to create an instance of Sub from the > interactive prompt but not from my script. > > I feel like I'm misunderstanding something... but can't figure out what it > is. Any insight or help would be appreciated. Thanks, > > David > > From loredo at astro.cornell.edu Fri Jul 19 14:28:22 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Fri, 19 Jul 2002 14:28:22 -0400 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <190720021018041866%pecora@anvil.nrl.navy.mil> Message-ID: <3D385A46.6DC47857@astro.cornell.edu> "Louis M. Pecora" wrote: > > Many people have suggested doing something like the following (which is > reasonable) to eliminate self. from mathematical expressions: > > t, x, y, z=self.t, self.x, self.y, self.z > result=sin(t)*x**y+sqrt(z) # A pretend formula Yes, this was suggested earlier. I don't consider it a great solution to the problem. For example, in a current calculation I have a class with many member variables and many member functions that use them to return various quantities. In a language that boasts of how simple and straightforward it is, and how it shrinks code size (by omitting braces, declarations, etc.), it is rather silly to have lines like: t, x, y, z=self.t, self.x, self.y, self.z in every one of many member functions, often with the same variables. You look at that code, with all those redundant lines of negligible content, and it yells out to you: something is missing here that should make this silly copying unnecessary in order to have expressions that are easy to read/understand. The language is so great in other respects, and on a fundamental level the arguments for "self." are so sound, that I just live with this. But it sure is a nuisance. -Tom Loredo From Gabe.Newcomb at noetix.com Thu Jul 18 18:33:47 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Thu, 18 Jul 2002 15:33:47 -0700 Subject: Tkinter vs. wxPython Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F60C8@NOXMAIL.noetixad.com> Thanks to all who've responded. I see now that this has been brought up a number of times before (thank you Google Groups) and I'll be better about checking on that next time. Thanks all Gabe -----Original Message----- From: Peter Hansen [mailto:peter at engcorp.com] Sent: Thursday, July 18, 2002 3:18 PM To: python-list at python.org Subject: Re: Tkinter vs. wxPython Gabe Newcomb wrote: > > I've been trying to get into wxPython, but I'm finding the lack > of documentation difficult. There's some, and I'm very grateful for > everybody who's contributed it, but I'm somebody who really likes having > a decent reference and more examples. Do you mean more examples than the massive demo program for wxPython? I don't think I've found almost anything not covered by something in that code yet. > My question is this: is there any compelling reason I shouldn't just go > with Tkinter instead? I work (for now) exclusively on Win32 boxes, by > the way. I switched to wxPython for reasons which were, to me, compelling, but they simply related to my failure to get acceptable looking and performing results under Tkinter. Note I said it was my failure, not Tkinter's... -Peter -- http://mail.python.org/mailman/listinfo/python-list From raims at dot.com Mon Jul 29 06:01:55 2002 From: raims at dot.com (Rhymes) Date: Mon, 29 Jul 2002 12:01:55 +0200 Subject: [ZOPE] Zope, Python, Win2k and Mysql Message-ID: <4a4akukkfg92po76t3svc7flen29s3stui@4ax.com> I've just installed Zope 2.5.1 on my windows box (Win2k Pro) but it's built on top its own python version (2.1). During the day I use Py 2.2.1 and when i tried to install the mysql-bindings (ZMySQLDA) for Zope a problem raises itself. In the Zope-Ctrl-Panel there is this error: Traceback (most recent call last): File "C:\PROGRA~1\WEBSITE\lib\python\OFS\Application.py", line 531, in import_product product=__import__(pname, global_dict, global_dict, silly) File "C:\PROGRA~1\WEBSITE\lib\python\Products\ZMySQLDA\__init__.py", line 91, in ? import DA File "C:\PROGRA~1\WEBSITE\lib\python\Products\ZMySQLDA\DA.py", line 92, in ? from db import DB File "C:\PROGRA~1\WEBSITE\lib\python\Products\ZMySQLDA\db.py", line 89, in ? import _mysql ImportError: Module use of python22.dll conflicts with this version of Python. what can i do now? -- Rhymes (rhymes at myself.com) http://www26.brinkster.com/rhymes " ride or die " From lac at strakt.com Thu Jul 11 08:47:12 2002 From: lac at strakt.com (Laura Creighton) Date: Thu, 11 Jul 2002 14:47:12 +0200 Subject: Python in the enterprise: Pros and cons In-Reply-To: Message from Kim Petersen of "Thu, 11 Jul 2002 10:21:29 +0200." <3D2D4008.7050207@kyborg.dk> References: <3D2D4008.7050207@kyborg.dk> Message-ID: <200207111247.g6BClCci026363@ratthing-b246.strakt.com> Kim Petersen: > > Learning Python is straight forward, and doesn't scare of a COBOL > programmer in the way that C++ or Java would. > Is getting a float when they wanted a fixed-decimal a problem? Laura Creighton From mike at bindkey.com Fri Jul 26 14:08:52 2002 From: mike at bindkey.com (Mike Rovner) Date: Fri, 26 Jul 2002 11:08:52 -0700 Subject: str() inconsistency References: Message-ID: Thank you, Mark. Both posts are up to the point. Fortunately, since 2.2 we can do: >>> class L(list): ... def __repr__(self): return '' ... def __str__(self): return '[%s]' % ', '.join([str(i) for i in self]) ... >>> l=L([1,2,3,4.1]) >>> l >>> print l [1, 2, 3, 4.1] >>> print [1,2,3,4.1] [1, 2, 3, 4.0999999999999996] And even: >>> list=L >>> [1.1] [1.1000000000000001] >>> list([1.1]) >>> print list([1.1]) [1.1] Unfortunately GvR consern remains: >>> print list([1, '1', '2, 3', '], [']) [1, 1, 2, 3, ], [] Sincerely, Mike "Mark McEahern" wrote in message news:JHEOKEOOLIGLDHCMAHMOCEHODDAA.marklists at mceahern.com... > [Mike Rovner] > > Why it's not a bug: > > > > >>> 4.4 > > 4.4000000000000004 > > >>> `4.4` > > '4.4000000000000004' > > >>> str(4.4) > > '4.4' > > >>> str([4.4]) > > '[4.4000000000000004]' > > > > IMHO, str() shall call str, not repr on complex objects. > > Apparently, this topic comes up from time to time. I was trying to find the > most recent post from Tim Peters on this (sometime in the last two weeks, I > believe). It may be somewhere in the results of this search: > > > http://groups.google.com/groups?as_q=str%20repr%20list%20bug&as_ugroup=comp. > lang.python > > I did find this one from October 2000: > > > http://groups.google.com/groups?selm=mailman.971929189.1785.python-list%40py > thon.org > > as well as Guido's post on this topic from November 1999: > > > http://groups.google.com/groups?selm=5lln8ht38a.fsf%40eric.cnri.reston.va.us > > // mark > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jonathan at onegoodidea.com Tue Jul 2 03:41:26 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 02 Jul 2002 08:41:26 +0100 Subject: Performance question about math operations References: Message-ID: On 2/7/2002 7:00, in article mailman.1025589663.1583.python-list at python.org, "Andrew P. Lentvorski" wrote: > I have a VLSI layout editor written in Python. At its core, it has to > redraw a lot of polygons. This requires a lot of coordinate conversion > mathematics. Essentially the following loop: Could you post the actual code, or is it too long/proprietary? How are all the magic numbers arrived at? Does it really look as simple as you suggested? > What is eating all that time? And can I do anything about it? Try disassembling the loop: >>> def foo( n ): ... i = 0 ... while i < 100000: ... i = i + 1 ... >>> import dis >>> dis.dis( foo ) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 (0) 9 STORE_FAST 1 (i) [...] You could look out for LOAD_GLOBAL instructions which are expensive. Another thread here recently discussed why and a couple of methods of speeding them up. If it turns out that your loop is as fast as it's going to get, your best bet is to convert it to C instead. You can do this by writing an extension module. There's some documentation on the Python website that should get you started on writing extension modules. Jonathan From ulbi at ivs.tu-berlin.de Wed Jul 24 05:14:36 2002 From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich) Date: Wed, 24 Jul 2002 11:14:36 +0200 Subject: Jython: any workaround for the missing array module References: <20f81d64.0207221651.6d57a39@posting.google.com> <3D3D2A29.7000906@ivs.tu-berlin.de> Message-ID: <3D3E6FFC.9000805@ivs.tu-berlin.de> Philip Tsai wrote: > Right; jarray, however, only exposes two methods while the array module > provides a number of useful methods. > > In my case, I have a (c)python class that manipulates an array of bits using > array.array('I') structure. The class uses several array methods such as > tostring() and fromstring(), which do not seem trivial to re-implement in > python or jython.... Would you have any suggestion on how to implement such > array methods (I guss at the end there is always the approach of looking > into the source code and try to port it...)? Are the Java-classes in java.util of any help? Especially Arrays, ArrayList and so on are worth looking into. They might already provide what you are looking for. Implementing tostring and fromstring is not all that difficult in many cases anyway using the string class, list comprehension and so on Hope that helps. From whisper at oz.net Tue Jul 2 15:44:42 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 2 Jul 2002 12:44:42 -0700 Subject: Python needs better error reporting In-Reply-To: <25nU8.46033$n4.10990753@newsc.telia.net> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Fredrik Lundh > Sent: Tuesday, July 02, 2002 12:24 > To: python-list at python.org > Subject: Re: Python needs better error reporting > > > Hans-Joachim Widmaier wrote: > > > Instead of listing all the legitimate tokens that may follow, why not > > just give something like "Incomplete 'if' statement?" > > of course, if you bother to read the *entire* error message, > that's not too far from what it says today: > > File "", line 1 > if s == "" > ^ > SyntaxError: invalid syntax > > (and the fact that your typical Python autoindenter > refuses to indent the next line if you leave out the > colon may also help; I usually discover mistakes like > this long before I run the code...) > > Except that everything to the left of the circumflex is syntactically correct. Dave LeBlanc Seattle, WA USA From astrophels at yahoo.com Fri Jul 12 02:42:54 2002 From: astrophels at yahoo.com (Micah Mayo) Date: Fri, 12 Jul 2002 06:42:54 GMT Subject: Python for data driven website? References: <3D2E51A0.730F521A@engcorp.com> Message-ID: > > You don't need to say any more than that to elicit the correct answer > at this point, which is "what are your requirements?". > > You need to get a handle on what you actually need to accomplish, > not just go on a wild search for cool technologies. You've > implicitly identified that you are uncomfortable with the restrictions > of some proprietary products from certain largish companies, so one > can infer one of your requirements is something like open or free licensing. True > What else? What kind of performance do you need? Reliability? > Scalability? Ease of development or maintenance? Prior experience > in the technology by existing developers? > Definatly reliabilty/scalability. We expect anywhere from 100-1000 customers, which may or may not translate into multiple users per account. Whatever we use need to be able to handle a gradual, or steep for that matter, rise in use. I didn't mean to sound as if we were just looking for cool technology. We have three person team. One older developer who has years of experience with database programming, and two younger intermediates. Me being one of the younger guys. The older guy is teaching us the industry. The problem is almost all of his experience is with microsoft products. When he decided that microsoft was not able to provide an affordable solution, he started talking to us about a free/unix solution. Of the three of us I am the only one with any real experience with unix(when i was a luser teenager I thought I was cool because I ran FreeBSD as my desktop), so I am the only one who is really comfortable in this area. So, I get stuck with alot of research work of this sort. So, as far as the application goes - the software is going to be a service for tax firms available through the web only(unless a custom version is needed, which would cost a pretty penny). We have a preliminary version written in access, but it is far from done. We want to do this right the first time - we expect to spend a year working on it.So scalability is a must, as well as general reliability. We want the design to allow change of content without having to rewrite the front-end at all, and minimal changes in the backend(i.e. data driven). In other words, we want to write the website once, and have the database decide, based on user settings, what content will be displayed. We'll have a set of tables as a template, and inside those tables the content could vary greatly depending on the particular customer. So, ASP.net would work. ASP would work(but it would be harder to code) and we believe PHP would be fine also. Again, my boss (the older guy who knows what he's doing, kind of ;) was reading a book on python and thought it might provide a better solution. Does that help? :) From mwh at python.net Wed Jul 3 10:02:39 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 3 Jul 2002 14:02:39 GMT Subject: Thread safetyness in Python References: Message-ID: John Goerzen writes: > Hi, > > I have some questions about what is thread-safe in Python. Can someone tell > me whether each of the following are thread-safe: I'm not a thread expert, but these are my answers: > 1. a = a + 1 No. a += 1 would be, though (I'm fairly sure). Assuming a.__add__ isn't written in Python... > 2. a = a + 2 No. a += 2, again. > 3. list.append(x) Yes. > 4. list.remove(x) Yes. > 5. del(list[0]) Yes. Cheers, M. -- Strangely enough I saw just such a beast at the grocery store last night. Starbucks sells Javachip. (It's ice cream, but that shouldn't be an obstacle for the Java marketing people.) -- Jeremy Hylton, 29 Apr 1997 From mark.charsley at REMOVE_THIS.radioscape.com Thu Jul 4 11:38:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Thu, 4 Jul 2002 16:38 +0100 (BST) Subject: Forward Declaring Py_complex References: <3VYU8.600843$Oa1.37637572@bin8.nnrp.aus1.giganews.com> Message-ID: In article <3VYU8.600843$Oa1.37637572 at bin8.nnrp.aus1.giganews.com>, tjreedy at udel.edu (Terry Reedy) wrote: > > "Mark Charsley" wrote in > message news:memo.20020704104527.604A at a.a... > ... > > for it, and don't treat it as a syntax error" then I can avoid > having to > > force all my class's clients from having to pull in a lot of header > files > > that most of them don't care about. This will have two benefits: > > 1) build times won't be hit by having to process unnecessary headers > for > > each cpp file > > 2) my workmates won't spend the next week moaning that I've broken > their > > build and asking which directories they have to put in their > project's > > include path to fix it. > > Given these desiderata, I would consider handcrafting a minimal > 'mypyplex.h' include with just the stuff needed, even knowing that it > might break and need editing for some future version of Python. Alas that doesn't work... MyClass.h includes MyPyPlex.h, which defines Py_Complex. MyClass.cpp includes MyClass.h and Python.h which also defines PyComplex My compiler complains about multiple definitions of PyComplex. How does one go about putting in a Change Request/PEP/whatever asking for ComplexObject.h to be changed so that Py_Complex can be forward declared. My C (with no ++ at all) skills are a little rusty, but I think changing typedef struct { double real; double imag; } Py_complex; to either typedef struct TAG_Py_complex { double real; double imag; } Py_complex; or failing that #ifdef __cplusplus struct { double real; double imag; } Py_complex; #else typedef struct { double real; double imag; } Py_complex; #endif would solve the problem. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From mwh at python.net Wed Jul 24 07:16:28 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 24 Jul 2002 11:16:28 GMT Subject: cmd, readline, and /path/filename completion References: Message-ID: Dave Cinege writes: > Dunno much about programming readline, so maybe this is obvious. > > I toying with a unix shell written in python using shlex and cmd. > (For now based on the _Python 2.1 Bible_ lextocon example...) > > It's actually quite functional at this point. (Though replacing > bash with it, doesn't quite work yet... ) > > I'm trying to tweak the readline functionality, and am a bit lost. > > In Bash > cd /etc/ > Will display a list of files in /etc/ to complete against. > > In my shell, I will always see the files in the current directory. > > What must be done to mimic the bash functionaly? Is it an option that > must be turned on in readline? Do I have to snag the line, and if it is a > valid path, cd to that path? (then back to PWD) I'm guessing that you need to fiddle what characters readline thinks are word boundaries. readline.set_completer_delims looks hopeful. Cheers, M. -- Gullible editorial staff continues to post links to any and all articles that vaguely criticize Linux in any way. -- Reason #4 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From logiplexsoftware at earthlink.net Wed Jul 3 14:06:07 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 11:06:07 -0700 Subject: HT clear some wxPython fram? In-Reply-To: References: Message-ID: <20020703110607.00c02458.logiplexsoftware@earthlink.net> On Wed, 03 Jul 2002 19:39:04 +0200 Klaus Reinhardt wrote: > >> HOW I CAN CLEAR SOME FRAME? > --------------------------------------------------------------------- > Hi > > >My problem is, that the I want to monitor netstat; this > >is in principle working (s.b.). But I don't want the scrolling > >frame for 2 reasons. > > 1.) ergonomic > > 2.) after a while of outputting the display > > is stopping, I think for memory-reaons. > > I can use Clear here: > > class MyApp(wxApp): > def OnInit(self): > frame = MyFrame(self.stdioWin) > frame.Show(TRUE) > frame.Clear() #### OK, but sensless > self.SetTopWindow(frame) > But I want to clear the frame just bevor each new output > is given here: > > class MyFrame(wxFrame): > .. > def OnTimer(self, evt > y=os.popen( 'netstat -a -n','r').read() > ############# HERE > print "--------------------------------------------------------------" > yy=y.splitlines() > for i in yy: > if i[:5]==" TCP": > ry=string.split(i) > print "%5s %22s %22s %22s" % (ry[0],ry[1],ry[2],ry[3]) What do you want to clear from the frame? You've put nothing into it. I think you are confusing the stdout window with the frame. If you notice, when you run your program, two windows open. The first one with the title "Close me" is the frame. The second window titled "wxPython stdout/stderr" is not the frame. I could be wrong, but I don't think there's any way to control the stdout/stderr window. It's mostly for debugging purposes. What you will want to do instead is something more like this: from wxPython.wx import * class MyPanel(wxPanel): def __init__(self, parent): wxPanel.__init__(self, parent, -1) self.SetBackgroundColour(wxWHITE) self.text = [] EVT_PAINT(self, self.OnPaint) def OnPaint(self, event): dc = wxPaintDC(self) self.draw(dc) def write(self, text): self.text.append(text) if len(self.text) > 10: del self.text[0] dc = wxClientDC(self) self.draw(dc) def draw(self, dc): dc.Clear() y = 0 for t in self.text: dc.DrawText(t, 0, y) y += 15 class MyFrame(wxFrame): def __init__(self): wxFrame.__init__(self, None, -1, "MyFrame") self.panel = MyPanel(self) self.timer = wxTimer(self, -1) self.timer.Start(100) EVT_TIMER(self, -1, self.OnTimer) def OnTimer(self, evt): self.panel.write("hello") def OnClose(self,event): self.timer.Stop() self.Destroy() class MyApp(wxApp): def OnInit(self): frame = MyFrame() frame.Show(true) return true app = MyApp() app.MainLoop() Please realize that the apparent complexity of something so simple has more to do with the nature of GUI programming than with Python. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From rnd at onego.ru Tue Jul 30 07:30:23 2002 From: rnd at onego.ru (Roman Suzi) Date: Tue, 30 Jul 2002 15:30:23 +0400 (MSD) Subject: re question (perhaps a stupid misunderstanding of regex-logic) In-Reply-To: <20020730125303.GA2149@blackscarab> Message-ID: On Tue, 30 Jul 2002, Stefan Antoni wrote: > > i am currently reading Jeffrey E. F. Friedl's book about regex'es, and i > must admit that i play more with the re-module then reading further on > ;) > > thats why i ask the following question: > > i made the following regex: > m = re.compile("[^M]*") > > i think, it would be read as: "find everything except the occurences of > the char 'M' " . > i wrote the following code: > > all = string.letters + string.digits + string.hexdigits + \ > string.whitespace > > M = re.compile("[^M]*") > M.findall(all) > ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL', '', \ > 'NOPQRSTUVWXYZ01234567890123456789abcdefABCDEF\t\n\x0b\x0c\r ', ''] > > this gives me a list with an empty item at [1] of the list. > the documentation says: "findall: Find all occurrences of a > pattern in a string." > > since the ^M is a negated char (german "negiert", i don't know if negated is > right), the regex-object shouldn't give me an list-item for this match, or should > it? > > what am i missing? That "[^M]*" matches empty string. Use "[^M]+" to match 1 or more characters. > thx in advance, > > Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From spam at ob_scure.dk Sun Jul 7 06:41:39 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 12:41:39 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> Message-ID: <3D281AE3.3070800@ob_scure.dk> Anders Dahlberg wrote: [snip] > Why not consider using jython? > Same scripting as python, better scaling to multiple cpu's - seems atleast > to me as an easier solution than xml-rpc? Does it also scale well to multiple machines? If so, do you have any links to information regarding this? > (maybe it's easier to sell the idea to your boss too, due to java-hype and > all ;) That might be a point :-) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From nospam at here Sat Jul 20 10:41:29 2002 From: nospam at here (Richard Townsend) Date: Sat, 20 Jul 2002 15:41:29 +0100 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: <1027175934.94979.0@iris.uk.clara.net> "Rhymes" wrote in message news:8r1hjuk58o67amhuvfna5htpe2gtl3gnlr at 4ax.com... > > When Python 2.3 will be released? > Also, is there likely to be a 2.2.2 ? From mayer at acm.org Tue Jul 2 16:40:47 2002 From: mayer at acm.org (Robert George Mayer) Date: Tue, 02 Jul 2002 14:40:47 -0600 Subject: python decimal infection? References: Message-ID: <3D220FCF.F3C4B9BC@acm.org> Thinkit wrote: > > How much has the cancer known as decimal infected python? Decimal is evil. Thinkit - Too obvious, see: www.altairiv.demon.co.uk/troll/trollfaq.html For the others, try entering "Thinkit" in Google Groups, go to the last page, e.g. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=cf80a174.0111291400.41cfcf4c%40posting.google.com&rnum=14&prev=/groups%3Fq%3DThinkit%26hl%3Den%26lr%3D%26ie%3DUTF-8%26start%3D10%26sa%3DN - BOB From chris.gonnerman at newcenturycomputers.net Thu Jul 11 19:52:19 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 11 Jul 2002 18:52:19 -0500 Subject: Open document formats References: Message-ID: <004f01c22935$ffe1f880$0101010a@local> ----- Original Message ----- From: "David LeBlanc" > AFAIK, Windows still does not have "postscript drivers" unless you have a > driver for a postscript printer supplied by the printer vendor. Those are > typically HP Laserjets with a postcript engine built-in. 0123456789----------0123456789----------0123456789----------0123456789 I'm not sure I know what you are talking about. Windows 3.0 came with a dual UNIDRV/PSCRIPT system (dot matrix and PCL printers used the UNIDRV, while PostScript printers used PSCRIPT). In 3.1 this was improved quite a bit, with the PSCRIPT driver supporting PPD files (more or less). I haven't used the manufacturer's driver add-on on a PS printer in a long time; the built-in driver included with Win95 and higher is about as good as the OS itself (i.e. doesn't stink too bad if you cover your nose). > I have not seen, but have wanted and looked for, a "postscript to random > printer" driver for a long time. Ghostscript comes closest, but it's not > quite the same as a built-in driver. I use GhostScript and RedMon together with an old Tcl/Tk script on Windows and Linux to run my outbound fax service. (note RedMon only on Windows.) The fax server uses the efax package, which uses GhostScript to render fax pages. So, on Linux: application -> tksendfax -> lpr queue -> efax -> GhostScript On Windows it's like this: application -> RedMon -> tksendfax -> Samba -> lpr queue \ -> efax -> GhostScript Sounds pretty nasty when I stretch it out like that, but it's been working well for me for two or three years. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net > David LeBlanc > Seattle, WA USA > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of Cameron Laird > > Sent: Thursday, July 11, 2002 6:07 > > To: python-list at python.org > > Subject: Re: Open document formats > > > > > > In article , > > David Mertz, Ph.D. wrote: > > . > > . > > . > > >As far as I know, every OS, since maybe 1985, has had drivers for > > >postscript printing. Almost all the applications that do not use OS > > Well, wasn't Windows itself holding out > > against PS for a long time? OK, I'm not > > motivated enough to research this myself > > just now ... > > . > > . > > . > > -- > > > > Cameron Laird > > Business: http://www.Phaseit.net > > Personal: http://starbase.neosoft.com/~claird/home.html > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From cliechti at gmx.net Sun Jul 7 16:50:56 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Jul 2002 22:50:56 +0200 Subject: make cvs pserver/ssh(2) connection with python References: <20020707.223646.680466996.4043@tu-bs.de> Message-ID: [posted and mailed] "Marc" wrote in news:20020707.223646.680466996.4043 at tu-bs.de: > I am searching a way to make a cvs pserver or/and a ssh(protocol > Version 2) connection with python under Linux/Unix. I've tried to > control the cvs pserver > connection by a python frontend which uses the normal cvs binary, but > it won't work without using the 'normal console interaction' for input > (maintainly the cvs login). > I can get the inputstream, but I can't write correctly to the > outputstream. I get the password query, but the answer fails. > Perhaps someone have experience in writing a frontend for interactive > programms under Linux/Unix and can help me. do you use popen? something like that: >>> i,o = os.popen2("cat - >tmp") >>> i.write("hello") >>> i.close() >>> o.close() $ ls tmp $ cat tmp hello HTH, if not, please include a short example of what you did. chris -- Chris From barnaby.dalton at radioscape.com Thu Jul 18 11:04:48 2002 From: barnaby.dalton at radioscape.com (Barney Dalton) Date: Thu, 18 Jul 2002 16:04:48 +0100 Subject: python-mode - running a script that takes command line arguments Message-ID: <3D36D910.6010102@radioscape.com> How do I run a python script that takes command line arguments from within emacs python mode? C-cC-c and C-c RET don't seem to have an option for passing arguments. thanks Barney From robert_kuzelj at yahoo.com Tue Jul 2 18:06:17 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 2 Jul 2002 15:06:17 -0700 Subject: "my brain hurts" or is isinstance broken? Message-ID: hi, after playing around with all this metastuff it seems that isinstance is broken (but after all it could also be, that my brain finally broke down). here some script that checks for the instancetype of various objects defined within that script. >>>typestest.py import types import string class metatype(type): pass class A1: pass class B1(object): pass class C1: __metaclass__ = metatype values = [ [A1, A1()], [B1, B1()], [C1, C1()]] def getInstanceInfos(row): return [row[0].__name__, str(isinstance(row[0], types.InstanceType)), str(isinstance(row[0], types.ClassType)), str(isinstance(row[0], types.TypeType)), str(isinstance(row[1], types.InstanceType)), str(isinstance(row[1], types.ClassType)), str(isinstance(row[1], types.TypeType))] print print "INSTANCEINFOS" print " name | inst | class | type | inst | class | type " print "-----------------------------------------------------" for row in values: print " " + string.join(getInstanceInfos(row), " | ") >>>typestest.py #end >>>output INSTANCEINFOS name | inst | class | type | inst | class | type ----------------------------------------------------- A1 | 0 | 1 | 0 | 1 | 0 | 0 B1 | 0 | 0 | 1 | 0 | 0 | 0 C1 | 0 | 0 | 1 | 0 | 0 | 0 >>>output my question is why are the B1() and C1() not types.InstanceType? and if this is not a bug - of what type are B1() and C1()? ciao robertj From sholden at holdenweb.com Sat Jul 27 00:28:33 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:28:33 -0400 Subject: automating control-D References: Message-ID: "Victor Chen" wrote in message news:mailman.1027708758.17684.python-list at python.org... > Hi, > I'm fairly new a python stuff, working on my first python script. > I was wondering if anyone knows how I can represent > control-D as output using python. Firstly, I do not know > the special string used to represent the control key and secondly, I > would have to automate both the control and the d characters > be pressed together. Any help is appreciated. Thank you. In Python such characters are best represented as octal or hexadecimal escapes. Since the ordinal value of ^D is 4, you could use either "\004" or "\x04" to represent the character. Your parting shot, however, makes it appear that you are perhaps thinking of creating input to some other program. If this is indeed the case, you should be aware that if you are using conventional means such as pipes to communicate with another program then you shouldn't send a "^D" character, but instead simply close the file you are using to send data to the other program. When you enter "^D" in a Unix terminal input this is tasken (by the tty handler) to indicate end of input. If no readabl;e characters preceded this condition since the last read, this is taken as indicating end of file. On the third hand, if you want to have a Python program simulate keyboard input to a whole operating system (which you might, since you talk about pressing keys to create keystrokes), this is a couple of orders of magnitude more complex. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From gerhard.haering at gmx.de Sat Jul 20 16:46:33 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 20 Jul 2002 22:46:33 +0200 Subject: unloading imported modules In-Reply-To: References: Message-ID: <20020720204633.GA5735@lilith.my-fqdn.de> * Fran?ois Pinard [2002-07-20 16:26 -0400]: > [Alex Martelli] > > > xeon wrote: > > > > Is it possible in python intepreter to unload imported modules? or are > > > No. > > Hello, Alex. > > Suppose we reload, and reload and reload the same module, are the > previous copies freed from memory? The previous copies of what? As everything is an object in Python, whatever was in the module gets garbage collected as soon as all references to it are gone. Maybe an example can demonstrate where and why this happens: >>> import foo >>> x = foo.Foo() >>> x.__class__ >>> [1]+ Stopped python gerhard at lilith:/tmp$ vim foo.py [slightly change foo.Foo here] gerhard at lilith:/tmp$ fg python >>> reload(foo) >>> y = foo.Foo() >>> y.__class__ >>> del x # <--- Here the old foo.Foo class gets garbage-collected >>> # as the last reference to it will go away with x Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From doru-cat at ifi.uio.no Fri Jul 12 05:43:54 2002 From: doru-cat at ifi.uio.no (Doru-Catalin Togea) Date: Fri, 12 Jul 2002 11:43:54 +0200 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: Hei! There has come a lot of insight so far on this thread, pros and cons. That's good for those of us who have not yet thought things through. > It is -- easily. My pet peeve is the idea of using XML files for > tasks that obviously need a real database, preferably a relational one. > > I think some people never really GOT relational databases, no matter > that they've been around for decades and are so widespread, and they're > now turning to *overusing* XML to cover up for that:-). Personal experience: I tried once to install MySql on my Windows ME laptop, to use it to store the contents of a website I am working with. I found the process cumbersome. Even though I am working on my masters degree in computer science, I prefer to USE computers for specific tasks, rather then configure utilities. I appreciate very much tools where I can concentrate on PRODUCING something with them, rather then learning how to make them work the way I want. Unfortunately, in my experience, freeware needs a lot of configuration in order to work properly, and the documentation is often inaccurate. I would like to use Linux (and I tried several times) but I am not willing to put that much effort into configuring it as I had to. It seems that there is no driver for my video card (Savaga S3, 3D, tv-out) for Windows 2000 or XP, so I am stuck with Win ME. (I can run win 2000 with a generic screen driver which gives me max. 800x600) I could mention other difficulties I encoutered as I tried to somehow configure my system to cover all my needs, by trying several OSs and corresponding tools, but in order to make a long story short, I am still working in win ME and I store the contents of my website in XML files. Not by choice but by need. But I'm hoping for better days. Catalin <<<< ================================== >>>> << We are what we repeatedly do. >> << Excellence, therefore, is not an act >> << but a habit. >> <<<< ================================== >>>> From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 19:33:44 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 16:33:44 -0700 Subject: performance problem in python 2.2 References: <7xn0sedslz.fsf@ruckus.brouhaha.com> Message-ID: <7x8z3y12uf.fsf@ruckus.brouhaha.com> Fernando Perez writes: > The fact that one may spend a year's worth of cpu in computing an > expression for which an analytic solution exists is orthogonal to > the point I was making. It's a different point, yes, but related. Point 1, rather than bend backwards trying to optimize Python or Perl, write cpu-intensive code in a language that's closer to the machine. Point 2, rather than bending backwards writing efficient cpu-intensive code, look for a non-cpu-intensive way to solve your problem. From gerhard.haering at gmx.de Tue Jul 2 22:11:05 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 3 Jul 2002 04:11:05 +0200 Subject: what can i expect... In-Reply-To: <3D225A39.6070400@houston.rr.com> References: <3D225A39.6070400@houston.rr.com> Message-ID: <20020703021105.GA3220@lilith.my-fqdn.de> * Rod Haper [2002-07-03 01:58 +0000]: > +----------------------------------+ > | There is a better way ... | > | LAP => Linux + Ada95 + Python | > +----------------------------------+ Tried combining the three, yet? How did it go? Gerhard, who favours FAPP (FreeBSD/Apache/PostgreSQL/Python) over LAMP. -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From tim at bladerman.com Sat Jul 27 09:19:46 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sat, 27 Jul 2002 13:19:46 GMT Subject: Guide to the python interp. source? References: Message-ID: "Neil Schemenauer" > Tim Gahnstr?m /Bladerman wrote: > > Is there a guide or a recomended way to "get to know" the source code to the > > python interpreter? > > Not that I know of. Here are a few pointers: > > * Python/ceval.c:eval_frame is the heart of the virtual machine. This > is were most of the work is done. Use the 'dis' module to There I guess I will spend most of my coming days :-) > disassemble bytecode to get an idea of how the VM works. For > example: That was interesting, definitley a feature I must look at a little. > * The data structures in Include/object.h are key. You should > study PyObject, PyVarObject and PyTypeObject. Maybe there I can find a cheap way to make everything mutable. > > * Most builtin objects live in the 'Objects' directory. There is > * The parser lives in 'Parser' and the compiler is in 'Python'. I Thanks alot. It is fasignating how many people wanted to help out! Tim From marklists at mceahern.com Fri Jul 5 15:24:14 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 5 Jul 2002 14:24:14 -0500 Subject: shallow copy's In-Reply-To: Message-ID: > a = [1,2,3,4] > b = a > > Do some operations on a > Will the contents of b mirror a? Or will b remain unchanged? Why not answer the question yourself? Welcome to the Joy of Python: $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> a = range(5) >>> b = a >>> a [0, 1, 2, 3, 4] >>> b [0, 1, 2, 3, 4] >>> b.append("foo") >>> a [0, 1, 2, 3, 4, 'foo'] >>> b [0, 1, 2, 3, 4, 'foo'] Does that answer your question? // m - From theller at python.net Mon Jul 1 06:09:21 2002 From: theller at python.net (Thomas Heller) Date: Mon, 1 Jul 2002 12:09:21 +0200 Subject: reloading modules References: <1FVT8.56956$xy.18941573@twister.socal.rr.com> Message-ID: "Jeff Davis" wrote in message news:1FVT8.56956$xy.18941573 at twister.socal.rr.com... > > It seems like it might be common to import a module (that may or may not > have already been loaded) and require that you get the newest version at > the time of the import. > > The way I see it, this requires 3 steps: > 1) build a table of the modification times of files that have been imported > 2) compare a file's modification time to the time stored in the table > 3) import the module if it doesn't exist in the table, do nothing if the > modification times are the same, and reload it if the modification times > are different. > > My question is: are the python developers planning on including such a > standard function at some furture time, or should I just plan on having my > own module for that? Or does a 3rd party one exist? > > Thanks, > Jeff I've posted a script doing this (and more) some time ago. Here's a pointer: http://groups.google.com/groups?selm=9t132f%24160s9n%241%40ID-59885.news.dfncis.de Thomas From peter at engcorp.com Fri Jul 19 09:47:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Jul 2002 09:47:24 -0400 Subject: HTML DOM parser? References: <3D378CE6.E670EDAD@engcorp.com> <7x3cugnydr.fsf@ruckus.brouhaha.com> Message-ID: <3D38186C.30BB1F03@engcorp.com> Paul Rubin wrote: > > Peter Hansen writes: > > My choice of www.nightsong.com was of course because that's the > > domain the OP posted from. I didn't stop to think someone might > > have a "www" subdomain which actually refused a connect request... > > strange if you ask me. > > www.nightsong.com doesn't refuse connect requests. It accepts > connections and sends back a valid HTTP 403 response indicating > there's no page available at "/" (e.g. no index.html at the document > root). If you use an interior URL like > it should work fine. My apologies for using the wrong phrasing. What I meant to say was I didn't stop to think someone might have a "www" subdomain which did not provide a valid HTTP 200 response at the top level, which seems to me to be extremely unusual. (Not, I'm quite sure many other domains do this too... it just seems unusual.) -Peter From whisper at oz.net Thu Jul 11 14:59:20 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 11 Jul 2002 11:59:20 -0700 Subject: Open document formats In-Reply-To: <6425018709313012.B034167ED9F3563C.A514BB864F414733@lp.airnews.net> Message-ID: AFAIK, Windows still does not have "postscript drivers" unless you have a driver for a postscript printer supplied by the printer vendor. Those are typically HP Laserjets with a postcript engine built-in. I have not seen, but have wanted and looked for, a "postscript to random printer" driver for a long time. Ghostscript comes closest, but it's not quite the same as a built-in driver. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Cameron Laird > Sent: Thursday, July 11, 2002 6:07 > To: python-list at python.org > Subject: Re: Open document formats > > > In article , > David Mertz, Ph.D. wrote: > . > . > . > >As far as I know, every OS, since maybe 1985, has had drivers for > >postscript printing. Almost all the applications that do not use OS > Well, wasn't Windows itself holding out > against PS for a long time? OK, I'm not > motivated enough to research this myself > just now ... > . > . > . > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://starbase.neosoft.com/~claird/home.html > -- > http://mail.python.org/mailman/listinfo/python-list From logiplexsoftware at earthlink.net Wed Jul 3 14:51:32 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 11:51:32 -0700 Subject: GoTo considered missing In-Reply-To: References: <3D233D8C.2030104@onsitetech.com> Message-ID: <20020703115132.4a5565b5.logiplexsoftware@earthlink.net> On 3 Jul 2002 18:27:18 GMT Donn Cave wrote: > Quoth Robb Shecter : > | David LeBlanc wrote: > |>...if you're writing python > |> code that uses nested loops like that, it's possible you're not taking good > |> advantage of Python's features. Care to share what you're working on?... > | > | I'd like to know too. I can't really think of an example where I'd need > | a goto statement. > > Come on, guys - think outside of the block! Well, for that matter, setjmp/longjmp are missing too! It's a wonder anything gets written at all... -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From duncan at NOSPAMrcp.co.uk Mon Jul 8 04:07:32 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 8 Jul 2002 08:07:32 +0000 (UTC) Subject: converting an array of chars to a string References: <3d12dda2_6@news.newsgroups.com> <3D12E228.6030501@wedgetail.com> <3D1307AF.3070308@wedgetail.com> Message-ID: Derek Thomson wrote in news:3D1307AF.3070308 at wedgetail.com: > I would have expected "join" to be a method on the sequence, if > anything. As in "s = lst.join('')". In fact, I looked for it, as I > *knew* I'd seen it used before as a method, I just didn't expect it to > be in the string class. If join was a method on the sequence, then it would have to be implemented for every sequence you could join and it would have to check the type of the separator to find out what type to return. As a method of the separator, it has the appropriate implementation to return a 'str' or 'unicode' object, and works on any sequence type (you can even join a string). Writing ''.join(list) still sucks though. I've taken to writing str.join('', list) instead as something I find more readable. When the separator is known in advance I sometimes wrap it up: joinlines = '\n'.join ... return joinlines(list) Plenty people think that sucks though. > I think I'll just stick with string.join for the time being. As it turns > out, there's more than one way to do it, even in Python ;) Not really, as string.join simply calls the join method of the separator. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From kseergobin at sympatico.ca Tue Jul 2 21:56:23 2002 From: kseergobin at sympatico.ca (Ken Seergobin) Date: Tue, 2 Jul 2002 18:56:23 -0700 Subject: Splitting Text files References: <%XnU8.4057$aJ4.853781@news20.bellglobal.com> Message-ID: "William Park" wrote in message news:aft8lp$h4auq$1 at ID-99293.news.dfncis.de... > Ken Seergobin wrote: > > analysing/visualizing the data. As such, I was looking for an easy way > > to abandon the use of mulitple unix(like) tools. > > "Right tool for the right job" is the key insight (as Guido would say :-) I agree. For ages I've used a combination of unix tools plus Gary Perlman's |stat for data manipulation. Almost all of that has been done in (ms-dos) batch scripts, however. I'm now curious about integrating the same data manipulation with the various analysis and visualization tools available for python. I see that there is a Scipy project and I seem to recall that there is a python link to R. This recent need to split files, as described earlier, provided enough impetus to ask about Python's abilities - with an eye to bigger picture. Anyway, thanks for all the help. Ken From kosh at aesaeion.com Tue Jul 9 14:17:46 2002 From: kosh at aesaeion.com (kosh at aesaeion.com) Date: Tue, 9 Jul 2002 12:17:46 -0600 (MDT) Subject: Why self? In-Reply-To: Message-ID: On Tue, 9 Jul 2002, Mark McEahern wrote: > You say that lots of people would like to lose the requirement. My guess is > that's not true. It may appear true, since this topic does come up every so > often and the people who think it's a problem are often quite insistent > about it. > > What you don't see, of course, is all the people who are silent because > they're quite happy with self. prefixes and consider this a pointless > discussion usually kept alive by people who refuse to learn the idioms of > Python to their best advantage. > I have to agree with you on this. I find self makes the code very clear and much easier to maintain. Overall I am willing to use extra keystrokes to make maintenance easier since I tend to go back over a piece of code far more often then the first time I wrote it and having it simpler to read is really useful. Python already takes far fewer lines of code to express the same intent as most other languages why remove that even further when it then loses legibility. That seems like a waste to me. You might as well propose strange symbols for self which I think is also a bad idea then python would end up just looking like the line noise that some other langauges often look like. I welcome changes to python that increase it expressiveness, ease of reading, speed, reliability etc however making stuff shorter to type just to save some keystrokes is not a change I endorse. From imbosol at vt.edu Tue Jul 30 15:48:06 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 30 Jul 2002 15:48:06 -0400 Subject: lexing nested parenthesis References: Message-ID: Michael Hudson wrote: > pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > >> [Kristian Ovaska] >> >> > The language category you're dealing with is called context-free grammars. >> > It's more expressive than regular languages, and it can parse any >> > programming language. >> >> Any? :-) >> >> I would not go that far. There are strange beasts out there. > > I was once told that this doesn't even cover Python: the meaning of > "a=b" depends on whether you're in an argument list or not. You were told wrongly. I understand the confusion; the way a=b is parsed does depend on its syntactic context, but a context-free grammar refers to a grammar free of semantic context. In other words, a non-context-free grammar will parse a=b differently depending on the values of a and b (and other semantic state). The reason no one says "semantic-context-free" is that a grammar free of syntactic context is manifestly impossible, so there is no ambiguity when saying "context-free." -- CARL BANKS http://www.aerojockey.com From keith_s at ntlworld.nospam.com Wed Jul 24 09:38:25 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Wed, 24 Jul 2002 14:38:25 +0100 Subject: embedded python question References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com> Message-ID: <3D3EADD1.4020400@ntlworld.nospam.com> Alex Martelli wrote: > QLineEdit handles (and returns) a single line, right? Therefore, how > can you use it to input a multi-line command? True, although you can do this in the Python interactive shell, so I presume there *is* a way of doing it. > Why not use a multiline editing widget instead? Because I'd really like it to work just like the interactive shell if possible... - Keith From andreas at kostyrka.priv.at Sun Jul 28 10:44:58 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 28 Jul 2002 16:44:58 +0200 Subject: Which gui for slow (133 Mhz) pc In-Reply-To: <20020726105352.A2854@eecs.tufts.edu> References: <3d3b9eaa.7275472@news.utanet.at> <477762c2.0207221735.48b1792c@posting.google.com> <3d42f3dc.5866543@news.utanet.at> <3d42636b.4941993@news.utanet.at> <20020726105352.A2854@eecs.tufts.edu> Message-ID: <1027843391.20536.49.camel@vaio2> Am Fre, 2002-07-26 um 16.53 schrieb Michael Gilfix: > Agreed. PyQt is the base GUI toolkit that's used in KDE. If you've > had some experience with different window managers, I suggest just > deciding whether you like the look of KDE or GNOME better. If you > like KDE, use PyQT, otherwise use GTK which is also a well > developed toolkit. Well, if you'd read the orginal email, you might discover that this is about Windows developement ;) Andreas From squelart at hotmail.nospam.com Sun Jul 28 02:58:29 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Sun, 28 Jul 2002 16:58:29 +1000 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> <3d438609$1@duster.adelaide.on.net> Message-ID: <3d439616$1@duster.adelaide.on.net> "Daniel Fackrell" wrote > On Sat, 27 Jul 2002 23:50:01 -0600, Gerald Squelart wrote: > > "Erik Max Francis" wrote > >> Michele Simionato wrote: > >> > I know a print statement cannot stay in a lambda function, however as > >> > a newbie I ask : why ? > >> Because a lambda is an expression, not a statement. > > Therefore, a lambda *expects* an expression, not a statement. > > > > However, you could indirectly include a print statement in the course of > > a running lambda expression: > > def printArg(arg): > > print arg > > return arg > > l = lambda x: printArg(x) > > a = l(10) # will print 10 and assign 10 to a map(l, range(5)) # will > > print numbers 0 to 4 and return [0, 1, 2, 3, 4] It may be useful to > > debug a lamdba expression. > > Correct me if I'm wrong, but doesn't this just create an anonymous > function that calls the named function printArg? Besides the added > function-call overhead, how are the two following lines functionally > different? > > l = lambda x: printArg(x) > l = printArg > > Daniel Fackrell Yeah, that was a very simple expression, to show how it could work... Of course this lambda function is pretty lame! Well, my point was: if you have a lambda function used like this: map(lambda x: big_expression, some_list) and now you want to print something from the anonymous function, then it's possible by just adding the stoopid printArg() function around some subexpression, without having to remove the complete lambda expression and replacing it by a function def and a call... You choose: def lambdaReplacement(x): print stuff return big_expression map(lambdaReplacement, some_list) - or - def printArg(x): print x return x map(lambda x: expression_with_printArg, some_list) And it's easier to remove later, if needed, methinks Of course, some think lambda is inherently evil, I can't argue with that, it's a matter of taste... Let's not start this war please ;-) G. From alo at iki.fi.invalid Thu Jul 11 17:46:25 2002 From: alo at iki.fi.invalid (Antti Louko) Date: Thu, 11 Jul 2002 21:46:25 GMT Subject: Open document formats References: Message-ID: In article , David LeBlanc wrote: >AFAIK, Windows still does not have "postscript drivers" unless you have a >driver for a postscript printer supplied by the printer vendor. Those are >typically HP Laserjets with a postcript engine built-in. > >I have not seen, but have wanted and looked for, a "postscript to random >printer" driver for a long time. Ghostscript comes closest, but it's not >quite the same as a built-in driver. I understand you want to find a PostScript-->bitmap driver and I am not aware of any other free programs as Ghostscript. Usually PostScript driver (in Windows) means software which translates printer API calls into PostScript code. You can find generic PostScript driver in Adobe's site at . They work much better than many drivers supplied by printer manufacturers. From skip at pobox.com Mon Jul 22 08:20:50 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Jul 2002 07:20:50 -0500 Subject: Funny behaviour of MySQLdb In-Reply-To: <20020721141143.448123E646@cali-3.pobox.com> References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> <20020720173325.51C943E6AB@cali-2.pobox.com> <15674.7752.888722.873627@localhost.localdomain> <20020721141143.448123E646@cali-3.pobox.com> Message-ID: <15675.63650.240933.758077@12-248-11-90.client.attbi.com> >> Each time I .get() a connection from the pool, I do tend to execute >> multiple SQL statements. Alex> Yes, but, if that could be reasonably encapsulated in a callable, Alex> you could just pass the (callable, returnqueue) pair as the work Alex> request. I guess I should have stated that "multiple SQL statements with lots of other goo". >> Using a fixed numbers of threads associated with each connection is a >> bit more complicated, especially since I already wind up with a >> thread per request courtesy of SocketServer.ThreadingMixin. Why >> waste it? Alex> Without even having seen your code I suspect your highest gain in Alex> scalability would come from a slightly modified ThreadingMixin Alex> that reuses worker-threads from a thread pool rather than churning Alex> out one thread per request. Thanks, that might well be worth investigating. I already subclass ThreadingMixin to make each per request thread a daemon thread. Allocating from a fixed pool instead of creating one per request might be feasible there. Skip From SSchukat at dspace.de Mon Jul 22 06:57:52 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Mon, 22 Jul 2002 11:57:52 +0100 Subject: Python to Excell Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B238@PDC-DSPACE> Sorry missing gencache -> from win32com.client import gencache gencache.EnsureDispatch('Excel.Application', 0) Stefan -----Original Message----- From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] Sent: Monday, July 22, 2002 10:48 AM To: python-list at python.org Subject: Re: Python to Excell On Mon, 22 Jul 2002 09:49:33 +0100, Stefan Schukat wrote: >Search for excel8/9/10.olb an run makepy on it. There you'll have >all the classes available from Excel. > >or run "win32com.client.EnsureDispatch('Excel.Application', 0)" >and search the [PYTHON_ROOT]\Lib\site-packages\win32com\gen_py >directory for the generated module. When I try the code above I get: >>> import win32com >>> win32com.client.EnsureDispatch('Excel.Application', 0) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'win32com' module has no attribute 'client' >>> from win32com import client >>> win32com.client.EnsureDispatch('Excel.Application', 0) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'win32com.client' module has no attribute 'EnsureDispatch' Any idea? > >or use the macro recorder of excel and translate it to python code > >or use the excel online help > >or buy a book "Python Programming on Win32" > >or ... > > > Stefan > > >-----Original Message----- >From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] >Sent: Monday, July 22, 2002 8:33 AM >To: python-list at python.org >Subject: Python to Excell > > >Hi all, > >I want to use Python to automate Excell. What I want to do is writing >a script which updates an Excell sheet and which prints it out then. I >know the stuff about DispatchEx but I do not know the interface which >is exposed by Excell. Can anybody help me further on this one? > >Thanks, > >Henk >-- >http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list From alw at gate2.dda.dk Thu Jul 11 16:50:26 2002 From: alw at gate2.dda.dk (Allan Wermuth) Date: Thu, 11 Jul 2002 22:50:26 +0200 Subject: writing output to file References: Message-ID: Thank You all for the quick answers :-) /Allan Wermuth Alex Martelli wrote in message news:wulX8.57568$Jj7.1513132 at news1.tin.it... > Allan Wermuth wrote: > ... > > instead of writing the result to the screen, I would like to write output > > to a another file. > > > > #!/usr/bin/python > > for line in open('/etc/passwd').readlines() : > > if line.strip()[0] == '#': continue > > > > temp = line.split(':') > > if int(temp[2]) > 100 : > > print "%10s %30s" % (temp[0], temp[4]) > > > > How can I do that? > > My personal suggestion: > > flout = open('/tmp/otherfile', 'w') > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue > > temp = line.split(':') > if int(temp[2]) > 100: > flout.write("%10s %30s\n" % (temp[0], temp[4])) > flout.close() > > An alternative: > > flout = open('/tmp/otherfile', 'w') > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue > > temp = line.split(':') > if int(temp[2]) > 100: > print >> flout, "%10s %30s" % (temp[0], temp[4]) > flout.close() > > > As you see, the difference boils down to using a variant > of the print statement (with the clause >> flout , to > direct output elsewhere) versus using the write method > of the file-object flout (which, differently from print, > just takes whatever string you give it and puts it out > to the file without alterations). > > My personal opinion is that print is good for simple > quick & dirty output for debugging purposes, while using > formatting operations to prepare strings and then the > write method of file objects to emit them is the best > way to go for "production" code. But, if you disagree, > the >> flout , clause in the print statement lets you > use the print statement to write to a file, too. > > > Alex > > From chris.gonnerman at newcenturycomputers.net Tue Jul 2 00:21:58 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 1 Jul 2002 23:21:58 -0500 Subject: somewhat off-topic References: <3d211d32$1_5@nopics.sjc> Message-ID: <001801c22180$03b94840$0101010a@local> ----- Original Message ----- From: "Adonis" > i wrote a http server using SimpleHTTPServer, im using the GET command as my > cgi trigger, and would like to "hide" the path? > > i.e. > > i get a: > GET /login?user=foo&pass=bar > > client side (on their url box they see) > http://host/login?user=foobar&pass=bar > > i want them to just see: > http://host/login or just http://host/ since login is really mapped to a > class. > > i know it has to do something with headers, but have failed to find it on > google. You have to use
to avoid the variables being shown, OR you can store the data in a cookie (or cookies). There really isn't any other way AFAIK. > any help would greatly be appreciated. > > Adonis Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jdavis at empires.org Fri Jul 26 16:25:26 2002 From: jdavis at empires.org (Jeff Davis) Date: Fri, 26 Jul 2002 20:25:26 GMT Subject: performance problem in python 2.2 Message-ID: I wrote a small python program to help me solve a math problem. When I tried to run it with large values, it ate all my RAM and I eventually had to kill it. I tried writing the same thing in C and it used almost no RAM (and had an upper limit) and finished much faster. Then I was talking to someone who suggested that I try perl. I have the exact same algorithm in perl, and it doesn't eat my RAM, and executes much more quickly (same order of magnitude as the c program). It seems almost as if there's a memory leak in one of python's simple math operations, because it is so much worse than the other ones I tried. I have listed the two programs below. Does someone think I found a bug/memory leak? Does someone know about something else that might be going on? Thanks, Jeff ===================python======================== #!/usr/bin/python2.2 import sys n = 1.0 p = 2L**64 c = long(sys.argv[1],10) for i in range(1,c): n = (n * (p-i)) / p print 1-n ====================perl========================== #!/usr/bin/perl $p = 2**64; $c = $ARGV[0]; $n = 1; foreach $i (1..$c) { $n = ($n * ($p-$i)) / $p } print 1-$n, "\n"; From alexandrecourbot at linuxgames.com Tue Jul 23 15:48:29 2002 From: alexandrecourbot at linuxgames.com (Alexandre Courbot) Date: Tue, 23 Jul 2002 21:48:29 +0200 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: References: <7xfzybii29.fsf@ruckus.brouhaha.com> Message-ID: <20020723214829.1785847d.alexandrecourbot@linuxgames.com> > > > But that had an obscure endcase bug too, and it get replaced in > > > 2.2 by a new float method that doesn't make unwarranted > > > assumptions about the relative sizes of C longs and C doubles, and > > > usually gets out quickly -- provided float arithmetic isn't pig > > > slow. > > > > Ouch!! That doesn't sound so good for the Zaurus. > > Yeah, I wonder if it's worth to profile the stuff! :) > > Guys, I'll first test it with Python 2.1.3. Adonthell (the game I'm > porting) works with any Python >= 1.5.2, so if the problem can be > solved in the short-term by regressing to 2.1, that'll be fine for > now. If the differences are significant, then maybe we could consider > to add another interger-only checking method that would suit in the > case of Arm processors. I'll try to give you news about it tomorrow. Okay, I have cross-compiled Python 2.1.3, re-compiled Adonthell and linked it against it, and... it's as slow as with Python 2.2. So it looks like the overflow check isn't to blame here. I'll do some profiling as soon as I have the time and send the results here. My surprise is big, as Python's purpose is only to control some elements of the game. That is, it makes calls to *our* functions written in C++. So on a classic PC, 99% of the CPU time is spent in our functions. On the Zaurus however, it rather looks like 90% of the time is spent into Python, as the time runs at least 10 times slower when I enable the Python schedules. And no matter whether Python is used or not, all our "hot" functions are called. Note however that the interpreter is called very often to run very short scripts. We call PyObject_CallObject something like 70 times per second, for each schedule (and there is something like 10 of them). Maybe there is some context-switching or something like that and that it eats a lot of CPU on the Zaurus? But in this case I wouldn't understand why it isn't the case on my PC... Any idea here? Well, I'll try to come with profiling results ASAP. Alex. -- http://www.gnurou.org From peter at engcorp.com Mon Jul 22 20:17:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 20:17:06 -0400 Subject: Parnassus gone?? References: Message-ID: <3D3CA082.81726E6D@engcorp.com> Gerhard H?ring wrote: > > Matthias Huening wrote in comp.lang.python: > > What happened to The Vaults? I just got this error: > > Error 400 - Unable to resolve host name - http://www.vex.net/parnassus/. > > This site seems to have problems from time to time. It's possible, since it's hosted in Toronto, that it was hit by the nasty thunderstorm that rolled through here and killed power in several areas for over half an hour (although that was closer to 3:30 pm). It's also possible that vex.net's message of the day applies in some distant way: "The Web/Mail servers and related services were moved to new upgraded hardware this morning. All services should be back to running normally." -Peter From skip at pobox.com Fri Jul 26 17:36:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Jul 2002 16:36:18 -0500 Subject: Two RE proposals In-Reply-To: References: Message-ID: <15681.49362.442164.660697@12-248-11-90.client.attbi.com> David> 1. Add a substitution operator - in the example below it's "!<..>" David> word = r"\w*" David> punct = r"[,.;?]" David> wordpunct = re.compile(r"!!") How about word = r"\w*" punct = r"[,.;?]" wordpunct = re.compile(r"%(word)s%(punct)s" % locals()) which you can do today? (I'd also argue that a word would be "\w+".) David> 2. Make r"(a|b)*" mean any number of a's or b's. This doesn't David> work, at least in some situations with the current re compiler David> - the "any" op "*" doesn't seem to span over a parened David> group. The * doesn't (and shouldn't) operate over grouping parens. You're asking it to supply you with a variable number of groups, which it can't do. Besides, what's wrong with r"([ab]*)"? -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From me at michaelbauers.com Sun Jul 14 18:05:42 2002 From: me at michaelbauers.com (Michael Bauers) Date: Sun, 14 Jul 2002 17:05:42 -0500 Subject: Running multiple functions with Python 1.5 References: <20020714113045.08255.00000535@mb-fj.aol.com> Message-ID: Are you asking if Python has multi-threading abilities? Far as I know the latest version does...perhaps not 1.5 though. "Musicmaker1118" wrote in message news:20020714113045.08255.00000535 at mb-fj.aol.com... > I am trying to make a simple windowing system in python 1.5 that can run using > minimal memory. I would like for it to be able to display icons, and to be able > to run programs assosciated with them when you click on them. I would also like > it to be able to run simple programs inside of a window. To do this this, I > need to be able to run programs and monitor the movements of the mouse to > display the cursor. I plan on using a C extension for the graphics and > monitoring the mouse. The functions it defines will be run by the python code. > But I am not sure if Python 1.5 can be running different functions at the same > time, and if it is possible, how to do it. Does anyone know how this could be > done? If so, I would like to know. From shagshag13 at yahoo.fr Fri Jul 26 12:39:35 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 26 Jul 2002 18:39:35 +0200 Subject: AttributeError in re.findAll ? Message-ID: hello, from t2 : >>> t2 ' 1 2 3' i want to get ['', '', 'w1', 'w2', '-', '.', '$', '&', '', '', 'w3', '', '5', '', '', ''] so i use following : >>> t2 = """ w1 w2 - . $ & w3 5""" >>> import re >>> t2 = """ w1 w2 - . $ & w3 5""" >>> p = re.compile("<[^>]*>|[^<\s]+") >>> p.findAll(t2) Traceback (most recent call last): File "", line 1, in ? p.findAll(t2) AttributeError: findAll >>> p = re.compile("<[^>]*>") >>> p.findAll(t2) Traceback (most recent call last): File "", line 1, in ? p.findAll(t2) AttributeError: findAll and get these AttributeError that i don't understand ! What does it mean ? (is it missing something ?) thanks, s13. From shagshag13 at yahoo.fr Tue Jul 9 10:15:45 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 9 Jul 2002 16:15:45 +0200 Subject: sorting many arrays from one... References: Message-ID: "Duncan Booth" Alex Martelli thanks to you two ! so if i want to do this in a generic function, i should use something like : def sortManyFromOne(driven, compare = None, *others): aux = zip(driven, *others) if compare is None: aux.sort() else: aux.sort(compare) driven, *others = map(list, zip(*aux)) but this last line don't work and i don't know how to fix it... unless i replace it by : return map(list, zip(*aux)) is it a good idea if we consider that my "driven" and "others" could contain more than 300,000 elements each ? (i'm thinking of using array.array instead of list) s13. From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 07:21:39 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 04:21:39 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> Message-ID: <7xwus7n5q4.fsf@ruckus.brouhaha.com> Thomas Jensen writes: > I gotta look into this. > However I am uncertain as how to structure my program. > One of the tasks of the program will be to calculate the standard > deviation of rows of daily values (which are the result of another > calculation, etc). I was planning on using lists and tuples like this: > [(date, value), (date, value), ...] > How well will this perform i wonder? Since lists and tuples are Python > structures, won't they still be "slow" to traverse? Lists and tuples are fast to traverse (they're just vectors in memory) but I don't see their relevance if by "rows" you mean database rows. You have to iterate over the rows and compute the SD. I expect the time for that will be mostly taken by database operations. From mcfletch at rogers.com Thu Jul 18 04:14:04 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 18 Jul 2002 04:14:04 -0400 Subject: SimpleParse 2.0.0a4 released, mailing list created... Message-ID: <3D3678CC.30007@rogers.com> I've just released version 2.0.0a4 of SimpleParse. This includes an eXample/eXperimental XML parser (including DTD parser), a mechanism for generating SyntaxErrors on the failure of any production/element-token, and LookAhead support. http://simpleparse.sf.net/ I will be restricting further package announcements to the SimpleParse Users list. The Python and eGenix Lists will only get messages about major updates to the package. Those interested in more frequent updates and/or discussion should see the mailing list at: http://lists.sourceforge.net/lists/listinfo/simpleparse-users What is SimpleParse (From the WebSite): SimpleParse is a BSD-licensed Python package providing a simple parser generator for use with the mxTextTools text-tagging engine. SimpleParse allows you to generate tagging tables for use with the text-tagging engine directly from your EBNF grammar. Features: New in 2.0.0a4/a3: * Exposure of "LookAhead" mechanism in mxTextTools (allows you to spell "is followed by", "is not followed by", or "matches x but doesn't match y" in SimpleParse EBNF grammars) * "Error on fail" error-reporting facility, allows you to raise Parser Syntax Errors when particular productions (or element tokens) fail to match. This is not an automated system, but does allow for fairly flexible error reporting. To specify, just add a '!' character after the element token that must match. * The beginnings of an example XML-Parser (including DTD parsing) based on the XML specification's EBNF (this is not a production parser, merely an example for parsing a complex file format, and is not yet Unicode capable) New in 2.0.0a2 * New, refactored and simplified API. Most of the time you only need to deal with a single class for all your interactions with the parser system, and one module if you decide to use the provided post-processing mechanism. * Compatability API for SimpleParse 1.0 applications * "Expanded Productions" -- allow you to define productions whose children are reported as if the enclosing production did not exist (allows you to use productions for organisational as well as reporting purposes) * Rewritten Generators -- the generator interface has been seperated from the parser interfaces, this makes it possible to write grammars directly using generator objects if desired, and allows defining the EBNF grammar using the same tools as generate derived parsers * Hexidecimal escapes for string and character ranges * Exposure of callout mechanism in mxTextTools * With the non-recursive mxTextTools, can process (albeit inefficiently) recursion-as-repetition grammars * Non-recursive rewrite of mxTextTools now ~95% of the speed of the recursive version General * Simple-to-use interface, define an EBNF and start parsing * Fast for small files -- this is primarily a feature of the underlying TextTools engine, rather than a particular feature of the parser generator. * Allows pre-built and external parsing functions, which allows you to define Python methods to handle tricky parsing tasks Enjoy yourselves, Mike _______________________________________ Mike C. Fletcher Why, yes. I am looking for a job... http://members.rogers.com/mcfletch/ From oren-py-l at hishome.net Wed Jul 3 10:10:53 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 3 Jul 2002 10:10:53 -0400 Subject: pipes.py and its limits In-Reply-To: References: Message-ID: <20020703141052.GB73351@hishome.net> On Wed, Jul 03, 2002 at 09:52:05AM -0400, val wrote: > Hi All, > i'm looking at pipes.py, a great pipeline implementation > in python (BTW, who is the author?), and trying to figure > out its limits. The description says that the commands > to be appended to the pipeline template have to be > shell functions. I'd like to try to build the dynamic pipelines > using the python functions or callable objects. > > In other words, i'd like to modify the pipeline - > its functional components on-the-fly depending on > the results of running the pipeline (its output). > > I'm sure the real Pythoneers know how to do that. > Any pointers/help would be highly appreciated. Take a look at http://tothink.com/python/dataflow for a library that implements pipelines (I call them flows) using Python iterators and generators. I also have a library for intergrating external commands more easily into Python scripts. http://tothink.com/python/shell I'm working on merging the two so it will be possible to create flows with mixed Python functions and external commands. I do not intend to support modification of the flow while it is running because its elements may be delicate stateful components that have different input and output rates, buffering, etc. Changing it on the fly could lose data. But one of the elements in the flow can change its functionality or even embed a separate flow object inside it if you want. Oren From emile at fenx.com Tue Jul 2 23:33:54 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 03 Jul 2002 03:33:54 GMT Subject: Comments in pickles? References: Message-ID: "Roy Smith" wrote in message news:roy-AC514A.22260002072002 at reader2.panix.com... > I've got a file parser that returns a data structure. As part of a > regression test suite, I'm going to parse several sample files and save > the resulting data structures as pickle files to compare against future > versions. I want to check those pickles into CVS. > > Our usual practice is to imbed the CVS id string ($Id: ) in every > checked-in file as a comment. Is there any way to do that with a > pickle? Does a comment convention exist which cPickle.load() > understands? You could shadow the dumps and loads to add an attribute to each non-slotted instance. Here's a q&d for dumps for instance ;-) import cPickle class Test: pass t = Test() t.a = 1 t.b = 2 def cvsdumps(object, bin=0, dumps=cPickle.dumps): object._my_obscure_cvs_id_string_ = 'CVS_ID_STR' return dumps(object, bin) cPickle.dumps = cvsdumps cPickle.dumps(t) You could also tweak the code the checks the pickles into cvs I imagine. HTH, -- Emile van Sebille emile at fenx.com --------- From gerhard.haering at gmx.de Sun Jul 7 17:13:35 2002 From: gerhard.haering at gmx.de (=?ISO-8859-1?Q?Gerhard=20H=E4ring?=) Date: Sun, 7 Jul 2002 23:13:35 +0200 (Central Europe Daylight Time) Subject: openprojects python room is ruled by dangerous people In-Reply-To: <3eeda89d.0207070906.1fa45916@posting.google.com> References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: <20020707211113.1EBE04DF@gargamel.hqd-internal> Somebody with the uncool pseudonym of "Thinkit" wrote: > These people are dangerous, and will boot you if you do not agree to their > narrow worldview. Their twisted worldview? You can safely ignore twisted, if you're not into network programming. At least I do and I still feel safe, despite not agreeing with dash and moshez on everything :-) And I don't think anybody gets kicked there unless (s)he's trolling repeatedly. > They are an affront to the python language--especially "dash". I don't think so. Just don't try to argue about Free Software, C++ or LISP, unless you've done your homework. Apart from that, it's the coolest irc channel I've seen yet. Gerhard, aka Xamines -- mail: gerhard.haering at gmx.de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From BPettersen at NAREX.com Thu Jul 11 17:20:03 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 11 Jul 2002 15:20:03 -0600 Subject: Automating MSDEV studio build process Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201922151C2@admin56.narex.com> Does anyone have any experience automating a nightly build process using Python in combination with MSDevStudio? I remember some discussion here about it a while ago, but I couldn't find any reference to it through Google... We have three major classes of libraries we need to build (each class has its own dsw with about a dozen dsp's inside for individual sub-libraries). Would it be best to generate makefiles from the dsw's and proceed on the command line from there (is there a way e.g. through COM to have VS generate the makefiles since we normally don't use makefiles?) -- or should we try to automate it all through controlling VS through COM? The engineer who is working on this is pretty new to Python, so this would be a good way to show him how to get rid of five hours of manual build processes (especially since I just got mandated that we install Python on all machines :-) -- bjorn From fp at contact.de Wed Jul 10 12:43:54 2002 From: fp at contact.de (Frank Patz) Date: Wed, 10 Jul 2002 18:43:54 +0200 Subject: Embedding Python the extreme way In-Reply-To: <3D2C424F.5020609@darkstargames.de> Message-ID: > > OK, so I think a better (read: easier) strategy might be to /hide/ > > these objects, not /remove/ them. > > How can I do that? My initial idea was to modify bltinmodule.c to do > things I want. What I definitly don't want, is to call Py_Initialize() > and then replace the original modules with my own. I'd appreciate it, if > it would be possible to modify the sources. Something like "del sys.__dict__['exit']" basically works. - frank From matt_gerrans at hp.com Tue Jul 9 17:41:35 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Tue, 9 Jul 2002 14:41:35 -0700 Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: > >> eval! > > > >Overkill. Unsafe. Ugly. Lame. > > > > What do you mean by unsafe? Also, in addition to the criticism of the suggested method (eval), you could post your simpler, safe and able-bodied alternative. Perhaps it was: try: n = eval(string) except: n = 0 From msachet at hotmail.com Thu Jul 18 03:53:20 2002 From: msachet at hotmail.com (Marc) Date: 18 Jul 2002 00:53:20 -0700 Subject: Newbie : Processes management under W2K Message-ID: Hi everybody, in order to kill a specific app, i'd like to know how to get the list of all processes currently running under Win2000 with name, pid, etc.. thanks in advance ! Marc From steve.menard at polyester.com Wed Jul 10 15:32:07 2002 From: steve.menard at polyester.com (Steve Menard) Date: Wed, 10 Jul 2002 15:32:07 -0400 Subject: j2ee and python and evil competitors References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: "Jacek Generowicz" wrote in message news:tyf7kk4jauz.fsf at pcitapi22.cern.ch... > "Bo M. Maryniuck" writes: > > > On Tuesday 09 July 2002 16:59, curt finch wrote: > > > ftp://ftp.jump.net/pub/journyx/other/PythonWhtPaper0_1.doc > > > > Right people will not download this. M$ Word DOC is *evil* format. Please do > > PDF, DVI or HTML instead. > > I'll second that. I was about to have a look, and then saw the doc > extension. I take doc extensions to mean "This document is intended > for Microsoft customers only". I am not a Microsoft customer. See, this is something I really don't understand. I will agree that PDF or html would have been a better choice, but not everyone can generate PDF ya know. With this kind of attitude, we'll forever be regarded as the extremists who won't listen to anything .... Steve From huaiyu at gauss.almadan.ibm.com Wed Jul 24 17:28:58 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 24 Jul 2002 21:28:58 +0000 (UTC) Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3E9BCF.90806@mxm.dk> Message-ID: Alex Martelli wrote: >How is it more convenient to pass, say, object X, rather than >to pass bound method (e.g.) X.primary? Take your example: Well, here's one example: >>> class A: ... def __call__(self, x): return x+self.x ... >>> a = A() >>> a.x = 3 >>> a(2) 5 >>> a.x = 4 >>> a(2) 6 >>> >>> class B: ... def call(self, x): return x+self.x ... >>> b = B() >>> b.x = 3 >>> b.call(2) 5 >>> b.x = 4 >>> b.call(2) 6 >>> If you take b as the object, you need to use explict call. If you take b.call as object, you can't do other things to the object. Callable objects can be viewed as parameterized functions. Regarding whether the parameters can be modified later, it is similar to functions with attributes, but not similar to bound methods. Huaiyu From unendliche at hanmail.net Tue Jul 2 03:03:39 2002 From: unendliche at hanmail.net (Seo Sanghyeon) Date: 2 Jul 2002 00:03:39 -0700 Subject: What is ""? Message-ID: <45e6545c.0207012303.5a0e44fd@posting.google.com> Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> from types import ModuleType as module >>> MyModule = module() >>> MyModule >>> dir(MyModule) [] >>> What is this? From vvainio at tp.spt.fi Thu Jul 25 06:49:25 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 25 Jul 2002 03:49:25 -0700 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> <3D3EA54C.3EF009A@lfpt.rwth-aachen.de> <3D3DF209.17923D28@cybermesa.com> Message-ID: Jay O'Connor wrote in message news:<3D3DF209.17923D28 at cybermesa.com>... > That was my other thought., wondering if someone else had already done > what I was toying with. It appears so :) Yes, almost everybody starts to think about implementing a distributed objects scheme when playing with python. It's so easy and fun, and things like introspection practically force one to reinvent the wheel ;-). It would appear that the sensible thing to do is to go the CORBA way, which is tried, true, *easy* (controversy on this issue mainly concerns non-python bindings) and interoperable (and fast, at least with omniORBpy that I've tried). -- Ville From pixie888 at hotmail.com Tue Jul 23 02:02:48 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Tue, 23 Jul 2002 06:02:48 GMT Subject: Python to Excell References: <3d3bb483.250106359@news.skynet.be> Message-ID: <3d3cf15b.331217890@news.skynet.be> Thank you all for the help!! Henk On Mon, 22 Jul 2002 07:33:07 GMT, pixie888 at hotmail.com wrote: >Hi all, > >I want to use Python to automate Excell. What I want to do is writing >a script which updates an Excell sheet and which prints it out then. I >know the stuff about DispatchEx but I do not know the interface which >is exposed by Excell. Can anybody help me further on this one? > >Thanks, > >Henk From pecora at anvil.nrl.navy.mil Wed Jul 10 15:26:47 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Wed, 10 Jul 2002 15:26:47 -0400 Subject: Why self? References: <090720021439257166%pecora@anvil.nrl.navy.mil> <7934d084.0207091739.4720aafc@posting.google.com> Message-ID: <100720021526477293%pecora@anvil.nrl.navy.mil> In article , Huaiyu Zhu wrote: > The Pythonic way to use namespace is :-) > > from self import x, y, z, a, tseries > y= x**2 * t/z + a * FFT(tseries) > to self export y Hmmmm....never thought that way. Very interesting. > Any change that persists beyond local namespace is mentioned explicitly. > Does it solve all the problems mentioned below? Don't know. -- Lou Pecora - My views are my own. From robin at jessikat.fsnet.co.uk Sat Jul 13 05:10:07 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 13 Jul 2002 10:10:07 +0100 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) References: <1026460828.781.70.camel@lothlorien.colorstudy.net> Message-ID: ..... nonsense is of course in the eye of the beholder Beautiful lies are not better than ugly truths. Explicit nonsense is not better than implicit sense. Simple failure is not better than complex success. Complex failure is not better than complicated success. Flat cats are not better than nested birds. Sparse matrix algorithms are not better than dense matrix algorithms. Readability of rubbish does not count. Special cases are exactly the ones that break the rules. etc etc etc -- Robin Becker From sholden at holdenweb.com Sat Jul 27 00:55:24 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:55:24 -0400 Subject: how to count lines in a file ? References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> <15682.10208.325890.497677@12-248-11-90.client.attbi.com> Message-ID: "Skip Montanaro" wrote in message news:15682.10208.325890.497677 at 12-248-11-90.client.attbi.com... > > >> Not quite. Any cycle containing an object with a __del__ method will > >> be skipped and left to languish in memory-limbo forever. > >> > Steve> You mean the garbage collector doesn't *collect* data that > Steve> appears in cycles? That's not my understanding (which doesn't > Steve> nevessarily mean it's dissonant with reality). > > No, just those cycles where at least one of the involved objects contains a > __del__ method. In those situations, it's the programmer's responsibility > to break the cycle. Thanks for the clarification. I hadn't understood that the existence of a __del__() would modify the GC's actions. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From peter at engcorp.com Sun Jul 7 15:39:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Jul 2002 15:39:08 -0400 Subject: How to organize test cases with PyUnit References: Message-ID: <3D2898DC.B59538B1@engcorp.com> Roy Smith wrote: > > I could put all the test-case code in the same .py file as the module. I'd only consider this for a small stand-alone module. Anything larger and I would expect to have maintainability problems (file growing too large, for example), as well as issues like you pointed out with having to parse the test code every time the module is compiled. > I could put the test cases for a module in another file in the same > directory, or possibly put all the test cases for all my modules in a > "test" subdirectory. This answers the efficiency question above, but > seems like it's begging to have the two files get out of sync. We put all of ours in a subdirectory called "unit", with files named for the module under test but with "_unit" appended, as in somemodule.py getting a somemodule_unit.py for its tests. Depending on the project, we similarly use "_user" or "_accept" at the end for tests involving acceptance tests rather than unit tests. These are also in a separate directory (predictably named "user" or "accept"). As for getting out of sync -- this is not a problem if you always write the test code before the application code, and make sure your tests always run 100% successfully (which tells you you're done coding). If you leave tests until later, you'll definitely start encountering synchronization problems unless you have a very disciplined process. > Also, does the test case file import the module being tested? Is there a > common higher-level file that imports both? No need for a third file, except perhaps as part of a sophisticated framework. Don't make life more complicated than it already is. :) > BTW, I started out with the test cases in a "test" subdirectory, and ran > into a slight uglyness. My initial idea was to just have module-test.py > do an "import ../module", until I discovered that gives you a syntax > error. I can get around it with: > > import sys > sys.path.insert (1, '..') > import module We modify PYTHONPATH to include ".." first and run from the folder containing the tests. Then the "import module" is all we need. By the way, you might encounter problems with "module-test.py" as a file name at some point... you couldn't import it, for example. Use underscores instead of hyphens... -Peter From solrac at us.ibm.com Thu Jul 4 09:58:01 2002 From: solrac at us.ibm.com (Frank Carlos) Date: Thu, 4 Jul 2002 09:58:01 -0400 Subject: Python and XML development using the open source 4Suite toolkit Message-ID: Python and XML development using the open source 4Suite toolkit 4Suite is an open source, comprehensive library and toolkit for XML processing in Python. 4Suite implements various open standards related to XML. This series of tutorials introduces 4Suite and gives practical examples of XML development using 4Suite and Python. Part 1: PyXml There are various DOM implementations, in varying computer languages. Here, we will be introducing PyXml. This particular implementation is written in Python. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse- bytitle/28BEDEE3E7219EB386256AE300743B69?Open&t=gr,lnxl22,p=PyXml Part 2: 4XPath and 4XSLT This tutorial introduces 4XPath and 4XSLT . If you plan to use Python in association with XML processing, these are useful tools to get to know. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse- bytitle/BE1A7E60838F9F7686256AF400523C58?Open&t=gr,lnxl22,p=4XPath4XSLT Part 3: 4RDF This tutorial will go into detail on RDF, with hands-on examples of how to use the various RDF facilities available with Python. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse- bytitle/8A1EA5A2CF4621C386256BBB006F4CEC?Open&t=gr,lnxl22,p=4RDF -------------- next part -------------- An HTML attachment was scrubbed... URL: From loewis at informatik.hu-berlin.de Fri Jul 26 09:36:30 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 26 Jul 2002 15:36:30 +0200 Subject: Solaris 9, python 2.1.3, find References: Message-ID: Marc Petitmermet writes: > I have a new SunBlade 100 with Solaris 9 and the latest patches for this > OS installed. Now I'd like to install python 2.1.3 from source with > tkinter enabled. Although I have correctly configured Modules/Setup to > point to the correct location of the libraries and header files of > tcl/tk, the compilation (./python setup.py build) stops with telling me > that "libtk8.3.so: open failed: No such file or directory". > [...] > the library cannot be found although it is located in > /usr/local/tk8.3.4/lib/libtk8.3.so. Leaving the issues of symbolic links alone, I'm not surprised that Solaris won't find the shared library. With the -L option, you only specify the path for the static linker (ld(1)); at run-time, you need a different mechanism to find it. The most common mechanisms are: - set LD_LIBRARY_PATH at run-time, - set LD_RUN_PATH at compile-time, - use -R options (see ld(1)), - use crle(1). HTH, Martin From marklists at mceahern.com Fri Jul 12 12:14:25 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 11:14:25 -0500 Subject: newbie question: getting rid of space in string :( In-Reply-To: Message-ID: Joseph, as someone else has pointed out, the comma at the end of print foo, is responsible for the space. You have at least two options: o print things all at once l = [] for x in "foobar": l.append(x) print ''.join(l) o write to sys.stdout import sys for x in "foobar": sys.stdout.write(x) The following modification of your script allows you to explore several interesting ideas in Python: o generators o nested scopes o the use of locals() to add simplicity and clarity to format strings o use lists to accumulate strings before printing o string methods (e.g., join) o the fact that you should never name a variable to conflict with the name of a module in the standard library (e.g., string, i renamed to 's') Cheers, // mark #! /usr/bin/env python from __future__ import generators def make_color_switch(color1, color2): def color_switch(): i = 0 while True: if i % 2: yield color2 else: yield color1 i += 1 return color_switch def colorize(s, color1, color2): color_switch = make_color_switch(color1, color2)() template = "<%(color)s>%(c)s" l = [] for c in s: color = color_switch.next() l.append(template % locals()) print ''.join(l) colorize("testing", "black", "red") -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Joseph Youssef Sent: Friday, July 12, 2002 12:53 AM To: python-list at python.org Subject: newbie question: getting rid of space in string :( Hello, I'm new to python and I'm writing a very small script which takes each letter of a string and adds text to it (I know this is not a good explanation but you'll understand below :) ) anyway, this is my current code: def textColor(string, color1, color2): color = color1 for a in string: print "<" +color+ ">" +a+ "", if color == color1: color = color2 else: color = color1 so when I run let's say textColor("testing","black","red") it returns: t e s t i n g now this works just fine exept that space in between each block of text, I can't get it to stick together, now I know this is a very easy question but I need some quick help thanks -- Too often we lose sight of life's simple pleasures. Remember when someone annoys you it takes 42 muscles in your face to frown, BUT, it only takes 4 muscles to extend your arm and bitch-slap that mother@#?!&! upside the head! - From maxm at mxm.dk Mon Jul 22 04:47:22 2002 From: maxm at mxm.dk (Max M) Date: Mon, 22 Jul 2002 10:47:22 +0200 Subject: HTMLGen in Zope (Update) References: Message-ID: <3D3BC69A.8010509@mxm.dk> Justin Shaw wrote: > Here is what I've done: > 1. Moved HTMLgen directory to \lib\products > > 2. Added the __init__.py file: > # __init__.py > from Products.PythonScripts.Utility import allow_module, allow_class > from AccessControl import ModuleSecurityInfo, ClassSecurityInfo > from Globals import InitializeClass > > import HTMLgen > > allow_module("HTMLgen") > > 3. Restarted Zope > > I can see HTMLgen in Zope: > Product at /Control_Panel/Products/HTMLgen > > But my script bombs at: > import HTMLgen > Error Value: No module named HTMLgen You are doing it way more complicated than it need to be. Just put HTMLgen in /lib/python/ and then, asuming it is a normal module: import HTTMLgen ... etc. There is no need to call allow_module or anything special to use a module in Zope. And you certainly should not install it as a product as it does no through the web management. regards Max M From fakeaddress at nowhere.org Mon Jul 8 16:52:50 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 08 Jul 2002 20:52:50 GMT Subject: sending a file through sockets References: <3D277DDC.1040705@nowhere.org> <1026007094.566332@yasure> <3D280B4B.8020008@nowhere.org> Message-ID: <3D29FBA5.7080707@nowhere.org> Donn Cave wrote: > Quoth Bryan Olson: > If you feel the standard distribution's modules are really bad, then > maybe it would make sense to address that. I've looked into it. Right now I don't have facilities to test on most of the supported platforms. > They certainly ought to > be much more robust than the present example needed to be, since it > really was more introductory. What perhaps is really harder than it > looks, is deciding "how much is enough". Part of my job is to decide > how robust an application needs to be, and while it may be good to > err on the side of safety, that doesn't excuse me from making the call. For an internet application, it turns out to be more than most people think. It's a rough network out there. [...] > The signal issue with httplib.py is another matter. It isn't so much > about sockets, as C stdio via file objects. I wouldn't have written > it that way myself, because of liabilities like this. recv(2) will > return EINTR, and socketobject.recv() will accordingly raise an exception, > so there is no ambiguity. fileobject.read() ignores the error. The > example used recv(), so it didn't put its foot in that hole to start with. > But that's another trade-off - the authors of those modules apparently > felt that the simplicity of a file object solution was worth the lossage. I have to disagree. The trouble with signals is their global-ness. The modules don't handle the exception on EINTR. One module using an alarm can break others. On the other side, the sockets module (on some platforms) calls signal to ignore SIGPIPE. That could come as a surprise to other modules or users, and it's possible someone else might set it back. > | I gathered that you had in mind a kind of any-old-way of ending. Clean > | close of a TCP connection is a deliberate act, and the method you named > | doesn't do it. > > Let's review what I said: > Fine if the file is all you're sending, but it's like "who needs > an on-off switch on this appliance, when you can just cut the > power cord with a pair of insulated wire cutters." A byte count > prefix usually is needed, and in the rare case when it isn't, > it doesn't cost much to do it anyway. > > "Appliance" means, to me, popcorn popper, steam iron, whatever you > like. It's an analogy. Yes, and a TPC's graceful close is analogous to an off-switch, not a cut cord. > I would send a byte count. I welcome you to send a byte count. I didn't even say it was bad advice; just that it's not really needed, and since the protocol didn't check it, we might as well take it out. To me, this one looked like a job for HTTP/0.9. For a flexible protocol I would not recommend sending a single byte count as a prefix, because in many cases the sender doesn't know how much data he'll be transmitting. It's a huge pain to have to buffer the entire transmission to see how big it is. So we'd want a chunked representations, or a maybe a second control connection. --Bryan From brian at sweetapp.com Mon Jul 8 15:27:50 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 8 Jul 2002 12:27:50 -0700 Subject: Why self? In-Reply-To: <3D29DBA4.7070606@onsitetech.com> Message-ID: <000d01c226b5$8c68f520$bd5d4540@Dell2> Robb wrote: > I don't think so: As I understand it, the double underscores are > necessary in order to for the class to function correctly if subclassed. > Without them, a subclass could inadvertently use/misuse/overwrite them. Two leading underscores make the instance variable private. I doubt that is required in the example that you gave. Actually, private instance variables are uncommon in general. > These requirements remind me of C++ or Perl, where in order to do the > correct thing, you have to go through extra work. Or, conversely, the > language encourages you to do the wrong thing. Python forces you to be explicit. That way we will know what you are doing, right or wrong. Cheers, Brian From gmfawcett at operamail.com Tue Jul 9 15:53:12 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 9 Jul 2002 12:53:12 -0700 Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 References: <3D24FF3A.4010205@something.invalid> Message-ID: <3d799735.0207091153.258cc430@posting.google.com> Matthias Baas wrote in message > I think the easiest way to compile Pyrex modules (either on Windows, > Linux or anything else) is by using the distutils. For example, to > compile the file shrubbery.pyx you just need the following setup.py > script (which assumes you have "pyrexc" somewhere in your path): You're right, of course, Matthias. It didn't occur to me that I was replacing distutils functionality with my little script. Pyrex the language is so deceptively similar to Python -- it "feels" more like .py-->.pyc compilation than "real" extension programming. I'll revise the suggestions I posted on my Web site. I suppose that one could add a distutils.command.pyrexc as a subcommand of "build_ext" to handle the .pyx compilation. That way the os.system() call in the build script could be avoided. I've never written a distutils command, but perhaps I'll give that a try. Regards, -- Graham From tdelaney at avaya.com Wed Jul 24 19:56:19 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 25 Jul 2002 09:56:19 +1000 Subject: how to count lines in a file ? Message-ID: > From: Richard Jones [mailto:rjones at ekit-inc.com] > > On Thu, 25 Jul 2002 8:31 am, Delaney, Timothy wrote: > > > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt] > > > > > > print len(open('/etc/passwd').readlines()) > > Sorry, I'm coming in to this thread halfway through, but I > need to know why > that code is broken? Is it the > "open('/etc/passwd').readlines()"? That's a > very common pattern, as you note, because people think it is > perfectly > legitemate. What about it is broken? Why isn't it pointed out > more often that > it _is_ broken? We had this discussion just recently, but yes, that is precisely what is broken. What is broken? The file is never explicitly closed. Why is it broken? There are no guarantees that the file will be closed either: 1. Immediately (the assumption in code that uses the above construct); 2. In a timely manner; 3. Before the interpreter exits; 4. Before the computer is turned off. You can usually gather a guarantee of 4 from the OS (all files opened by a process are closed when that process exits) but you then have another problem: open(filename).write(string) Now you not only have no guarantees that the file is closed, but also no guarantees that is the file is closed, it is flushed before closing. The most likely case where this occurs is at program exit - all files are closed, but not flushed. It is explicitly documented that yo may not rely on reference-counting semantics for such things (Paul Rubin - take note please). Tim Delaney To date, many people have relied in (non-) guarantee #1 - that the file will be closed (and flushed) immediately. This in currently not true in Jython, and would not have been true with the proposed patch. Luckily for such people, there is a strong desire not to break "working" code, even if such code really is broken anyway. What happens if I try to use a module containing such code under Jython? Tim Delaney From zopestoller at thomas-guettler.de Wed Jul 24 11:33:07 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 24 Jul 2002 17:33:07 +0200 Subject: Solved: Content-Type Guesser References: <3D3E9E43.2050507@thomas-guettler.de> <3D3E9F7B.2050604@livinglogic.de> Message-ID: <3D3EC8B3.40902@thomas-guettler.de> Walter D?rwald wrote: > Thomas Guettler wrote: > >> Hi! >> >> Has someone a function for guessing the content type >> given a filename? >> >> foo.xml --> text/xml >> foo.html --> text/html >> .... >> >> It should work for the most common file-extensions > > > Python 2.2.1 (#1, Apr 10 2002, 19:08:12) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import mimetypes > >>> help(mimetypes.guess_type) > Help on function guess_type in module mimetypes: > ... Thank you very much! thomas From zuber at centrum.cz Wed Jul 10 03:50:58 2002 From: zuber at centrum.cz (Martin Zuber) Date: Wed, 10 Jul 2002 07:50:58 GMT Subject: Excel type 'time' conversion to string problem Message-ID: Hello, I am writting some utility, which converts data from XLS to formatted ASCII file. I create instance of the COM component Excel.Application and read values using the Cells(x,y).Value. Everything is fine for string and numbers. But when I read the cell with the date/time value, the property Value returns object 'time'. I am unable to convert this value to string representation, I have tried some experiments with the time module, but without success. Can someone help me? Thanks, Martin From zeitlin at seth.lpthe.jussieu.fr Wed Jul 3 12:22:45 2002 From: zeitlin at seth.lpthe.jussieu.fr (Vadim Zeitlin) Date: Wed, 3 Jul 2002 16:22:45 +0000 (UTC) Subject: HT clear some wxPython fram? References: Message-ID: On Wed, 03 Jul 2002 17:05:02 +0200, Klaus Reinhardt wrote: > HOW I CAN CLEAR SOME FRAME? You can't clear a frame (even by shouting at it) because it doesn't make sense. A frame doesn't show anything by itself, so if you draw something on it yourself, you should stop doing it and call Refresh(). But I have a strong feeling that you mean something completely different -- unfortunately it's not at all clear what from your message. Regards, VZ -- GCS/GM d? H+ s++:-- p2 au--- a- w+ v C+++ UBLS+++ P- L++ N++ E--- W++++ M? V-- -po+ R++ G`` !tv b+++ D--- e++++ u++ h--- f+ r++ n- y? From donn at u.washington.edu Mon Jul 15 13:03:52 2002 From: donn at u.washington.edu (Donn Cave) Date: 15 Jul 2002 17:03:52 GMT Subject: Making code 2.1 compatible References: Message-ID: Quoth "Mark McEahern" : |>| did you know that 2.2 has been deemed the release targeted for |>| stability by the pbf? |> |> Where can I read about that? I'm curious to know what they mean. | | I read about that here: | | http://starship.python.net/crew/mwh/europython.html | | There doesn't appear to be a formal announcement here, yet: | | http://www.python-in-business.org/ Interesting, but only in the sense of "tantalizing". It reads like the author (Michael Hudson?) already knew about the basic idea, and assumed the reader does too. I think it would be great if there was some way to arrive at a kind of standard milepost release version, where if you couldn't support every single release from 1.5.2 to 2.Xb2, maybe you could make this one a priority. "You" means library authors, OS vendors, application authors. It sounds like that might be what they're talking about - but since it's already where I'm coming from, I could easily be reading my thoughts into it. And the choice of 2.2 doesn't help clarify it, since it's a pretty new release. The point is frankly to kind of deprecate some new releases, permanently, so the real test of the idea will be the first new release to be rejected for stability. Just thinking about whether these people have the stomache for that, makes me doubt it's what we're talking about after all. But it is cheering to read that Laura Creighton is involved. Donn Cave, donn at u.washington.edu From marklists at mceahern.com Tue Jul 9 14:48:08 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 9 Jul 2002 13:48:08 -0500 Subject: Why self? In-Reply-To: <090720021439257166%pecora@anvil.nrl.navy.mil> Message-ID: > self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) > > is a LOT uglier than > > y= x**2 * t/z + a * FFT(tseries) Do you use emacs? It would probably be trivial to write a Lisp macro that would transform this: y = x**2 * t/z + a * FFT(tseries) into: x = self.x t = self.t z = self.z a = self.a tseries = self.tseries y = x**2 * t/z + a * FFT(tseries) self.y = y // m - From tim.one at comcast.net Fri Jul 19 04:00:41 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 19 Jul 2002 04:00:41 -0400 Subject: C-API question: Memory returned by PyString_AsString In-Reply-To: <2379a09f.0207182349.58a98350@posting.google.com> Message-ID: [Christoph Bennemann] > functions like PyString_AsString return a pointer to a character > vector. Is this memory specially allocated when I call this function Sorry, I don't know what that means. Luckily, it's irrelvant . > (which implies I have to take care of it in my program) or is this > merely a pointer to a character vector stored by the Python > interpreter (implying that I should not free the memory). I assume > that the later is correct, but would like to have a definitive answer. No Python API function returns a pointer you should free() or realloc(). In the case of PyString_AsString, you're getting a (shared with Python) pointer into the guts of a pre-existing Python string object, and trying to free() that would lead to disaster. From chris.gonnerman at newcenturycomputers.net Thu Jul 25 20:01:29 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 25 Jul 2002 19:01:29 -0500 Subject: setup.py OS X issue References: <20020725194854985-0400@news.mindspring.com> Message-ID: <001b01c23437$9be4bd60$0101010a@local> ----- Original Message ----- From: "Ross M Karchner" > Hey, > > I am trying to install MySQLdb ( http://sourceforge.net/projects/mysql- > python ) > > and I am unable to install this Have you considered giving more details? (perhaps the PSU was here... there's no punctuation at the end of his last sentence... maybe they are Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From simon at uggs.demon.co.uk Sun Jul 7 17:54:39 2002 From: simon at uggs.demon.co.uk (Simon Foster) Date: Sun, 07 Jul 2002 21:54:39 GMT Subject: Splitting lines in a file Message-ID: <3d28b895.70324260@news.dsl.pipex.com> Quick query, hopefully, How come when I split a file on arbitrary whitespace I get one fewer lines then when I split on end of line? In the case when I split on the \n the last line has zero length. C:\hexbin>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = file( 'siu_build.hex' ).read() >>> len( f.split() ) 1254 >>> len( f.split( '\n' )) 1255 >>> lines = f.split( '\n' ) >>> len( lines[-1] ) 0 >>> From fakeaddress at nowhere.org Sat Jul 6 19:31:13 2002 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 06 Jul 2002 23:31:13 GMT Subject: sending a file through sockets References: Message-ID: <3D277DDC.1040705@nowhere.org> brueckd at tbye.com wrote: [Bryan Olson had written:] >>That's the system doing the shutdown for you. If you think it's too >>dangerous, well, > > ?? Not sure what you're talking about here. I don't remember saying > anything was too dangerous. My intended meaning was "if you think relying on shutdown to determine end-of message is too dangerous..." >>the code you posted didn't actually check the length. >>The explicitly sent length only protected against the server sending >>more data than that. > > Yes, as I already pointed out, I failed to include the standard disclaimer > of "this works in my brain's Python interpreter, YMMV". Well it did work, the same as it would work without the length prefix. So in my response when I saw the length was useless, I thought I'd keep simple and remove it, consistent with my recommendation of the HTTP protocols. It also explains good socket programming practice: shutdown the writing end, and read till the other end's shutdown. > I actually spend > most of my days writing network agents in Python (so I do know how to do > it "right" or whatever), but I was just posting some code from memory to > help the guy out; I think it's pretty obvious that you don't cut code from > a Usenet post and paste it into your production system and expect no > problems. O.K., and if you read my first post, I was entirely matter-of-fact in pointing out the issues. No reason to get defensive. Do you actually believe use of INADDR_ANY in connect() is doing it right? >>Actually the sockets in the Python 2.2 (Windows) library I have support >>timeouts and select(). The problem is that the protocol libraries don't >>use them. > > > What I'm saying is that, in CVS, Modules/socketmodule.c has Michael > Gilfix's timeout socket implementation, e.g. socket objects have > settimeout(). Also, once you have timeout sockets, most of the protocol > libraries don't _need_ to worry about them. For example, in the Python > version of timeoutsocket.py, you can just set a global timeout value and > then the protocol libraries work automatically because an exception gets > raised on timeout and control returns to your app. There's not much more > than this they could do intelligently even if they _did_ know about > timeouts themselves. O.K. I'm not familiar with Gilfix's implementation. I tried Tim O'Malley's, and the timeout on accept() caused servers to bomb out just because no one had yet made a connection. I'm a security engineer, so I tend to look at adversarial cases, hence my call for a "timeout discipline" rather than just a global timeout. >>On pull-the-plug a recv won't detect the connection loss until the local >>system tries a keepalive probe, which is typically two hours. > > > Apparently we're talking about different things because I just tried it > and got a socket.error exception ('connection reset by peer') on Windows. On the recv() side? Sure doesn't work that way for me. Any idea how it knew? --Bryan From glongman at ilangua.com Tue Jul 30 10:05:30 2002 From: glongman at ilangua.com (Graeme Longman) Date: Tue, 30 Jul 2002 15:05:30 +0100 Subject: Searching for email address Message-ID: <3D469D2A.28154B51@ilangua.com> Hi, I'm writing some code which searches html for email addresses. Does anyone out there have a good regular expression syntax for searching for the email string, I'm sure this must've been done a few times before. Thanks in advance, Graeme From polux2001 at wanadoo.fr Wed Jul 31 12:58:14 2002 From: polux2001 at wanadoo.fr (polux) Date: Wed, 31 Jul 2002 18:58:14 +0200 Subject: newbie : unicode References: <3D473933.8040306@wanadoo.fr> Message-ID: <3D481726.20500@wanadoo.fr> I did whMartin v. Loewis wrote: > polux writes: > > >>I'm using IDLE for windows and when i'm using a char like ? or ? (i'm >>french :)), i get the error message : UnicodeError: ASCII encoding >>error: ordinal not in range(128) >> >>but if i've understood, Python works with unicode, so there should be >>no problem ! > > > The problem is that Python does not know what encoding to use for > those characters; by default, it assumes ASCII, but ASCII does not > support those characters. A work-around is described in > > http://www.python.org/doc/FAQ.html#4.102 > > Regards, > Martin > at's written but it didn't work what is or where is sitecustomize.py ? it doesn't exist on my computer i've created it but it doesn't change anything i've made the corrections in site.py too but no result.....please help From amir at clockwise3d.com Wed Jul 24 05:05:52 2002 From: amir at clockwise3d.com (Amir Hadar) Date: 24 Jul 2002 02:05:52 -0700 Subject: locale on Japanese win XP Message-ID: <3324f4eb.0207240105.48db826e@posting.google.com> I'm trying to get the locale settings with the locale module under Japanese windows XP. when I try to set the locale settings with the following command: locale.setlocale(locale.LC_ALL,'') the locale throws the following exception: locale.Error locale settings not supported Any ideas? From cliechti at gmx.net Tue Jul 23 11:13:43 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 17:13:43 +0200 Subject: Python on W2000 References: Message-ID: "tony papadato" wrote in news:mailman.1027433045.3204.python-list at python.org: > it is possible to generate an executable file and run it on different > machines without python installed on them ? Best regards sure, use one of these tools: http://starship.python.net/crew/theller/py2exe/ http://www.mcmillan-inc.com/install1.html chris -- Chris From mis6 at pitt.edu Sun Jul 28 10:52:42 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 28 Jul 2002 07:52:42 -0700 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> <3d438609$1@duster.adelaide.on.net> <3d439616$1@duster.adelaide.on.net> Message-ID: <2259b0e2.0207280652.202f1721@posting.google.com> Now I see the source of my confusion. I thought the print "statement" was actually an expression with result None. However in Python result=print("something") gives a syntax error. Then my question is: why Guido decided to keep the distinction between statements (with no value returned) and expressions ? what are the advantages ? is it a matter of personal taste ? Sorry if these questions sounds naive, Michele From skip at pobox.com Sat Jul 20 13:02:52 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Jul 2002 12:02:52 -0500 Subject: Funny behaviour of MySQLdb In-Reply-To: <1027183241.17774.143.camel@d168.stw.stud.uni-saarland.de> References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> <1027183241.17774.143.camel@d168.stw.stud.uni-saarland.de> Message-ID: <15673.38844.283090.960766@localhost.localdomain> Heiko> btw. If anybody is interested in the project as a whole, once I Heiko> get it to work, then just say so. What this server basically does Heiko> is offer XML-RPC services to a frontend, and is especially well Heiko> suited to get all that database and user administration code out Heiko> of a web-application. Precisely what I do. Perhaps I should extract just the XML-RPC skeleton and the backend database access code for people. As I mentioned in my previous post, I don't seem to encounter the problems you are having. I do things a bit differently than you. Perhaps there's something subtly incorrect about the way you are doing things. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From skip at pobox.com Tue Jul 2 23:09:19 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 2 Jul 2002 22:09:19 -0500 Subject: curses-based menu module? In-Reply-To: <3D218499.38153895@anansispaceworks.com> References: <3D218499.38153895@anansispaceworks.com> Message-ID: <15650.27359.948856.70499@12-248-8-148.client.attbi.com> Terry> Curses itself seems really easy to use, but is kind of a Terry> low-level interface. Clearly, I will be well-served to make a Terry> higher-level interface for creating and using menus. But I have Terry> a couple of questions: Terry> Am I reinventing the wheel? Is there already a high-level Terry> interface available (this seems rather likely, though I haven't Terry> found one). Dunno, but the first place I'd look is anygui: http://anygui.sourceforge.net/ Checking the platforms page: http://anygui.sourceforge.net/platforms.php suggests that curses is a working platform. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From whisper at oz.net Tue Jul 9 19:48:18 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 9 Jul 2002 16:48:18 -0700 Subject: openprojects python room is ruled by dangerous people In-Reply-To: Message-ID: > My new complaint about #python is a rather locker-room atmosphere > that seems to have snuck into the place over time. I suspect this is > yet more proof of the evil robot conspiracy. Darn, and here I thought that if you had a PDA with python on it, it was a pocket python ;-) > Regards, > > Martijn > -- > History of the 20th Century: WW1, WW2, WW3? > No, WWW -- Could we be going in the right direction? Wow, I missed WW3! Regards, Dave LeBlanc Seattle, WA USA From eugene1977 at hotmail.com Fri Jul 19 13:38:20 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Fri, 19 Jul 2002 12:38:20 -0500 Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) Message-ID: hi.. i'm trying to parse a xml file and feed into postgresql... the xml file contains korean.. is this python problem or postgres problem? and of course how do i solve this?? thanks a lot xml file format ---------------- -------------------- error msg -------------- self.url: http://music.2000mp3.com/artist_viewk.php3?mode=abcd&name=A&lg= self.title: 2000 MP3 : MP3 ???????????????????????? Traceback (most recent call last): File "second.py", line 78, in ? parser.parse("smallhistory2.xml") File "/usr/lib/python2.2/xml/sax/expatreader.py", line 90, in parse xmlreader.IncrementalParser.parse(self, source) File "/usr/lib/python2.2/xml/sax/xmlreader.py", line 123, in parse self.feed(buffer) File "/usr/lib/python2.2/xml/sax/expatreader.py", line 143, in feed self._parser.Parse(data, isFinal) File "/usr/lib/python2.2/xml/sax/expatreader.py", line 217, in start_element self._cont_handler.startElement(name, AttributesImpl(attrs)) File "second.py", line 67, in startElement sqlclause = 'INSERT INTO history VALUES (' + tmp + self.url + tmp +","+ tmp + self.title + tmp + "," + self.firsttime + "," + self.lasttime + "," + self.visits + " )" UnicodeError: ASCII decoding error: ordinal not in range(128) --------------------- code ---------------- #!/usr/bin/python import sys import string import xml.sax.handler import _pg user=_pg.set_defuser('postgres') db=_pg.connect('test','localhost') def converter( oldString): newString = oldString for aChar in HistoryHandler.specialCharacters: if ( aChar in oldString): newString=string.replace(oldString, aChar, "\\"+aChar) return newString class HistoryHandler(xml.sax.handler.ContentHandler): specialCharacters = [ '"', "'", "`"] # def __init__(self): # self.inItem =0 # self.mapping={} # self.count=0 def startElement(self, name, attributes): if name=="item": self.url=attributes["url"].encode('utf-8') self.title = attributes["title"].encode('utf-8') for aChar in self.specialCharacters: if ( aChar in self.url): if aChar == "'": print "yo" print "before " + self.url self.url=converter(self.url) print "after " +self.url if ( aChar in self.title): self.title=converter(self.title) self.firsttime=attributes["first_time"] self.lasttime=attributes["last_time"] self.visits=attributes["visits"] tmp = "\"" sqlselect = 'SELECT url, visits FROM history WHERE url = \'' + self.url + "';" result = db.query(sqlselect).getresult() if(result): existUrl = str(result[0][0]) existUrl = converter(existUrl) newVisits=str(result[0][1]+ int(self.visits)) sqlclause = 'UPDATE history SET visits =' + newVisits + ' WHERE url = \'' + existUrl + '\'' else: print "self.url: " + self.url print "self.title: " + self.title sqlclause = 'INSERT INTO history VALUES (' + tmp + self.url + tmp +","+ tmp + self.title + tmp + "," + self.firsttime + "," + self.lasttime + "," + self.visits + " )" print sqlclause db.query(sqlclause) # import pprint parser = xml.sax.make_parser( ) handler = HistoryHandler( ) parser.setContentHandler(handler) parser.parse("smallhistory2.xml") # pprint.pprint(handler.mapping) From roger at projekt01.ch Fri Jul 5 14:05:23 2002 From: roger at projekt01.ch (Roger) Date: Fri, 5 Jul 2002 20:05:23 +0200 Subject: dynamic path to a method ??? Message-ID: <000301c2244e$88ef0510$0b01a8c0@projekt01.local> Can anybody tell me how I can construct a dynamic path with attributes in a python class? my situation is: I get the classname, methodname and attributes by a dynamic form. They are strings and the names and attributes are dynamic. I do a iteration over the request an split the names and attributes. Example after iteration over the request: class (instance) = 'personManager' method = 'addPerson(firstname='', lastname='')' attribute1, firstname = 'max' attribute2, lastname = 'miller' how can I construct a dynamic path like: personManager.addPerson( firstname='max', lastname='miller') with other attributes from the form, the call can look like this: MasterClass.addObject( name='manager') and so on... how can i handel this. ??? Thanks a lot. Mit freundlichen Gr?ssen Roger Ineichen ___________________________ Projekt01 GmbH www.projekt01.ch Langackerstrasse 8 6330 Cham phone +41 (0)41 781 01 78 mobile +41 (0)79 340 52 32 fax +41 (0)41 781 00 78 email r.ineichen at projekt01.ch ___________________________ END OF MESSAGE From grante at visi.com Wed Jul 31 14:24:15 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 31 Jul 2002 18:24:15 GMT Subject: Can't detect EOF with pylibpcap References: <8qU19.30825$eH2.13210511@ruti.visi.com> Message-ID: In article <8qU19.30825$eH2.13210511 at ruti.visi.com>, Grant Edwards wrote: > I'm using pylibpcap 0.4 to analyze capture files created by > Ethereal. It works nicely except I can't detect end of file. > > When you use the next() method, it just never returns when it > hits end of file. Hmm. The next() method seems to be working better now. It returns (, None, timestamp) at EOF. I would have sworn it wasn't doing that before... Still, it would be nice to be able to use dispatch() or loop(). -- Grant Edwards grante Yow! I'm also pre-POURED at pre-MEDITATED and visi.com pre-RAPHAELITE!! From mh at esh-online.de Mon Jul 15 10:40:43 2002 From: mh at esh-online.de (Michael Hoffmann) Date: Mon, 15 Jul 2002 16:40:43 +0200 Subject: could not import mod_python.apache Message-ID: Hi, I've the folowing Error when I try to run my pythonscript: make_obcallback(): could not import mod_python.apache. make_obcallback(): could not call init. [Mon Jul 15 16:12:46 2002] [error] [client 62.226.50.138] python_handler: make_obcallback returned no obCallBack! but httpd start is ok: [Mon Jul 15 16:14:54 2002] [notice] Apache/1.3.19 (Unix) (SuSE/Linux) mod_python/2.7.2 Python/2.0 mod_ssl/2.8.3 OpenSSL/0.9.6a PHP/4.0.6 mod_perl/1.25 mod_th rottle/3.0 mod_layout/1.0 mod_fastcgi/2.2.2 mod_dtcl configured -- resuming normal operations [Mon Jul 15 16:14:54 2002] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) The directives are: AddHandler python-program .py PythonHandler mptest PythonDebug on Options +ExecCGI the script ist: from mod_python import apache def handler(req): req.content_type = "text/plain" req.send_http_header () req.write ("Hello World!") return apache.OK any Idea????? Regards Michael From eric.brunel at pragmadev.com Tue Jul 30 06:38:18 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 30 Jul 2002 12:38:18 +0200 Subject: condensed syntax? References: <7d5281ea.0207300150.1fcef017@posting.google.com> Message-ID: Matthieu Bec wrote: > is there any way to condense the following: > > # scan subdir(s) within mydir > for d in os.listdir(mydir): > dd=os.path.join(mydir,d) > if os.path.isdir(dd): > self.subdir.append(dd) > > > what follows doesn't work, but I'm thinking of a something like: > > self.subdir=[(os.path.isdir(dd=os.path.join(mydir,d))?dd:pass) > for d in > os.listdir(mydir) ] Try (untested): self.subdir = [os.path.join(mydir, d) for d in os.listdir(mydir) if os.path.isdir(os.path.join(mydir, d))] You won't be able to make an assignment (like to your dd variable) in a list comprehension (except by utterly horrible and unreadable ways...), hence the double os.path.join... You may also do: self.subdir = filter(os.path.isdir, [os.path.join(mydir, d) for d in os.listdir(mydir)]) Maybe a tad more readable, but probably less efficient too... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From mgerrans at mindspring.com Fri Jul 12 03:03:28 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Fri, 12 Jul 2002 00:03:28 -0700 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: > XML combines all the inefficiency of text-based formats with most of the > unreadability of binary formats :-) Maybe it was surreptitiously introduced by a consortium of router and disk drive manufacturers, to ensure increasing sales of hardware, by its voracious appetite for bandwidth and disk space. ;-) From wilk-spamout at flibuste.net Thu Jul 18 16:00:26 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Thu, 18 Jul 2002 22:00:26 +0200 Subject: safe_mode of modpython ? Message-ID: <20020718220026.53776b94.wilk-spamout@flibuste.net> Hi, Is there an equivalent of the safe_mode and openbasedir of php in a python module for apache ? thanks -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From mwh at python.net Tue Jul 16 05:37:58 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 16 Jul 2002 09:37:58 GMT Subject: Making code 2.1 compatible References: Message-ID: "Donn Cave" writes: > Quoth "Mark McEahern" : > |>| did you know that 2.2 has been deemed the release targeted for > |>| stability by the pbf? > |> > |> Where can I read about that? I'm curious to know what they mean. > | > | I read about that here: > | > | http://starship.python.net/crew/mwh/europython.html > | > | There doesn't appear to be a formal announcement here, yet: > | > | http://www.python-in-business.org/ > > Interesting, but only in the sense of "tantalizing". It reads > like the author (Michael Hudson?) Yes. I'm not good at mentioning my own name on my web pages... > already knew about the basic idea, and assumed the reader does too. Which parts confuse you? Or has Tim cleared it up? [Tim, later] > If they don't, we do -- the volunteer bugfix-release Patch > Czars so far have taken a strong "no new features!" stance. Note that a selling point of the "no new features!" stance is a reduction of the work required... every time I said "no" to a patch, there was less fiddling with cvs to do. Cheers, M. -- I have no disaster recovery plan for black holes, I'm afraid. Also please be aware that if it one looks imminent I will be out rioting and setting fire to McDonalds (always wanted to do that) and probably not reading email anyway. -- Dan Barlow From joec at mill.co.uk Mon Jul 22 11:42:32 2002 From: joec at mill.co.uk (Joe Connellan) Date: Mon, 22 Jul 2002 16:42:32 +0100 Subject: unsigned ints and operator.rshift References: <3D3C1802.948E2D99@mill.co.uk> Message-ID: <3D3C27E8.CD7DC56@mill.co.uk> bingo! thanks Michael Hudson wrote: > Joe Connellan writes: > > > I'm storing info in an int (32bits) that I'm wanting to shift left and > > right using operator.[l|r]shift the problem is that because the int is > > signed rshift fills in 1's rather than 0's on negative numbers - is > > there any way to store the 32bits as an unsigned int do get around this? > > Use longs and keep masking? There's no guarantee that Python int's > are 32 bits -- they're 64 bits on alphas f'ex. > > Cheers, > M. > > -- > LINTILLA: You could take some evening classes. > ARTHUR: What, here? > LINTILLA: Yes, I've got a bottle of them. Little pink ones. > -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From spp at monaco377.com Mon Jul 29 11:13:21 2002 From: spp at monaco377.com (=?iso-8859-1?Q?S=E9bastien?= Cottalorda) Date: Mon, 29 Jul 2002 17:13:21 +0200 Subject: Prob installing Python 2.2.1 on Redhat 7.0 Message-ID: <3D455B90.4A3FBF16@monaco377.com> Hi all, I tried to compile the source code of Phyton 2.2.1 on a Red Hat 7.0 (kernel 2.2.16.22) with gcc (ver 2.96). The ./configure program didn't see any errrors. I immediately obtain the following error, after make command: ---------------------------------- gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/python.o Modules/python.c In file included from Include/Python.h:62, from Modules/python.c:3: Include/pyport.h:480:2: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." make: *** [Modules/python.o] Erreur 1 ----------------------------------- If somebody as a clue ? Thanks in advance. Sebastien From emile at fenx.com Fri Jul 12 13:35:31 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Jul 2002 17:35:31 GMT Subject: Input again (!!@#&#$^@#$) References: Message-ID: Seth Ainsley > Input again. Thanks for the answer on what I thought was raw.input (but was actually raw_input), but how would it be for me to get something like the following to work: > input = raw_input('What's your answer? ') You're mixing your single quotes. Try: input = raw_input("What's your answer? ") > if input = "Yes" then print "Something" Python doesn't have in-line assignment or a then. This s/b: if input == "Yes": print "Something" > else print "Something else" else: print "Something else" Go to the newbies page at http://python.org/doc/Newbies.html and work through the tutorial at http://python.org/doc/current/tut/tut.html. It looks like you're trying to write in basic, not python. HTH -- Emile van Sebille emile at fenx.com --------- From jb at cascade-sys.com Sat Jul 13 02:01:57 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 12 Jul 2002 23:01:57 -0700 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: <3D2FC255.41635CD9@cascade-sys.com> Donn Cave wrote: > Quoth eddie at holyrood.ed.ac.uk (Eddie Corns): > ... > | Basically, when you layout code you need to think about how to convey to the > | reader what's going on. In constructions like the above I believe it's much > | easier to see that it's only ever looking at the beginning of the line and the > | table like structure makes it easy to map what it finds to what gets done. > > Don't try to come up with nifty ways to convey to the reader what's > going on. Read the coding standards in PEP 8, and follow them to > the letter. You can't do better. "...to the letter." This strikes me as a "foolish consistency." I think the standard is good overall but what makes it best is it acknowledges up front that there's some room for personal judgment and common sense. Among adults I expect we all can accommodate a little flexibility in following these rules. So to some extent, I regard interpreting it "to the letter" to be inconsistent with how the PEP is written. My particular problem is that some of the express rules about horizontal white space actually hinder readability. As Mr. Corns points out, some sections of code are inherently tabular and I agree that presenting them in tabular format is the clearest way to format the code. You simply cannot argue that the extra white space obscures the meaning because it obviously adds clarity. You could argue that it doesn't help a lot or that it IS a bit more tedious to maintain. (Of course part of the maintenance problem is a direct consequence of Fearless Leader's treasonous reversal of position on horizontal tabs.) But from a readability standpoint, it is a superior (and harmless) deviation from the standard. I'll concede that most deviations from the standards do hinder readability. Overall, it's a pretty good standard. But it's not perfect and horizontal white space is one place where, BDFL's personal biases notwithstanding, the standard is overly specific. I guess the trouble it that the nature of the language intrinsically avoids so many of the important battles that we're left to quibble about secondary and tertiary matters. Of course, I come from a far away land, where Python is but one tool among many on the work bench, rather than some kind of a religion. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From alex.tournier at iwr.uni-heidelberg.de Wed Jul 10 03:40:37 2002 From: alex.tournier at iwr.uni-heidelberg.de (Alex Tournier) Date: 10 Jul 2002 00:40:37 -0700 Subject: leastSquaresFit References: Message-ID: Fernando P?rez wrote in message > Many numeric functions do not > implicitly convert lists to arrays (though some can operate on lists as well > as arrays). Try data = Numeric.array(data) and see what happens. > > f I tried as you said, putting it through array(), but still get the same message! Could there be a problem with the FirstDerivatives.py module?? Alex From see_reply_address at something.invalid Wed Jul 10 00:44:37 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 10 Jul 2002 16:44:37 +1200 Subject: A better self References: <3D2B6EFB.4DA9A4DB@alcyone.com> Message-ID: <3D2BBBB5.1030209@something.invalid> Erik Max Francis wrote: > so that the notation `.attribute' is just a shortcut for > `self.attribute'. Or it could be a shorthand for .attribute, so you could still call the first arg something else. But I tend to agree that a leading "." is a bit *too* unobtrusive! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From rob Fri Jul 5 22:25:34 2002 From: rob (Rob Andrews) Date: Sat, 06 Jul 2002 02:25:34 GMT Subject: idiots guide to python References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: To see a variety of different Python stuff for the newbie, and plenty of examples of source code, also feel free to check out Useless Python (http://uselesspython.com). And I *highly* recommend the Python Tutor email list, where you can ask all manner of *idiot* questions and be treated like the non-idiot you are (http://mail.python.org/mailman/listinfo/tutor). Rob http://uselesspython.com baptism_of_fire_842 at hotmail.com (Mike Johnson) wrote in news:626290cd.0207051529.518f4ce7 at posting.google.com: > I am starting an A-Level course in computing in september, and i will > need to learn how to use python. I have no previous experience of > programming, but could anyone point me in the direction of an "Idiots > Guide"? > > thanks. > > Mike Johnson From mgilfix at eecs.tufts.edu Thu Jul 25 22:48:16 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Thu, 25 Jul 2002 22:48:16 -0400 Subject: how to count lines in a file ? In-Reply-To: ; from tdelaney@avaya.com on Fri, Jul 26, 2002 at 08:51:03AM +1000 References: Message-ID: <20020725224816.A26774@eecs.tufts.edu> On Fri, Jul 26 @ 08:51, Delaney, Timothy wrote: > > From: Michael Gilfix [mailto:mgilfix at eecs.tufts.edu] > > > > So, out of curiosity, if I define a metaclass on top of some > > file object, is this still considered broken code? Is the > > __del__ semantics meaningless? Would this object ever become > > part of garbage collection? > > > > class file: > > def __init__ (self, path): > > self.file = open (path) > > def __getattr__ (self, name): > > return getattr (self.file, name) > > def __setattr__ (self, name, value): > > return setattr (self, name, value) > > def __del__ (self): > > self.file.close () > > First of all, you shouldn't use the name "file" for your class (file is a > builtin name, and is an alias for open). Secondly, you're using the term Ah, wasn't aware of that alias. At any rate, it's just an example. > "metaclass" incorrectly here (at least in respect to python) - the term you > are looking for is "proxy", "delegate" or even "adaptor". Ok. Proxy class sound sgood to me. > There are no problems with the above. You have created a normal delegation > class. If an instance does not participate in a cycle (in CPython) it will > be collected as soon as the last reference to it goes away. If it does > participate in a cycle, it will probably be collected at some later stage. > In Jython, all objects participate in garbage collection. Sorry, I'm a little unclear on this one. Do I actually gain anything by creating this proxy class over using the regular file object? Does the use of __del__ add anything? Meaning, will the file.close call definitely be called at the "some later stage" or whenever the object is freed? -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From muk_pr at yahoo.com Wed Jul 31 20:42:18 2002 From: muk_pr at yahoo.com (vb) Date: 31 Jul 2002 17:42:18 -0700 Subject: how to use PyRun_String Message-ID: <76710511.0207311642.78516008@posting.google.com> after a PyRun_SimpleString("s='a string'"); how can I get s as a C PyObject*? I tried PyRun_String but I dont know what to pass in last 2 params.(globals & locals dictionary) so it returns NULL. Thanks. From henrik.motakef at web.de Sat Jul 20 20:08:47 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 21 Jul 2002 02:08:47 +0200 Subject: XSLT processor References: <21k_8.103407$%%2.4630636@news2.east.cox.net> Message-ID: <871y9yosc0.fsf@pokey.henrik-motakef.de> thehaas at binary.net writes: > Stefan Heimann wrote: > > Saxon - a XSLT processor written in Java - provides such an internal > > API. Does anyone know if there is something similar for python? > > I have no idea if the "pure-Python" XSLT processors (4xslt, etc.) have > that, 4XSLT has an API to write extension elements/functions. I can't find the documentation on the net right now, but my (oldish) installation came with the files 4XPath-Api.html and 4XSLT-Api.html in the doc/html directory that should help. hth Henrik From piet at cs.uu.nl Tue Jul 9 09:41:48 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 09 Jul 2002 15:41:48 +0200 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> <3D2A57B9.8EDD2BF0@engcorp.com> <14rkiu8fnp8chiua156k2qm9r1s2vf5trs@4ax.com> <3D2A7088.755DD676@alcyone.com> Message-ID: >>>>> Erik Max Francis (EMF) writes: EMF> Lowel Stern wrote: >> fp = os.popen('C:\python_scripts\prog %s') % (key) EMF> fp = os.popen('C:\python_scripts\prog %s' % key) fp = os.popen('C:\\python_scripts\\prog %s' % key) -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From aleax at aleax.it Sat Jul 13 05:11:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 13 Jul 2002 09:11:43 GMT Subject: dir() shows strange behaviour with VPython References: <3d2fe41e$0$25552$91cee783@newsreader02.highway.telekom.at> Message-ID: Gregor Lingl wrote: > I thought to understand the dir() function, but... dir() is somewhat in transition between Python 2.1 and 2.2. Not sure what Python level should be installed with Visual-06-14. It does matter which exact level you did install, and on which platform, though. I just downloaded and installed Visual-2002-07-07 on top of my Python 2.2.1 but the s.__members__ access, and thus also dir(s), just kills the Python interactive session stone dead with 'Aborted' as the only message. Maybe the 06-14 version had its own problems -- not quite as serious as 07-07's (at least with Python 2.2.1 on Mandrake Linux 8.2:-) but enough to give the anomalies you observe. (It's also possible that I made some mistake in installation, of course, but I closely followed the specific instructions for Mandrake on the "additional info" page of Visual). Alex From tg5027 at citlink.net Wed Jul 24 12:32:04 2002 From: tg5027 at citlink.net (terry) Date: Wed, 24 Jul 2002 12:32:04 -0400 Subject: Numeric data question In-Reply-To: <%Nz%8.15893$A72.86385@news1.mts.net> References: <%Nz%8.15893$A72.86385@news1.mts.net> Message-ID: >> Well, PostgreSQL does have a money type, but IIRC it's just a >> float with a fixed number of decimal places. You could just >> use pennies as the unit and integer math though. Thanks Tim, it is a more complex representation than just float as it also contains the decimal places. I haven't seen the exact internal format in Postgres, but it's a very common datatype in many databases. In general it's not appropriate/legal to use integer or floating point math when dealing with money. It creates too many coding dependent variations in results - not to mention maintenance nightmares. I'm guessing now (from lack of real experience) that being a 'typeless' language that I would be forced into contriving a method for handling money such that I could never code something straightforwardly like: TotalCost = Quantity * UnitCost (where Quantity is integer and the others money). Am I loonie, or is Python just not inherently suitable for accounting applications for this reason? terry From jknapka at earthlink.net Mon Jul 1 22:26:39 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 02 Jul 2002 02:26:39 GMT Subject: python threads and the linuxthread pthread library References: Message-ID: <3D210EFB.51E375EA@earthlink.net> Tim Peters wrote: > > [anton wilson] > > ... > > Is the Python Virtual Machine it's own thread? > > No. All threads run in the PVM, but the GIL serializes their PVM time. Does Jython lift this limitation, by any chance? Or is the GIL a universal and unchangable Python artifact? Thanks, -- Joe From tim_one at email.msn.com Wed Jul 17 23:49:16 2002 From: tim_one at email.msn.com (Tim Peters) Date: Wed, 17 Jul 2002 23:49:16 -0400 Subject: SSL support in 2.2.1/win In-Reply-To: <3d362ab9@duster.adelaide.on.net> Message-ID: [Gerald Squelart] > I've downloaded and installed python 2.2.1 on my win2k machines, and > tried my first program... And I was disappointed to see that SSL support > is not enabled by default. Wow! I didn't know print "Hello, world." required SSL . > That was embarassing since my colleague made a similar > program in perl, which seems to support SSL by default. > Any reason for not including SSL by default? > Do I have to rebuild the world to get SSL? > Will it be included in future versions? > ... Help by giving Mark Hammond the feedback he's asking for: http://www.python.org/sf/576711 I can't make time for it, short of someone approaching my employer with an unexpected offer to fund the work. If it came to that, I'd advise paying Mark to work on it instead. if-he-gives-any-more-he'll-run-out-of-blood-ly y'rs - tim From wadebk at nswc.navy.mil Thu Jul 18 07:47:56 2002 From: wadebk at nswc.navy.mil (Brian) Date: 18 Jul 2002 04:47:56 -0700 Subject: netCDF in 2.2 References: Message-ID: <57fe7929.0207180347.fe71ecc@posting.google.com> brueckd at tbye.com wrote in message news:... > On 17 Jul 2002, Brian wrote: > > > wadebk at nswc.navy.mil (Brian) wrote in message news:<57fe7929.0207120253.37865e70 at posting.google.com>... > > > I'm a relative newbie in Python and I can't get netCDF to work under > > > 2.2 on Windows. I found a .pyd file that makes it work under 2.1 > > > (scientific_netcdf.pyd), but it doesn't work under 2.2. Does anyone > > > have the equivalent version of this file or another easy solution? > > > > I can't believe that nobody else has run into this before. Please, if > > someone knows how to do this tell me. > > Have you tried the netCDF mailing list? netCDF isn't exactly ubiquitous, > so it shouldn't be too surprising that the intersection of c.l.py readers > and netCDF users is close to zero. ;-) > > Where did you get the .pyd that works with 2.1? Maybe whoever built it has > or will build you one for 2.2. Or do they at least make available the > source code (so that you or some kind soul could build you a new .pyd)? > Give us some more details and then maybe we can be of more help. > > Have fun, > Dave I found it on this newsgroup. Apparently it is part of the Scientific package. From pinard at iro.umontreal.ca Mon Jul 8 11:36:42 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 11:36:42 -0400 Subject: `~/.pythonrc' `from __future__ import' In-Reply-To: References: Message-ID: [Michael Hudson] > try: > from two_point_two_using_module import func > except SyntaxError: # is that what bogus future statements should > # really raise? too late now, I guess > from two_point_one_using_module import func > Writing code that uses 2.2 features where possible but still runs on > 2.1 is a pain, but I'm not sure how it could have been done better, really. I agree with you, thanks for the hints. Your approach is workable, at least for packages big enough to warrant many modules. It might also mean that for really simple packages, such portability is not affordable, so better plainly write for the oldest Python one wants to support. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mimurra3 at vt.edu Wed Jul 31 14:39:49 2002 From: mimurra3 at vt.edu (mimurra3) Date: Wed, 31 Jul 2002 14:39:49 -0400 Subject: source installation issue Message-ID: <3D4953AC@zathras> All, I am attempting to install Python from source on my Mac OS-X system. I downloaded the tar file to my desktop and expanded it there. I ran './configure,' 'make,' and 'make install' without any issues. However, the only way I can get the interpreter to start is by going to /usr/local/bin and typing './python' On my Linux systems at work Python can be started directly from any directory simply by typing 'python.' I would like this ability also so I am not limited to one directory. Does anybody have any suggestions on how to make the python executable work globally? The only thing I can think of is that I ran 'make' etc. after expanding the tarball from my Desktop directory. Should I have untared it directly into /usr/local/bin? Any help would be greatly appreciated. I use UNIX systems regularly but have never attempted to install a program by myself. thanks, Mike -------------------------- Michael Murray Virginia Polytechnic Institute and State University Biochemistry Department 201 Engel Hall lab: 540-231-0505 email: mimurra3 at vt.edu From robin at jessikat.fsnet.co.uk Tue Jul 16 08:35:15 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 16 Jul 2002 13:35:15 +0100 Subject: distutils macro string quoting Message-ID: Is there a standard way to get a distutils string pre-processor macro defined properly? I find that I need 'macros':[('MYSTRDEF','\\"%s\\"' % myStr)], to get the right things to happen under win32 and it seems a bit OS dependent to me. -- Robin Becker From china at thewrittenword.com Tue Jul 2 00:12:55 2002 From: china at thewrittenword.com (Albert Chin-A-Young) Date: Tue, 02 Jul 2002 04:12:55 -0000 Subject: zipfile and Tru64 UNIX References: Message-ID: Albert Chin-A-Young wrote: > Anyone aware of problems with zipfile against Python 2.0.1, 2.1.2, or > 2.2.1 and 64-bit systems like Tru64 UNIX? I'm testing against 4.0D and > 5.1 and a zipfile that tests out using testzip() on IRIX, HP-UX, and > Solaris gives a CRC error on Tru64 UNIX. I've tried creating the zipfile > with the UNIX zip program or zip.write() and get the same error. The > only bug I could find on sf.net was: > http://sourceforge.net/tracker/index.php?func=detail&aid=453208&group_id=5470&atid=105470 > >> import zipfile >> zip=zipfile.ZipFile('/tmp/a.zip','r') >> zip.printdir() > File Name Modified Size > vmunix 2002-05-31 14:29:06 9225952 >> foo=zip.read('vmunix') > Traceback (most recent call last): > File "", line 1, in ? > File "/opt/TWWfsw/python221/lib/python2.2/zipfile.py", line 354, in > read > raise BadZipfile, "Bad CRC-32 for file %s" % name > zipfile.BadZipfile: Bad CRC-32 for file vmunix >> bar=zip.getinfo('vmunix') >> bar.CRC > -2068761705 > > The output of binascii.crc32 on the contents of 'vmunix' is: > 2226205591 > or from the unzip program: > $ unzip -v /tmp/a.zip > Archive: /tmp/a.zip > Length Method Size Ratio Date Time CRC-32 Name > -------- ------ ------- ----- ---- ---- ------ ---- > 9225952 Stored 9225952 0% 05-31-02 14:29 84b13397 vmunix > -------- ------- --- ------- > 9225952 9225952 0% 1 file > > Adding some debugging statements to zipfile.py reveals that the CRC > returned by binascii.crc32() is 2226205591 which is 0x84b13397. So, this > matches the output above from unzip. So, bar.CRC is wrong. > > BTW, the /tmp/a.zip file used in this example was written with the > zipfile module (it is a valid zip file as I unpack with unzip and ran > cmp against /vmunix, the original source). Ok, I did some digging. The attached patch solves the problem. I think this is a problem for any machine where sizeof(long) == 8. Is there an easier way to force crc to be a 32-bit int. From the typesnumeric.html document: Plain integers (also just called integers) are implemented using long in C, which gives them at least 32 bits of precision. -- albert chin (china at thewrittenword.com) -- snip snip --- Lib/zipfile.py.orig Mon Jul 1 23:10:00 2002 +++ Lib/zipfile.py Mon Jul 1 23:10:26 2002 @@ -346,7 +346,7 @@ raise BadZipfile, \ "Unsupported compression method %d for file %s" % \ (zinfo.compress_type, name) - crc = binascii.crc32(bytes) + crc = struct.unpack(' Message-ID: <9aZX8.47377$n4.11526798@newsc.telia.net> Jane Austine wrote: > Newly added function sre.finditer and (matchedObject.)finditer > break down and the system crushes on win32 when requested for > next() after StopIteration. > > see: > >> import sre > >> fi=sre.finditer(r'\s','a b') > >> fi.next() > >> fi.next() > >> fi.next() #system halts for ever. well, I'm tempted to just say "don't do that" (if python tells you to stop iterating, stop iterating ;-), but it sure looks like a bug. bugs are best reported on sourceforge; see http://www.python.org/dev/ for details and links. From jknapka at earthlink.net Mon Jul 8 20:03:53 2002 From: jknapka at earthlink.net (Joseph A Knapka) Date: Tue, 09 Jul 2002 00:03:53 GMT Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <3D2A27DA.16E95379@earthlink.net> curt finch wrote: > > Our free web timesheet app is written totally in Python. > One of our competitors is saying the following > things about python to our customers. Help me make them look stupid. > Please? > > ps. enjoy our free stuff at http://pnk.com/wt3.html > > thanx for any comments you can provide OK, after spending twenty minutes responding to this post, I'm starting to strongly suspect that you are a troll. But what the hell. > > > Summary > Python is often used as pseudocode to conduct rapid development. And it's often used to produce production code. See the recent c.l.python thread "Using Python for processing of large datasets (convincing managment)" for several citations. > Its > major users are web sites that do not reuse code and often conduct > “throw away” I'd demand numbers from these damned liars. How, exactly, do they know this? Of course, they won't be able to produce any evidence. > development to meet internet development time > tables. It is a very new language and has very little support compared > to the Java development community. Python is, what, ten years old now? I've personally got better support from the Python community than from the Java community, but that's just hearsay and doesn't help you much. (My theory is that using a nice language tends to make people nicer!) > It is also not J2EE compliant. Hmm. Jython would probably be a fine way to implement the innards of EJBs, but I haven't tried it. I suspect a EJB server based on Jython could be built without much trouble. In any case, I don't see this as a major drawback - C isn't "J2EE compliant" either, but that doesn't stop people from using it in high-quality software. > Platform Drawbacks > As a new relatively untested development platform in the licensed > software community, Python has certain deficiencies with which all > users and developers should be aware. > > > > > Issues and concerns > > ? No integrated GUI (Graphic user interface) support. I'm not sure what that means. Do they mean, "no way to write a UI"? Tk is a mature toolkit if ever there was one, and Tkinter is just a wrapper around Tk. I've never had any stability trouble with Tkinter. Do they mean "There aren't any magical dragon-droppings UI builders"? There are, but I have no experience with them. In any case, this can hardly be construed as a major disadvantage. I've never encountered a UI builder that could write better code than I could, and it's a virtual certainty that a human is going to have to maintain that code eventually. > ? No compiler to the native code. True. But you can run Python code on a JIT Java VM, using Jython. > ? No automatic garbage collection. A damned lie, as casual perusal of the Python documentation would reveal. Your major weapon against this competitor might be simply that they lie to their customers! > ? Does not have vast number of libraries as that of Java, > Perl, C++; etc. And another damned lie. > ? Since Python is an interpreted language, it requires > frequent run-time checks and thus does not provide the speed, > performance and efficiency of compiled languages like Java, Perl and > C++, which is a major issue. This is true, though for many applications it's a non-issue, and for apps where speed is critical one can always write selected pieces of the app in a lower-level language. > ? Python does not provide multiple ways to perform tasks as do > most other languages. This is just stupid. These people clearly have an axe to grind. Like all the other languages they blather on about, Python is Turing-complete, so logically there are an infinite number of ways one could accomplish a given task in any of them. The fact that Python doesn't give you a bewildering assortment of syntactic forms for expressing the same semantics is an *advantage* - it makes the code easier to read and maintain. > ? It takes a lot of time for Python to adjust to the > indentation style of the structuring code. Actually, it takes *Python* no time at all to adjust to the indentation style - the interpreter requires it. It takes humans about five minutes to adjust to it. See Eric S Raymond's "Why Python?" for a compelling personal account of the ease with which humans adjust to Python's coding style. http://www.linuxjournal.com/article.php?sid=3882 > ? Since Python is relatively a new language, there are only a > few resources available for information on its latest developments. What utter bullshit. I'm sorry, but these people should get out more. www.python.org is a splendid counter to this "argument". > ? Limited documentation- only two English language books exist > which provide tutorials or a library reference for Python. And they are *good* books - not like the stinking mounds of literary shit people have produced about Java and C++. (I'm actually getting angry here!) > ? The language is restricted to fewer code modules. What does that even *mean*? Who is your competitor, may I ask? I want to make sure me and mine never actually use any of their products, as they are either idiots or marketroids. > ? Lacks native threading capabilities. Sort of true. I see this as a major drawback of CPython, but Jython doesn't suffer from the same threading limitations, or so I'm told. And on uniprocessor hardware, CPython's threading works just dandy. > ? Lacks basic tools such as integrated source level debuggers. That's not entirely true. There's IDLE and Pythonwin, neither of which are particularly stunning IMO. But one rarely actually needs to interactively debug Python code, in my experience. > ? No packaging methods for software distribution. distutils > ? Lacks tools to solve typographical and type mismatch classes > of errors. Huh? I think the IQ of the person who wrote this was actually dropping as he worked on the document. They seem to be saying, "Python is not a statically-typed language". Damn straight, and we like it like that. At least it doesn't have a completely braindead typesystem like Java's. > ? Python cannot write docstrings in C++. Who the f!%k cares???? I prefer my docstrings to be in English. > ? Python is difficult to read. That line was obviously written by a person who has never *tried* to read someone else's Python code. IMO *no* language (of the twenty or so that I know well) is as readable as Python. (This is also the line that triggered my troll detector.) > ? Dynamic loading is not available on all systems, requiring > that a developer use static loading. This is a criticism of operating systems, not of Python. Whew. I need to lay down for awhile. -- Joe > > > > > > Application Areas > ? Prototyping and development > > ? Platform independent graphic user interface applications > > ? Internet scripting/applications > > ? Automated test harnesses > > ? System administration applications > > ? Shell scripting/OS Scripting > > ? Text processing > > ? Database Interfaces > > ? Application Extensions > > ? Distributed Programming > > > > Python users > ? Yahoo > > ? Infoseek From whisper at oz.net Wed Jul 10 14:00:48 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 11:00:48 -0700 Subject: Win32 Registry Manipulation w/PythonWin? In-Reply-To: Message-ID: OOps, I saw this after I posted my pointer to _winreg... I was confused in part by the mention of PythonWin - that's not needed to do registry stuff with the standard winreg module. What exactly are you trying to accomplish with the registry? Manipulating the registry isn't all that hard, but if you do scramble it, it's a Very Bad thing. One thing you should do before testing registry manipulation code is to make an emergency repair disk - this (IIRC) will also offer the option of making a backup of the registry. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Tim Daneliuk > Sent: Wednesday, July 10, 2002 10:30 > To: python-list at python.org > Subject: Re: Win32 Registry Manipulation w/PythonWin? > > > Matthias Huening wrote: > > Tim Daneliuk wrote in > > news:qmqgga.g31.ln at eskimo.tundraware.com: > > > > > >>Does some kind soul out there happen to have a pointer to a > >>tutorial/examples on fiddling with the Win32 registry from PythonWin? > >> > > > > > > There is a module called pyRegistry. Can't find the url right now, but > > you can get it from ActivState: > > http://aspn.activestate.com/ASPN/Modules/Python/dist_html?dist_id=11218 > > > > Matthias > > Is there some advantage to this module over the standard _winreg module? > > -- > ------------------------------------------------------------------ > ------------ > Tim Daneliuk > tundra at tundraware.com > > -- > http://mail.python.org/mailman/listinfo/python-list From vinay_sajip at yahoo.co.uk Sun Jul 7 20:38:44 2002 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 7 Jul 2002 17:38:44 -0700 Subject: ANN: Logging Module v0.4.6 released Message-ID: <2e37dc1.0207071638.11381436@posting.google.com> A new version of the proposed Python standard logging module (as per PEP 282) has been released. What Does It Do? ================ The logging module offers the ability for any Python program to log events which occur during program execution. It's typically used to provide application diagnostics, warnings and error messages. In addition to capturing "what happened", "where it happened", "when it happened", "how important it is" and event specific data, you can configure, without changing the application source code, both the verbosity of logging and the routing of events to different destinations such as console, disk files, sockets, email addresses, Web servers, SOAP servers etc. etc. You can even change the configuration of a running program without stopping and restarting it! You can use the logging module in exception handlers, and it will include traceback information in the log. It's thread-safe, and very easy to use - just "import logging" and log away! Classes provided include: Logger - used to log messages for a particular area of an application. You can instantiate these wherever you want, there's no need to pass references to them around your application. You can log events based on importance levels of DEBUG (least important), INFO, WARN, ERROR, and CRITICAL (most important). You can define your own levels if the default levels don't meet your requirements. Handler - used to route events to particular destinations. Handlers included are: StreamHandler (for generalized streams, including console) FileHandler (for disk files - including log file rotation with size limits for log files) SocketHandler (for sending events to a TCP socket) DatagramHandler (for sending events to a UDP socket - faster, but less reliable than TCP) SMTPHandler (send events to arbitrary email addresses) HTTPHandler (send events to Web servers) SysLogHandler (send events to Unix syslog) MemoryHandler (batch up events and process them several at a time) NTEventLogHandler (send events to Windows NT event logs) There are also examples of XMLHandler and SOAPHandler in the distribution. Formatter - used to format events as text strings. Flexible "msg % arg_tuple" formatting is the basis for formatting, with flexible date/time formatting including ISO8601 and any strftime-based formats. Filter - used when filtering based on importance (DEBUG/INFO/WARN/ERROR/CRITICAL) is not sufficient. The distribution includes examples of filters based on class matching, regular expression matching, value matching, and logger matching. In the unlikely event that you're daunted by all the apparent complexity, fear not. The module offers a simple function-based interface to allow very simple, almost casual use of the underlying features. In addition to the core logging functionality, you get the ability to configure logging using a ConfigParser-based text file format, a Tkinter-based GUI configurator which creates configuration files for you, and a simple network-based event receiver which receives events on TCP, UDP, HTTP and SOAP ports. This is suitable for testing and might perhaps serve as a model for your own event receivers. Also included are over 20 test scripts which serve both as test harnesses and examples of how to use the logging module. You can get more information from http://www.red-dove.com/python_logging.html There are "download" and "recent changes" links at the top of that page. The new stuff includes some bug fixes, better support for class-based filtering and logging, more documentation of the configuration file format, an example hand-coded configuration file for those people who can't use the GUI configurator, an example Filter for regular-expression match-based filtering, and more! As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. Changes since the last version: ================================= Added raiseExceptions to allow conditional propagation of exceptions which occur during handling. Added converter to Formatter to allow use of any function to convert time from seconds to a tuple. It still defaults to time.localtime but now you can also use time.gmtime. Added log_test22.py to test the conversion feature. Changed rootlogger default level to WARN - was DEBUG. Updated some docstrings. Moved import of threading to where thread is imported. If either is unavailable, threading support is off. Updated minor defects in python_logging.html. Check to see if ConfigParser has readfp method; if it does and an object with a 'read' method is passed in, assumes a file-like object and uses readfp to read it in. From cja at dqs.nwt Mon Jul 29 17:12:32 2002 From: cja at dqs.nwt (CJ) Date: Mon, 29 Jul 2002 14:12:32 -0700 Subject: wxPython printing help Message-ID: I am having a very hard time trying to sift thru the wxWindows docs on printing. I have screated a pdf file via reportlab now I would just like to be able to print it. I would like to be able to print without any other input from the user (ie. selecting the file) The file name would be hard coded into the script I am using wxPrintDialogData() to bring up a box but I can't figure out how to enter the filename to print CJ From wdraxinger at darkstargames.de Wed Jul 10 08:43:23 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Wed, 10 Jul 2002 14:43:23 +0200 Subject: Embedding Python the extreme way References: <3D2C2103.3020706@darkstargames.de> Message-ID: <3D2C2BEB.2040803@darkstargames.de> Michael Hudson wrote: > To me these sentences contradict each other. So I must be missing > something... I want not to add a statically linkes python.lib to my linkage > For the modules, just don't build them. You really don't want to try > getting rid of sys, btw. Yes I want that! I just want the language and the grammar and basic data types. E.g. I've a virtual file system in my engine. All that's related to files should go through this natively. Ok, discarding sys may be not a good idea, but things like sys.exit, sys.path, sys.dllhandle and similair should definitely not be touched by engine object scripts. > For getting rid of builtin functions, why bother? Because some of them can mess up all. I know what I'm talking about. I should have said, getting rid of all where it is possible and replacing the rest with custom stuff at a low level base. >>Can anybody give me some advice for that. > Yes: don't. Why? > PS: I saw that you x-posted this to python-dev. Please don't do that. OK -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From jdhunter at nitace.bsd.uchicago.edu Mon Jul 22 11:43:27 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Mon, 22 Jul 2002 10:43:27 -0500 Subject: how to delete or change... References: Message-ID: >>>>> "Shagshag13" == Shagshag13 writes: >> There are some unknown's here that would be helpful to know. >> You say it's a text file but then talk about opening in binary. >> Is it ASCII? Shagshag13> yes, it's an ascii file (i try to open it in binary to Shagshag13> do bytes operations instead of lines operations) >> How large all the files? Is it feasible for you to work in >> memory? Shagshag13> No, i can't (huge file between 1,5 and 2,5 go) >> Also, you say when you tried the binary seek you got an I/O >> error. Was there anything informative about that error that >> you can post? >>>> f2 = file('d:/test.txt', 'rwb') f2.seek(-5, 2) f2.read(5) Shagshag13> 'TUR\n' >>>> f2.seek(-5, 2) f2.write('new') Shagshag13> Traceback (most recent call last): File Shagshag13> "", line 1, in ? f2.write('new') IOError: Shagshag13> (0, 'Error') Shagshag13> Maybe i miss something ? Yes, this can be confusing `open(filename[, mode[, bufsize]])' Return a new file object (described earlier under Built-in Types). The first two arguments are the same as for `stdio''s `fopen()': FILENAME is the file name to be opened, MODE indicates how the file is to be opened: `'r'' for reading, `'w'' for writing (truncating an existing file), and `'a'' opens it for appending (which on _some_ UNIX systems means that _all_ writes append to the end of the file, regardless of the current seek position). Modes `'r+'', `'w+'' and `'a+'' open the file for updating (note that `'w+'' truncates the file). Append `'b'' to the mode to open the file in binary mode, on systems that differentiate between binary and text files (else it is ignored). If the file cannot be opened, `IOError' is raised. Note that 'w' truncates the file (which you clearly don't want) and 'a' appends to the end regardless of seek position. What you want is 'r+b'. I think the doc string could be a little clearer here .... fname = 'somefile.dat' f2 = open(fname, 'r+b') f2.seek(-5,2) f2.write('John') Hope this helps, John Hunter From marklists at mceahern.com Thu Jul 25 10:21:05 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 25 Jul 2002 09:21:05 -0500 Subject: Completion in emacs mode In-Reply-To: Message-ID: > I'm looking for the ability to do command completion in Emacs' python > mode. I haven't managed to get Google to show me anything really > pertinent to this quest. http://www.geocrawler.com/archives/3/338/1993/12/0/1878323/ // m - From abelo at earthlink.net Tue Jul 16 18:25:26 2002 From: abelo at earthlink.net (Carl) Date: 16 Jul 2002 15:25:26 -0700 Subject: Module Problem Message-ID: <1d95285a.0207161425.2be84123@posting.google.com> - I downloaded the Python22 software along the the Python Manuals. - I got the part where you are supposed to save the fibo.py module. - I saved the module to C:\Python22 using the notepad in windows 98. the file in that directory was saved as fibopy~1 the full file name reads as fibo.py.txt - The python shell does not recognize this as a module when I try to import it. - Please help me get around this problem. Thanks. From phr-n2002b at NOSPAMnightsong.com Fri Jul 26 20:09:41 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Jul 2002 17:09:41 -0700 Subject: performance problem in python 2.2 References: Message-ID: <7xd6tayqt6.fsf@ruckus.brouhaha.com> Jeff Davis writes: > 'p' was an unsigned long long int. I slightly modified the algorithm in C > because it doesn't have (native) support for > 64-bit ints. Since the > number of possibilities is 2**64 that value will be slightly bigger than a > 64 bit int could hold. So, I just basically multiplied twice by 2^32 and > divided twice by 2^32. In other words, I basically treated 'p' as > sqrt(p)*sqrt(p) and commuted the multiplication so that I would arrive at > the same result (and the testing seemed to show the same results as my > other algorithm). I have attached my c code below in case you'd like to > know exactly what's going on. It's amazing that you ended up with an accurate answer doing that. You should do this kind of thing completely in floating point: double p; p = pow(2.0, 64.0); /* 2**64 */ etc. > #!/usr/bin/python2.2 > > import sys > > n = 1.0 > p = 2L**64 > c = long(sys.argv[1],10) Try "p = 2.**64" instead of "2L**64" and see if you get a speedup. Also, make c int instead of long unless you want c > 2**31. From shalehperry at attbi.com Sun Jul 7 00:26:00 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 06 Jul 2002 21:26:00 -0700 (PDT) Subject: structs in python In-Reply-To: <20020706231200.A25295@arizona.localdomain> Message-ID: On 07-Jul-2002 Kevin O'Connor wrote: > Hello, > > I often find myself using Python tuples in the same way I might use C > structs. For example, I might store a "point" as "p = (x, y, color)". > > Unfortunately, this quickly becomes cumbersome when the code starts to make > frequent references to tuple positions instead of member names. For > example, one would see code like "delta = (p1[0] - p2[0], p1[1] - p2[1])". > Ideally, this code would read something more like "delta = (p1.x - p2.x, > p1.y - p2.y)". > > Clearly, the use of classes makes the code much more readable, but > unfortunately the declarations necessary to instantiate a class is often > too much of a hassle for small and infrequently used objects. > > It would be useful if there were a simple way of declaring a class with > only member variables (and no methods); an object more akin to a C struct. > >>> class Point: ... pass ... >>> p = Point() >>> p.x = 1 >>> p.y = 2 >>> p.color = "blue" >>> p2 = Point() >>> p2.x = 3 >>> p2.y = 5 >>> p2.color = "green" However this breaks down for your delta = ... example. is class Point: def __init__(x, y, color): self.x = x self.y = y self.color = color really that much to type? delta = Point(p2.x - p.x, p2.y - p.y, default_color) From yduppen at xs4all.nl Wed Jul 10 02:29:57 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Wed, 10 Jul 2002 08:29:57 +0200 Subject: Lunar lander example References: Message-ID: <3d2bd853$0$12303$e4fe514c@dreader4.news.xs4all.nl> > I was wondering if there was a place for example programs for new > Pythoneers to look at? Uselsss Python is a great repository for such scripts. http://www.uselesspython.com/ YDD -- .sigmentation fault From lists at lophty.com Wed Jul 31 14:20:21 2002 From: lists at lophty.com (Brian Donovan) Date: Wed, 31 Jul 2002 18:20:21 GMT Subject: parse_qs ... why dictionarykey : list ? Message-ID: I've been working on a small project using, among other modules, Python's cgi mod and have a couple of questions. I've read the docs, Google'd, and searched the comp.lang.python archives for an answer, but have come up empty so far. (1.) Why does cgi's parse_qs return each of the param:value pairs in a querystring as a dictionary key and a list? (2.) How does one format a query string so that lists can actually be passed to a Python script via querystring so that parse_qs will "see" them? [I've futzed around a bit but haven't stumbled on how it's done.] I apologize if this is a dumb question. :D Thanks in advance, -brian From mhammond at skippinet.com.au Sun Jul 28 18:57:25 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 28 Jul 2002 22:57:25 GMT Subject: Disappearing Output? References: Message-ID: <3D4476FB.70200@skippinet.com.au> George Hester wrote: > I have a very simple Python script in a ASP page. The ASP looks like this: ... > But if I try to run an ASP as shown above I get output sometimes but often I get > absolutely nothing. No output. No errror. Just absolutely nothing. > > Is this a Python issue, a Python Script issue or something else under the sun? This is a Python bug. It has been fixed in the latest versions of win32all - see my starship page. Mark. From maxx at easynews.com Fri Jul 26 14:27:26 2002 From: maxx at easynews.com (Max) Date: Fri, 26 Jul 2002 18:27:26 GMT Subject: Python in the enterprise: Pros and cons References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: What is the other one? On Wed, 10 Jul 2002 15:53:33 -0700, "David LeBlanc" wrote: >There two commercial tools for wysiwyg tkinter development, one of which >is PythonWorks from Pythonware. From nulldevice at hotmail.com Tue Jul 16 11:09:41 2002 From: nulldevice at hotmail.com (alex) Date: Tue, 16 Jul 2002 17:09:41 +0200 Subject: Com module on linux? Message-ID: Hi, I desperatly need a com module on linux to interface with Rose. Rose is using MainWin from MainSoft to implement com on unix. Is there a module that allows to access Rose via the com interface on linux? Did not find anything on the web :-(. Many thanks in advance, alex From howard at eegsoftware.com Thu Jul 25 17:34:09 2002 From: howard at eegsoftware.com (Howard Lightstone) Date: Thu, 25 Jul 2002 21:34:09 GMT Subject: embedding problem with dictionary References: Message-ID: Following up on myself after "Finding the Problems" (two of them): > pnd=PyDict_GetItemString(idict,basename); // borrowed reference > if (!pnd) > { > // must "create" such a subdictionary > pnd=PyDict_New(); // new reference > // add reference into main dict > PyDict_SetItemString(idict,basename,pnd); > // always leave with valid pnd > } The problem here is that the dictionary-within-a-dictionary was sometimes None. I was only checking for NULL output from PyDict_GetItemString. The new test became if (!pnd || pnd == Py_None) This works because None is a singleton (it actually IS documented, just not obvious the first time). And I forgot about None as a possibility. The second problem was reference counting. The code below worked sometimes but not others. > static PyObject * idict; > > static PyObject * > pyaccess_Run(PyObject *self, PyObject *args) > { > > if (idict) <==REMOVED > Py_DECREF(idict) <==REMOVED > if (!PyArg_ParseTuple(args, "O",&idict)) > return NULL; Of course, carefull reading of the docs again and again pointed me to the fact that the outputs of PyArg_ParseTuple are BORROWED references. I deleted the spurious DECREF above it and things began working reliably. I assume that when it didn't work, the object had been destroyed somehow when I erroneously DECREF'ed it. Even though I have read the embedding docs many times, it seems I don't "see" the key phrases when I need them. I need a little hammer that smacks me on the head at those subtle points. From coventry at removethisandallhyphens-o-n-e.net Thu Jul 11 19:16:05 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Thu, 11 Jul 2002 19:16:05 -0400 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> Message-ID: <3D2E11B5.4070502@removethisandallhyphens-o-n-e.net> No, you are only using a convention to let other developers know that these variables are private - the python interpreter does not even attempt to hide a '__' variable from other classes or code. Private members are by convention only in python, they are not enforced, thus you do not realistically get a similar result. >>Only 2 'extra' chars are needed -- a letter and '.'. Why the extra >>'__'? >> > > Thy're "private" instance variables. Whereas other languages > provide a declaration for such a propterty, you get a similar > result in Python by mangling the name... > > From spam at ob_scure.dk Sun Jul 7 11:57:18 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 17:57:18 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> <3D282FF8.6040602@ob_scure.dk> <7x3cuvsnc7.fsf@ruckus.brouhaha.com> Message-ID: <3D2864DE.6030608@ob_scure.dk> Paul Rubin wrote: > Thomas Jensen writes: >>The current job takes about 5 hours to complete! > > Is 5 hours acceptable, if your data doesn't get any bigger? > It not, what's the maximum you can accept? 5 hours is about the maximum acceptable. Usually the time is a little shorter, but 5 hours happen when much new data is added. However, this is a case of "faster is better". 5 hours is acceptable but 1 minute would open up new business oppertunities. > OK, you're certain you can do it in 30 minutes. Are you certain > you CAN'T do it in 5 minutes? If you can do it in 5 minutes, maybe > you can stop worrying about scaling. It would perhaps be possible to reach 5 minutes. However I am quite certain that the effort and development time of going from 10 minutes to 5 minutes would be far greater than writing a simple RPC client/server architecture. Since we have 8 (or is it 6, I don't remember) CPU's that are mostly idle at nighttime, why not utilize them ? > In another post you said you wanted to handle 10 times as much data > as you currently handle. Now you say it's not known exactly--do you > have an idea or not? AFAIR I said at least 10 times (thats what I meant anyways). Faster calculations => able to handle more data => new business oppertunities. I it was a big problem making the program distributed, I probably wouldn't consider it. > If it's acceptable for the program to need 3 hours, and you can handle > the current data size in 10 minutes, then you can handle 10x the data > size with plenty of speed to spare (assuming no > seriously-worse-than-linear-time processes). Most sub-calculations currently scales almost linearly, asuming indices are set up correctly. > I think the bottleneck is going to be the database. You might not get > better throughput with multiple client CPU's than with just one. If > you do, maybe your client application needs more optimization. We already have 2 DB Servers, a master replicating changes to a slave. Our analysis shows that most database operations are/will be SELECTs. Adding more DB servers is trivial, especially if we migrate to MySQL (well, cheaper at least :-) > What is the application? What is the data and what do you REALLY need > to do with it? How much is there ever REALLY likely to be? Is an SQL > database even really the best way to store and access it? If there's > not multiple processes updating it, maybe you don't need its overhead. We have several applications accessing the DB via SQL. Migrating to something else is out of the question in the near future. > Could a 1960's mainframe programmer deal with your problem, and if > s/he could deal with it at all, why do you need multiple CPU's when > each one is 1000 times faster than the 1960's computer? I've never used/programmed a mainframe, so I don't know :-) > Inside most complicated programs there's a simple program struggling > to get out. I agree, I really do. I usually rewrite most of my programs 1 or more times to make them less complicated. Before going on with the distributed approach, I will probably write a "proof of concept" demo. Should this demo show, that it is not worth the effort, I will put it aside for now. The reason I mentioned XMLRPC earlier is that I've used it before and in my oppinion it is extremly easy and intuitive to use. The model I'm currently working with is caracterized by having relativly few RPC calls, with each call having only one integer as input and output. Should I require more complex data structures, I'd probably look for a binary protocol. But all that apart - the distributed part is not really the hard or complex part about this project. I understand that as soon as the calculations take place in more than one thread (be it on one or more CPUs/machines) it adds some complexity. However, designing the application in such a way that parralell computations are possible/plausible, can't be that bad I think. I really see all this distribution talk as one among several optimization strategies. An extreme example of another strategy: Develop the entire thing in assembler, using flat files or entirely bypassing the file-system. I done correctly, it would probably outperform other strategies by far, but it would also be: * Less maintainable * Less readable * a lot harder to use from ASP/PHP * etc Sometimes you just have to chose. If you like I can come up with some less extreme examples :-) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From fredrik at pythonware.com Mon Jul 15 15:10:44 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Jul 2002 19:10:44 GMT Subject: Write \x1a to binary file References: Message-ID: Martin v. Loewis wrote: > > I've got a problem with writing "\x1A" to a binary file on Win32 platform. > > I think due tue an issue wiht popen() this terminates the output stream. Is > > there any solution for this ? > > I think there is some win32 module that allows you to set the default > open mode for files to "binary". msvcrt.setmode(filehandle, mode) see http://www.python.org/doc/current/lib/msvcrt-files.html for a bit more information. From mis6 at pitt.edu Mon Jul 29 14:14:01 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 29 Jul 2002 11:14:01 -0700 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> <3D432D3D.9E265A18@alcyone.com> <3d438609$1@duster.adelaide.on.net> <3d439616$1@duster.adelaide.on.net> <2259b0e2.0207280652.202f1721@posting.google.com> Message-ID: <2259b0e2.0207291014.478c210@posting.google.com> It seems Guido took his time machine to answer my question four days ago at OSCON. From http://www.python.org/doc/essays/ppt/ , Python Regrets: "print should've been a function" Michele From rchii at lycos.com Wed Jul 3 19:45:56 2002 From: rchii at lycos.com (Ron Horn) Date: Wed, 3 Jul 2002 16:45:56 -0700 Subject: File Locking (or any similar file mutex) in Windows OS??? Message-ID: <3d238ca3$0$333$e2e8da3@nntp.cts.com> OK, I'm kinda new to Python, but I want to setup a simple app that will allow multiple client machines to examine an modify a SHARED file on some server. I want to avoid two clients writing to the file at the same time, so some sort of (simple!) mutex on the file (or file locking, etc.) is needed. All the machines are running Windows of some sort (usually Windows 2000, but whatever). I was considering using the "shelve" module to read/write the shared file. I've tried several things to determine on one client if another client has the shelve file open, but to no avail, and the clients will merrily overwrite each others data. As a test, I've also tried just using os.open() with various flags (e.g. O_EXCL), also to no avail. The clients ignore the fact that the file is already open by another client. I would like some simple and robust way to know if one of the clients is currently using the file, but my question could apply to any shared resource the various client instances could want to share. It seems that the various file locking features of os.open(), and anydbm.open(), etc. are not working right on Windows? Any suggestions on how to make this work in python running on windows clients/server would be appreciated. ron From shagshag13 at yahoo.fr Thu Jul 25 10:34:20 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 25 Jul 2002 16:34:20 +0200 Subject: how to get a return value from an exception ? References: Message-ID: "Eric Brunel" a ?crit dans le message de news: ahp184$c9v$1 at wanadoo.fr... > Shagshag13 wrote: > > hello, > > > > i need to raise an exception which "carry" some data... i think that it's > > something like : > > > > class MyException(Exception): > > > > def __init__(self, *args): > > Exception.__init__(self, args) > > > >>>> raise MyException('one', 2, 'three') > > Traceback (most recent call last): > > File "", line 1, in ? > > raise MyException('one', 2, 'three') > > MyException: ('one', 2, 'three') > > > > but them how to access to 'one', 2, and 'three' ? > > Just do the following: > > class MyException(Exception): > def __init__(self, arg1, arg2): > Exception.__init__(self) > self.arg1 = arg1 > self.arg2 = arg2 > > try: > raise MyException('one', 2) > except MyException, ex: > print ex.arg1, ex.arg2 thanks ! i was missing that "ex" was an instance of MyException class ! so : try: raise MyException('one', 2, '3') except MyException, ex: print type(ex) ex[0][0] 'one' i had another questions : * if exceptionB and exceptionC subclass from exceptionA, if i raise exceptionB i could still catch it as it was ExceptionA ? * is it a correct statement ? : try: #do except exceptionB: #do 1 except exceptionC: #do 2 except exceptionA: #do else thanks, s13. From aleax at aleax.it Tue Jul 9 05:29:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 09:29:51 GMT Subject: Multi-threading on Multi-CPU machines References: <3D29FC43.C239BD5F@earthlink.net> Message-ID: Garry Taylor wrote: ... > that this would make no difference? Do you have any tips/ideas how I > could make use of multiple processors in a Python program? Use multiple *processes* rather than multiple *threads* within just one process. Multiple processes running on the same machine can share data very effectively via module mmap (you do need separate process-synchronization mechanisms if the shared data structures need to be written, of course), and you can use other fast same-machine mechanisms such as pipes, in addition of course to general distributed programming approaches that offer further scalability since they also run on multiple machines on the same network as well as within a single machine (pyro, corba, etc etc). Optimal-performance architectures will be different for multiple processes than for a single multi-thread process (and different for really-distributed versus single-machine), but the key issue tends always to be, who shares / sends what data with/to whom. If your problem is highly parallelizable anyway, the architectural distinction between multithread, multiprocess and distributed can boil down to using larger "slices" to farm out to workers to reduce the per-slice communication overhead, sometimes. Say for example that your task is to perform some pointwise computation cpuintensivefunction(x) on each point x of some huge array (assume without loss of generality the array is one-dimensional -0- the pointwise assumption allows that). With a multithreaded approach you might keep the array in memory and have the main thread farm out work requests to worker threads via a bounded queue. You want the queue a bit larger than the number of worker threads, and you can determine the optimal size for a work request (could be one item, or maybe two, or, say, 4) via some benchmarking. Upon receiving a work request from the Queue, a worker thread would: -- get a local copy of the relevant points from the large array, -- enter the C-coded computation function which -- releases the GIL, -- does the computations getting the nes points, -- acquires the GIL again, -- put back the resulting new points to the same area of the large array where the input came from, then go back to peel one more work request from the Queue. If you can't release the GIL during the computation, e.g. because your computation is in Python or anyway requires you to interact with the interpreter, then multithreading will give no speedup and should not be used for that purpose. A similar architecture might work for a single-machine multi process design IF multiple processes can use mmap to read and write different regions of a shared-memory array at the same time, without locking (I don't think mmap ensures that on all platforms, alas). "Get the next work request" would become a bit less simple than just peeling an item off a queue, which makes it likely that a rather larger size of work request might be optimal -- depending on what guarantees you can count on for simultaneous reads and writes from/to pipes or message queues, those might provide the Queue equivalents. Alternatively, wrap the data with a dedicated process which knows how to respond to requests for "next still-unassigned slice of work please" and (no return-acknowledgment needed) "here's the new computed data for the slice at coordinate X". pyro might be a good mechanism for such a task, and it would scale from one multi-CPU running multiple processes to a network (you might want to build-in sanity checking, most particularly for the network case -- if a node goes down, then after a while without a response from it the slices that had been assigned to it should be farmed out to others...). Of course, most parallel-computing cases are far more intricate than simple albeit CPU-intensive computations on a pointwise basis, but I hope this very elementary overview can still help!-) Alex From andreas at kostyrka.priv.at Sun Jul 28 10:45:08 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 28 Jul 2002 16:45:08 +0200 Subject: Guide to the python interp. source? In-Reply-To: References: Message-ID: <1027848147.20536.125.camel@vaio2> Am Sam, 2002-07-27 um 15.19 schrieb Tim Gahnstr?m /Bladerman: > I noticed, but thought that I just had missed it. I thought there must be > some where for such a large project. But the problem is ofcourse ever > present, "nobody likes to do documentation" Well, start with the embedding/extending documantation. > Maybe look into value/copy return as Alex Martelli mentioned. What I want is > not really CBR but the, from Ada known "in out parameters" or the Pascall > "var parameter". var parameters are true call by reference. And it would make no sense in a language design, because call by value semantics have cleaner semantics. f(i) with general reference semantics have unnice property, that I know nothing about i after the call. Now there is nothing in the python syntax that would make specifing which parameters should be reference passed. Additionally, the most important use CBR is passing out multiple return values, which is obviously not needed in python: def func(x,y,z): return (x+1,y+1,z+1) a,b,c=func(d,e,f) > > Probably easy. Not quite sure what you mean here. sys.stdout=open("somefile","w") sys.stdout=cStringIO.StringIO() > Didn't really mean anything briliant there, it was just small things that > poped out of my head while I was writing. > I meant I want all output (text, graphics, buttons, etc) in a certain window > in the IDE I am creating. > > > > better errormesages, > > Examples? Feel free to contribute these back to the project... > > Ofcourse I will contribut them back if I create something there that is > usefull for alot of people. > Maybe the error messages I want to have is not so badly needed for > experienced programmers but more for beginners. > A traceback is for instance really cryptic to a novice programmer I want an > errormessage to look loike this. > > "The program stopped running for some unknown reason. It is likely an error > on line 23 in the file "myprog.cod": > if (max(3)>variable): > The error is probably caused by the call to the function max(). If you mean > to call the built in function max it must have two arguments, namely "val1" > and "val2" but you only supply it with one argument (constant 3). > On the other hand it might also be a misspelled call to your own function > maz() in "mylib.cod" > " But that is exactly not correct: max(1,2) max(1,2,3,4,5,6) max((1,2,)) max([1,2,3,4,]) are all legal. max(someObject) might also be legal, if someObject is a user made list like object. > Currently the errormessage looks like this instead: > > "Traceback (most recent call last): > File "", line 1, in ? > if max(3)>variable: > TypeError: min() or max() arg must be a sequence" Well, this at least correct. (arg must be a sequence.) While your nice message above is misleading. Andreas From bokr at oz.net Mon Jul 15 15:23:17 2002 From: bokr at oz.net (Bengt Richter) Date: 15 Jul 2002 19:23:17 GMT Subject: implementing large trees References: Message-ID: On Mon, 15 Jul 2002 15:22:32 +0200, Michael Schmitt wrote: >Hello. > >I'm trying to implement a large tree data structure, which does not fit >into memory. Based on an in-memory implementation, which has two >dictionarys, one for all nodes and one for all edges, the first idea was to >use shelve to have disc-based dictionaries. > >But for usual tree operations (depth-first traversal, breadth-first >traversal) the shelve based tree was much slower, than the tree using two >dictionaries and relying on swapping. > >What is the "best" way to implement such a tree? Is it possible to improve >performance without knowing how the tree is traversed? What about having a >breadth-first and a depth-first cache, that prefetch nodes and edges after >each access? > >Thanks for any hints. - What about buying more memory ;-) - Are your nodes and edges class instances? Are you using __slots__ ? - What are you using as keys in your dictionaries? - Do you need to touch every node as you follow edges? - How many total nodes and edges? - How many edges per node? Min? Max? Usual? - Is it very deep or very wide? - Is the tree essentially static for many traversals, so that it might pay to do some special overall pre-procesing to speed traversal? - Is part of the tree "hot" and other parts hardly ever visited? Would caching pay off? - What does your tree actually represent IRL? Regards, Bengt Richter From sadams123 at optushome.com.au Tue Jul 30 19:26:17 2002 From: sadams123 at optushome.com.au (Steven) Date: Wed, 31 Jul 2002 09:26:17 +1000 Subject: Cookbook: Associating multiple values with each key in a dictionary References: <20020730171536.A992@bork.demon.nl> <20020730131414.C7503@eecs.tufts.edu> <20020730215002.A2145@bork.demon.nl> Message-ID: <3d47209a$0$11268$afc38c87@news.optusnet.com.au> "Dave Reed" wrote in message news:mailman.1028062367.18700.python-list at python.org... > > From: Egbert Bouwman > > > > On Tue, Jul 30, 2002 at 01:14:14PM -0400, Michael Gilfix wrote: > > > > > > I'm not really sure why you prefer the list method. Is there something > > > that you can't accomplish with the nested dictionaries? > > > > When I need > > { 'boys': ['mike', 'egbert'], 'girls': ['laura','lisa'] } > > it hurts me when I have to build: > > { 'boys': {'mike' : 1, 'egbert' : 1}, 'girls': {'laura' : 1,'lisa' : 1} } > > > > That adds an extra layer of complexity when i construct it, > > I have to remember or document that the values can be thrown away, > > and I have now sets of keys, while I need sets of values. ........... > The following works: > > { 'boys': ('mike', 'egbert'), 'girls': ('laura','lisa') } except that you can't change a tuple (can you?), you'd have to recreate the whole tuple each time you add or delete any values Steven From baf at texas.net Mon Jul 1 19:41:26 2002 From: baf at texas.net (Ben Fairbank) Date: Mon, 01 Jul 2002 23:41:26 GMT Subject: Integrating Python and Statsoft's Statistica. Message-ID: <3d20e7e8.1063108@news.texas.net> I would like to exchange email (probably off-list because of the limited topic appeal) with anyone who has accessed Statistica (a general purpose stat package for Windows) with Python. Ben Fairbank baf at texas.net From davidw at uq.net.au Sat Jul 13 06:00:27 2002 From: davidw at uq.net.au (David Wright) Date: Sat, 13 Jul 2002 20:00:27 +1000 Subject: Guido van Rossum Tutorial - .PDF or other format? References: <3D2F58A7.4080304@linuxmail.org> Message-ID: "Bob X" wrote in message news:3D2F58A7.4080304 at linuxmail.org... > David Wright wrote: > > Greetings > > > > Could someone please advise if this suberb document is available on the Web > > in a printer friendly format, such as .pdf or even .doc. (other than the > > hypetext version on line and on my PC). Yes, I'd like the *address* too ;-) > > > > Many thanks in advance > > David Wright > > ~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Education is not the filling of a vessel, > > but the kindling of a flame." - Socrates > > ~~~~~~~~~~~~~~~~~~~~~~~~~~ > > The PDF version *used* to have problems printing with Acrobat Reader. > Don't know if that is fixed yet. > Hi Bob, Just so you know...I printed the .pdf version. It emerged from the printer in a beautiful font, despite the rather 'awful' fuzzy veneer in the Acrobat Reader interface. Thanks everyone -- David Wright ~~~~~~~~~~~~~~~~~~~~~~~~~~ Education is not the filling of a vessel, but the kindling of a flame." - Socrates ~~~~~~~~~~~~~~~~~~~~~~~~~~ From mertz at gnosis.cx Tue Jul 2 13:43:55 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 02 Jul 2002 13:43:55 -0400 Subject: Simple Conceptual Pickling problems References: <3d217732$0$4276$afc38c87@news.easynet.co.uk> Message-ID: |"chris lyon" wrote in message |> However when I try to load the pickle file After I have imported |> the module from which it was all derived I get:- |> SystemError: Failed to import class Programme from module __main__ "Emile van Sebille" wrote previously: |This is the hint. The module's name when the pickle was created was |__main__, which only happens when the module is not imported, but is run |directly. You need to pickle and unpickle from within the same context, |eg, use import in both cases. OK... cheap plug time. My gnosis.xml.pickle package includes some extra mojo that cPickle/pickle doesn't for manipulating namespaces during unpickling. Chris Lyon's problem may well be better solved as posters have suggested, but if you ever want to deliberately futz with namespaces used (e.g. to restore a data bundle into a functionally different, but compatible, class than the one doing the pickling), gnosis.xml.pickle does this. For example (from the test suite): "Demonstrate on-the-fly and gnosis.xml.* namespaces not saved in XML file" import gnosis.xml.pickle as xml_pickle from UserList import UserList import funcs funcs.set_parser() ud_xml = """ """ class myfoo: pass class Foo: pass print "On-the-fly -- SHOULD *NOT* SEE MODULE NAME IN XML" p = xml_pickle.loads(ud_xml) # print it so we can see the modname print "Fullname = "+str(p) # write it to make sure modname doesn't stick s = xml_pickle.dumps(p) print s print "From (old) xml_pickle namespace -- SHOULD *NOT* SEE MODULE NAME IN XML" xml_pickle.Foo = myfoo p = xml_pickle.loads(ud_xml) # print it so we can see the modname print "Fullname = "+str(p) # write it to make sure modname doesn't stick s = xml_pickle.dumps(p) print s del xml_pickle.Foo xml_pickle.add_class_to_store('Foo',myfoo) print "From class store -- SHOULD *NOT* SEE MODULE NAME IN XML" p = xml_pickle.loads(ud_xml) # print it so we can see the modname print "Fullname = "+str(p) # write it to make sure modname doesn't stick s = xml_pickle.dumps(p) print s xml_pickle.remove_class_from_store('Foo') # now, make sure we haven't broken modnames showing up when they SHOULD :-) print "My namespace (__main__) -- SHOULD SEE MODULE NAME IN XML" xml_pickle.setParanoia(0) p = xml_pickle.loads(ud_xml) # print it so we can see the modname print "Fullname = "+str(p) # write it to make sure modname doesn't stick s = xml_pickle.dumps(p) print s Yours, David... BTW: for info. -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From raims at dot.com Tue Jul 30 03:56:35 2002 From: raims at dot.com (Rhymes) Date: Tue, 30 Jul 2002 09:56:35 +0200 Subject: [ZOPE] Zope, Python, Win2k and Mysql References: <4a4akukkfg92po76t3svc7flen29s3stui@4ax.com> Message-ID: <5jhckucrin6n3csgi9vfru3u66k38dcoa1@4ax.com> On Mon, 29 Jul 2002 18:25:02 +0200, Gerhard H?ring wrote: >Maybe you'll find the installers for the MySQL DA and the mxExtensions >from my homepage useful (see signature). Thanks a lot. MySQL binding works well! -- Rhymes (rhymes at myself.com) http://www26.brinkster.com/rhymes " ride or die " From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 01:04:49 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 21 Jul 2002 22:04:49 -0700 Subject: Callable modules? Message-ID: <7xznwk1hfy.fsf@ruckus.brouhaha.com> I seem to remember seeing something somewhere about making a module callable, but I can't seem to find it in the docs. Basically I want to have a file foo.py, and be able to say (in another file): import foo x = foo(3) instead of having to say foo.mumble(3). Is there a way to do that? I tried putting def __call__(x): ... into foo.py but that didn't work. If there's not a way to do this already, maybe it's a reasonable addition. From pinard at iro.umontreal.ca Thu Jul 18 06:59:23 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 18 Jul 2002 06:59:23 -0400 Subject: pickle performance on larger objects In-Reply-To: <9AEF2842-99D1-11D6-A291-003065B33450@intersight.com> References: <9AEF2842-99D1-11D6-A291-003065B33450@intersight.com> Message-ID: [Sam Penrose] > For my particular use case cPickle is still several (many ?) times slower > than just recreating the object by reading in a file. What implications > this has for best practices in persistence of larger objects I do not > know, but I hope the data point is of interest to others. It also corresponds to what I saw while rewriting `rebox.el' into `rebox.py'. `rebox.py' refills boxed comments in various programming languages, I made it to produce a bigger example for Pymacs, and also to make `rebox' itself more maintainable: I find Python easier to maintain than Lisp. When used in batch to rebox a single comment, `rebox.py' spends almost all of its time in initialisation, and I thought I could make it more speedy by initialising once and saving the result into a pickle, meant to be reloaded in later runs. Pickle loading was not significantly faster than re-initialising afresh, so I dropped it to favour simplicity. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From fredrik at pythonware.com Sun Jul 28 03:58:37 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 28 Jul 2002 07:58:37 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: Bryan Olson wrote: > The mistake was limiting lambda to expressions. Guido can channel himself (or Tim will do it), but from what I can tell, he's always said that the "mistake" was adding something to the language that almost, but not completely, works like lambdas do in other languages. (lambda, map, filter, etc was contributed code) the really big usage problem (whether you knew lambdas from other languages or not) used to be that they were a real pain to use under the LGB scoping rule. with the intro- duction of nested scopes, that problem no longer exists. to fix the other "mistake", some needs to come up with a really great syntax (and get michael hudson to implement it for them ;-). ideas are welcome. From roy at panix.com Tue Jul 9 15:34:26 2002 From: roy at panix.com (Roy Smith) Date: 9 Jul 2002 15:34:26 -0400 Subject: Why self? References: <080720021645110243%pecora@anvil.nrl.navy.mil> Message-ID: Ben Altman wrote: > Not if it is understood to be the convention especially if it clearly > documented. Then when you see '_' you strat thinking 'self' all the time. The nice thing about standards is that there's so many to pick from. From erict at millfilm.co.uk Thu Jul 18 09:43:13 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Thu, 18 Jul 2002 14:43:13 +0100 Subject: raw_input Message-ID: <3D36C5F1.9C966A8F@millfilm.co.uk> It's there anything better than raw_input to query a string input from the user in a console window. Thanks, Eric From mark at mceahern.com Fri Jul 12 16:25:40 2002 From: mark at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 15:25:40 -0500 Subject: switch recipe? In-Reply-To: Message-ID: > the template variable ...... Good point, that certainly could have been explained better. For what it's worth, in the original post in the other thread, I provided a list of the features that were used so that anyone who wanted to investigate could do a little searching to learn more. I could have spent more time compiling that list. Thanks for the feedback. > I always seem to have a semi violent reaction when I see locals(). Hmm, this may sound naive, but I don't understand why. Consider these admittedly cobbled examples: def colorize1(value, color): template = "<%(color)s>%(value)s" return template % locals() def colorize2(value, color): template = "<%(color)s>%(value)s" return template % {'color': color, 'value': value} def colorize3(value, color): template = "<%s>%s" return template % (color, value, color) That's the precise order in which I'd rank them. What could possibly be wrong with the use of locals() in colorize1()? Cheers, // mark - From jblazi at hotmail.com Tue Jul 16 12:20:23 2002 From: jblazi at hotmail.com (JB) Date: Tue, 16 Jul 2002 18:20:23 +0200 Subject: Making code faster Message-ID: <3d3445f9_7@news.newsgroups.com> How can I make the following code faster? I open a (text) file and read the lines in the file. The lines of the file have the form [,] After the lines have been loaded, I set up a new list via the function tmp1. i = -1 print 'loading file' def tmp1(s): global i i += 1 return QSimpleViewItem(i,self.sv.lv.newColor,eval(s)) try: myfile = open(filename) except: pass else: tmp = myfile.readlines() print 'lines loaded' datei.close() self.sv.lv.rows = map(tmp1,tmp) self.sv.lv.visible = range(len(self.sv.lv.rows)) print 'lines decoded',self.sv.lv.rows[0].col[0] Any ideas? It is astonishing that loading the lines from external storage takes much less time than the mapping itself! -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From whisper at oz.net Fri Jul 26 14:42:57 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Jul 2002 11:42:57 -0700 Subject: Two RE proposals Message-ID: 1. Add a substitution operator - in the example below it's "!<..>" word = r"\w*" punct = r"[,.;?]" wordpunct = re.compile(r"!!") The re compiler sees r"\w*[,.;?]" Trivial example, but for fancier patterns it would be great IMO. A substitution pass should be done over the substituted text for nesting: if = r"if" term = r"something" num = r"\d*" op = r"[-+*/]" factor = r"!\s*!\s*!" expr = r"!|!" if_stmt = re.compile(r"!\s*\(?\s*!\s*\)?\s*:" (this is just a muddle to give the idea) 2. Make r"(a|b)*" mean any number of a's or b's. This doesn't work, at least in some situations with the current re compiler - the "any" op "*" doesn't seem to span over a parened group. Note that the corresponding group in groups would have to be a list of strings. David LeBlanc Seattle, WA USA From roy at panix.com Mon Jul 1 21:41:59 2002 From: roy at panix.com (Roy Smith) Date: Mon, 01 Jul 2002 21:41:59 -0400 Subject: Teaching programming -- circular data structures Message-ID: This is more about how people learn to program than about python, but it happened in python, and I know folks here are interested in teaching programming... There's a guy at work who is mostly a self-taught perl and TCL programmer. A while ago, I showed him python, and he's very into it now. We've done a few projects together, of increasing complexity and sophistication. Today, we were working on implementing a particularly gnarly algorithm. We had made some headway with coding it up on the fly, and eventually ended up abandoning the code because our data structures were a total mess. So, we sat down at the whiteboard and started to design a set of classes, with the intent of starting to code again from scratch once we had a better idea of how the data was to be organized. This is, of course, how we should have started the first time, but you know how that goes :-) At one point, I sketched out two classes, called rule and indicator. A rule contained (among other things) a list of indicators, and each indicator contained a reference back to the containing rule. At this point, things came to a grinding halt when my coworker observed that I had just created a circular data structure. He was aghast that you could (although we had no intention to) write things like rule.indicator.rule.indicator.rule, and insisted that we had to find some other way to design the data structures so this couldn't happen. No amount of explaining on my part could convince him that such a thing wasn't evil, or horribly confusing. Although he could not articulate exactly what bothered him so much, I think he was vaguely scared of some sort of infinite loop in the code. Is this a common thing? I, as an experienced programmer, found the circular references perfectly reasonable, but it seemed to blow his mind. Have people teaching programming (or, more precisely, data structures) see this before; that people have problems understanding circular data structures the first time they're exposed to the concept? From aleax at aleax.it Thu Jul 11 02:53:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 06:53:10 GMT Subject: How to replace multiple-line text References: <3D2D0782.45FCEC98@bellatlantic.net> Message-ID: David Lees wrote: > I would like to process a code file and substitute one multiline block > of code for another. I know how to do this in Python by brute force > scanning through on a line by line basis until the first line of the > pattern is found then looping over the rest of the lines in the target > pattern for a match, then substituting in an output string multiline > substitution. But I am sure there is a neater solution, perhaps using > regular expressions. Could someone point me towards sample code or > something similar that I could modify. The simplest approach, a step-by-step example for clarity: old_lines = """Tyger, tyger, burning bright in the forests of the night, what immortal hand or eye dare frame thy fearful symmetry?""" new_lines = """Do not go gentle into that good night, Old age should burn and rave at close of day; Rage, rage against the dying of the light.""" old_file = open("oldfile.txt") old_text = old_file.read() old_file.close() new_text = old_text.replace(old_lines, new_lines) # other changes to new_text, if needed, go here new_file = open("oldfile.txt") new_file.write(new_text) new_file.close() The only possible problem with this approach is that if the files involved are truly huge you might not have space in memory for the text involved (about twice as much as the file's size plus a little). For a "code file" this is quite unlikely -- how many megabytes of code will there be even in a large such file, after all? So, in practice, for the need you've expressed, this approach is almost surely the best one. The theoretical problem in terms of substituting substreams of input streams on the fly is also interesting, but I doubt it's of much actual applicability to your case. Not sure what regular expressions would have to do with the case. I see it as a case of bunching. Matching multiline text, as long as you manage to get it in memory, is just as easy with string operations as with re's if it's an exact match you're lookin for -- re's would be useful if you needed more sophisticated matching, but they still need the file's contents to be in memory. Alex From aleax at aleax.it Mon Jul 22 01:42:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Jul 2002 05:42:24 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: <4XM_8.113673$vm5.3867548@news2.tin.it> Martin v. Loewis wrote: > Paul Rubin writes: > >> Is there a way to do that? > > You can put a callable object in sys.modules. Module objects > themselves are not callable. Right. E.g., the module could be: import sys class Callamod(object): def __call__(self): print "see, I'm callable!" def __getattr__(self, name): if name[:1].lower()=='x': return hex(name[1:]) raise AttributeError, name sys.modules[__name__] = Callamod() This shows off the possibility of having dynamic get-attr functionality, as well as callability, in what every other piece of code accesses as "a module". Only limitation I know of -- no reload() on this kind of "module"... reload(x) needs x to be a module object. Not sure if you could inherit Callamod from the module type to work around this. Alex From shalehperry at attbi.com Wed Jul 10 02:12:08 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 09 Jul 2002 23:12:08 -0700 (PDT) Subject: Lunar lander example In-Reply-To: Message-ID: On 10-Jul-2002 Michael Bauers wrote: > I wrote a simple Lunar Lander program in Python, and I thought it > demonstrated a lot of basic Python features. > > I was wondering if there was a place for example programs for new Pythoneers > to look at? > "useless python" and "python cookbook". Do not have the URL handy but a search should answer it fast enough. From cliechti at gmx.net Sat Jul 27 14:33:17 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jul 2002 20:33:17 +0200 Subject: Beginner problems importing module References: Message-ID: George Torrance wrote in news:mailman.1027778814.26007.python-list at python.org: > I am a beginner and am trying to use the module winioport by Dincer > Aydin. I put the files for this in the main c:\python22 directory. welcome. a good place for user installed packages is "C:\Python22\Lib\site-packages\" this directory is searched when loading modules. > When I try to import winioport I get the following error message >>>> import winioport ... > File "C:\Python22\Lib\site-packages\winio\windll.py", line 20, in ? > import calldll > ImportError: DLL load failed: One of the library files needed to run > this application cannot be found. calldll is a binary extension (a DLL) and it does not find an other DLL it needs. you're sure that you downloaded calldll for the correct python version? (unfortunately, on windows, binary extensions have to be build separately for each python version, usualy there are multiple downloads on the page you get the thing from) > Does this mean that it cant find calldll (which I put in c:\python22), > or that calldll can't find some library file it is looking for? it finds calldll, otherwise the error message would be different. chris -- Chris From martin at v.loewis.de Thu Jul 18 18:44:12 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Jul 2002 00:44:12 +0200 Subject: Calling Fredrik Lundh, (dare i ask) Guido, all other Guru's, could this be a bug? References: Message-ID: "G. Willoughby" writes: > My particular OS is WinXP Pro, with ActiveState Python 2.1 (#15, Jun 18 > 2001, 21:42:28) with PIL (via ppm.py) installed. any ideas whats going on? Your program has crashed. You need to use a debugger to find out why it did that. Regards, Martin From deltapigz at telocity.com Tue Jul 23 20:19:27 2002 From: deltapigz at telocity.com (Adonis) Date: Tue, 23 Jul 2002 20:19:27 -0400 Subject: wxPython/PythonCardPrototype Message-ID: <3d3df28b_1@nopics.sjc> in the provided wrapper for wxHTML object, how can i insert text into it like a textarea? or does it have to be a file at all times? any help would greatly be appreciated. Adonis From not.this at seebelow.org Fri Jul 19 14:36:14 2002 From: not.this at seebelow.org (Grant Griffin) Date: 19 Jul 2002 11:36:14 -0700 Subject: file modification esoterica Message-ID: Hi Gang, I've got a couple of questions about file operations with Python on Windows. First, how can I take posession of a file such that other processes will experience a Windows "sharing violation" when they try to read or write it. (I've even found that one can open the same file for writing in two different Python instances without causing an exception! Perhaps this behavior is inherited from C or Windows, but regardless, it seems like a silent error that passed silently...) Second, what is the best way to "touch" a file, that is, update its modification time or "mtime" to the current time? Obviously one could read the whole thing and rewrite it, but is there a better way--preferably via a Python library function? extra-credit-to-those-who-can-answer-answer-both-questions--ly y'rs, =g2 _________________________________________________________________________ Grant R. Griffin g2 at dspguru.com Publisher of dspGuru http://www.dspguru.com Iowegian International Corporation http://www.iowegian.com From martin at v.loewis.de Mon Jul 22 01:25:49 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 22 Jul 2002 07:25:49 +0200 Subject: XML with Python - supposed to be simple? ;) References: Message-ID: "Vladimir Cherepanov" writes: > I skimmed through some w3c documentation on DOM, but didn't find anything > about creating documents, apart from the statement that "it's > implementation-specific" (why?!). Most w3c documentation concerns more > advanced topics like XML parsing, etc. Where did you read that it is implementation-specific? In the DOM, you have the general problem that it only specifies interfaces, not implementations. Implementation classes are, by nature, implementation-specific, and so are their class names. To create an instance of a class, you need the class name in most languages - that makes it implementation-specific. In most cases, the DOM solves this problem by providing factory functions. In DOM Level 1, there is no factory for creating Documents, hence creating them is implementation-specific. In DOM Level 2, there is the DOMImplementation interface, which makes creation of Document nodes portable. There is still no portable way to parse a document, or to serialize it. Those capabilities become available in DOM Level 3, which is not yet completely specified, and unimplemented in PyXML. > > You'll then learn that you can create > > Document instances by invoking createDocument on the > > DOMImplementation. For minidom, you get the DOM implementation by > > calling xml.dom.minidom.getDOMImplementation(). > > Thanks, I'll try this. Btw, I didn't find this method in DOMImplementation > Interface - the only method I found was "hasFeature()". It is a method to obtain a DOMImplementation object, so it cannot be an operation of the DOMImplementation - to call it, you would need a DOMImplementation first, and then this operation would be pointless. Finding DOM implementations is still implementation-specific, even in DOM level 3. PyXML adds a Python-specific registry for DOM implementations, via xml.dom.getDOMImplementation. This operates on a number of registered DOM implementations, invoking some module-level getDOMImplementation functions. > And what about serializing? Again, implementation-specific (in DOM Level 3, part of the load-store-specification). In PyXML, toxml() and writexml() can be useful. Regards, Martin From padhia at yahoo.com Mon Jul 1 19:07:34 2002 From: padhia at yahoo.com (P Adhia) Date: 1 Jul 2002 16:07:34 -0700 Subject: Python COM installation and NT Administrative rights. References: <3281a460.0206290652.51b800c9@posting.google.com> <3D1EB9C7.70901@skippinet.com.au> Message-ID: <3281a460.0207011507.2cd668c5@posting.google.com> Mark Hammond wrote in message > Installing Python 2.2 + the latest win32all *should* work here - but I > am sure there will be some problems. I downloaded http://starship.python.net/crew/mhammond/downloads/win32all-148.exe Installation program just quits immediately after the first welcome screen. The last dialog box that comes up recommends that I rerun the program with administrative privileges - something that I don't control. P. Adhia From perryk at itis.com Sat Jul 6 11:57:31 2002 From: perryk at itis.com (Perry Kivolowitz) Date: Sat, 06 Jul 2002 15:57:31 GMT Subject: NumPy Question: Audio Frequency Spectrum / Signal Analysis - pe_audioLevels.py [0/1] Message-ID: [This followup was posted to comp.lang.python and a copy was sent to the cited author.] I'm having a little touble writing a graphical view of an audio spectrum. I'm using NumPy, and Useful Things - a Python programmable plug-in for Adobe After Effects. I am totally inexperienced with respect to signal processing, so please excuse my (possibly) bogus use of terminology. It seems to work, with the exception that sounds close to silence (highly negative DB) are putting out enormous amplitudes. So much so, I have to put in a base DB check - squelching anything more negative to 0. This is the code which converts from samples to frequency data: m = 2.0 / float(numSamples) halfSamples = numSamples / 2 samplePeriod = 1.0 / float(sampleRate) * numSamples firstHarmonic = 1.0 / samplePeriod fftData = fft(samples) realTerms = fftData[1 : halfSamples + 1] then I do: frequencyAmplitudes = [ 0 ] * halfSamples for i in xrange(halfSamples): frequencyAmplitudes[i] = convertToDecibels(m * abs(realTerms[i])) to gather up data from a specific band I finish with (to show the min DB test): outputData[i] = 1.0 - (abs(bandAccumulator / bandCounter) - minDB) / (maxDB - minDB) if outputData[i] > 1: outputData[i] = 1 if outputData[i] < 0: outputData[i] = 0 where convertToDecibels is: amp2db = 20.0 / log(10.0) def convertToDecibels(a): if a < 1.0e-30: return -600 else: return amp2db * log(a) When the min DB setting is played with, I get great results. Without it being set right, I get blown out in the lower frequencies. If this isn't enough, I have enclosed the entire source. If you're an After Effects user, I can supply a free license to Useful Things so you can actually see what's going on (and code your own After Effects plug- ins in Python!) in exchange for your help. Thanks From zopestoller at thomas-guettler.de Wed Jul 31 12:22:01 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 31 Jul 2002 18:22:01 +0200 Subject: win9x or WinNT Message-ID: <3D480EA9.9020807@thomas-guettler.de> Hi! How can a python programm know if it runs on win9x or on WinNT? sys.platform always returns win32. I need to handle some stuff different if I am on win9x. thomas From pecora at anvil.nrl.navy.mil Tue Jul 9 14:39:25 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 14:39:25 -0400 Subject: Why self? References: Message-ID: <090720021439257166%pecora@anvil.nrl.navy.mil> [[ This message was both posted and mailed: see the "To," "Cc," and "Newsgroups" headers for details. ]] In article , Mark McEahern wrote: > What you don't see, of course, is all the people who are silent because > they're quite happy with self. prefixes and consider this a pointless > discussion usually kept alive by people who refuse to learn the idioms of > Python to their best advantage. Yeah, I may be one of those complainers. I have tried to learn the language well and really like it, but for some reason this self. thing really bugs me. (I _am_ seeing a therapist :-) ). I write a lot of scientifc code and I just think self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) is a LOT uglier than y= x**2 * t/z + a * FFT(tseries) -- Lou Pecora - My views are my own. From emile at fenx.com Sat Jul 13 08:26:02 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 13 Jul 2002 12:26:02 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: JB > I have two lists and . The entries of these > lists have the format (id,rest), where is a natural > number. The list are sorted, the key is . Your use of the term 'key' here is throwing me. Lists don't have keys, dicts do. Dicts aren't sorted. ;-/ > I should like to write a funtion move: > > def move(f): > > The argument is a predicate: > f: {set of entries of list1} --> {true, false} > Now all elements of list1, for which returns true, > should be moved to list2. It is very important, that > remains sorted, that is, the entries from > should be inserted to the right positions in . When So, you end up with duplicates in list1 based on id? > is defined by > n := max(len(list1),len(list2)), > then should work in O(n) time. > > Any hints of how to do this (as fast as possible)? >>> >>> l1 = [1,4,7,10,32,45] >>> l2 = [4,32] >>> >>> def f(lst): return 1 ... >>> [ l1.append(x) for x in l2 if f(x) ] [None, None] >>> l1.sort() >>> l1 [1, 4, 4, 7, 10, 32, 32, 45] >>> There, only took a minute. Is that fast enough? ;-) If you need a lot more speed, look into kjbuckets, but that'll take a lot longer. ;-) -- Emile van Sebille emile at fenx.com --------- From danieleburrow at yahoo.com Thu Jul 18 20:58:30 2002 From: danieleburrow at yahoo.com (Daniel E. Burrow) Date: 18 Jul 2002 17:58:30 -0700 Subject: Internet Explorer Automation Object Crossframe Element Troubles Message-ID: Greetings! Python Rocks! Now I feel better... Mr. Hammond's win32com extensions positively enthuse me as I continue to discover how they empower a OOP newbie whose long history includes VB, Perl, and QBasic. My present joy is to develop an automated monitoring tool that launches IE, logs on, and then navigates through our SSL-enabled web application. Thus far development has been rapid until I wanted to simulate a user clicking on a onclick=doChange('gotonewurl'). Since our app utilizes frames, I need to specify the frame and element that needs to be clicked. Like a good trooper, I studied the resources at: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&group=comp.lang.javascript http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/webbrowser/reflist_vb.asp?frame=true http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/objects/frame.asp?frame=true I found one who was doing what I am doing but it just causes my gut to twist. I am able to fire cross-frame elements now but doing so in the manner shown in the *** ClickCrossFrameElement *** method below troubles me greatly: ######### note the code is snipped in several places ############# import os, sys from time import sleep, localtime, strftime from mx.TextTools import * from cls_AleCommonErrorHandler import AleCommonErrorHandler from cls_AleCommonCommandLineInterface import AleCommonCommandLineInterface from cls_AleCommonRegistryInterface import AleCommonRegistryInterface from cls_AleCommonOracleInterface import AleCommonOracleInterface import win32com.client import pythoncom class AlerioWebReporter: """ A class providing navigating, element fillin, and page verification of web applications. If a page's contents does not contain the specified search string, a record will be posted to the "xxx.tb_ale_webreporter_run_reportable" Oracle database table. """ ClassCount = 0 def __init__(self): """ AlerioWebReporter constructor initializes each data member to nothing """ AlerioWebReporter.ClassCount += 1 print 'AlerioWebReporter: ClassCount:', AlerioWebReporter.ClassCount ############################ Set methods go here ########################## def SetIE(self): self.o_IE = win32com.client.DispatchEx("InternetExplorer.Application") self.o_IE.Visible = 1 def lots of other methods not shown(self): self.xyz ############################ Get methods go here ########################## def lots of other methods not shown(self): self.xyz ############################ Other methods go here ########################## def ClickCrossFrameElement(self, i_FrameId, s_ElementNameOrId): print 'i_FrameId', i_FrameId, 's_ElementNameOrId', s_ElementNameOrId o_IE_Frame_Element = self.o_IE.Document.frames[i_FrameId].document.all(s_ElementNameOrId).click() ## in ASP this was done as: ## parent.frames[FrameId].document.all(s_ElementNameOrId).click() ############################# destructor goes here ##################### def __del__(self): del self.o_ErrorHandler del self.o_CommandLine del self.o_RegInterface del self.o_DbInterface del self.o_IE print 'Destroyed: AlerioWebReporter, AlerioWebReporter.ClassCount AlerioWebReporter.ClassCount -= 1 ############################ Main here ########################## def main(): ##clear the screen os.system('cls') ##instantiate o_AleApp = AlerioWebReporter() ##set o_AleApp.SetAleAppWebReporter() ##get the values at_SQLRunMbrConfigResults = o_AleApp.GetAleAppFileReporterRunMbrConfigVals() if len(at_SQLRunMbrConfigResults) >= 1: i_RowCount = len(at_SQLRunMbrConfigResults) i_Row = 0 while i_Row <= (i_RowCount -1): i_Col = 0 s_URLId = at_SQLRunMbrConfigResults[i_Row][i_Col] i_Col +=1 s_URL = at_SQLRunMbrConfigResults[i_Row][i_Col] i_Col +=1 s_URLNavOrder = at_SQLRunMbrConfigResults[i_Row][i_Col] i_Col +=1 s_PostNavEventsFlag = upper(at_SQLRunMbrConfigResults[i_Row][i_Col]) ##now set the currently running id member o_AleApp.SetRunningRunIdMember(s_URLId) o_AleApp.NavigateIE(s_URL) ##fire events after nav? print "There are", o_AleApp.GetIEDocumentAllObjectCount(), "elements on", o_AleApp.GetIELocationURL() o_AleApp.ClickCrossFrameElement(1, 'Sub1t') i_Row += 1 else: s_Error = 'No Results found for: SQL:' + s_SQL + ' Params: ' + str(at_SQLParams) o_AleApp.WriteErrorHandlerRecord('ERROR', s_Error) print s_Error os.sys.exit() del o_AleApp if __name__ == '__main__': main() Joyfully About Alerio's Business, Daniel Burrow From tjreedy at udel.edu Thu Jul 18 12:41:55 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 18 Jul 2002 16:41:55 GMT Subject: raw_input References: <3D36C5F1.9C966A8F@millfilm.co.uk> Message-ID: "John Hunter" wrote in message news:m2ofd5xdrg.fsf at mother.paradise.lost... > >>>>> "Eric" == Eric Texier writes: > > Eric> It's there anything better than raw_input to query a string > Eric> input from the user in a console window. Thanks, Eric > > x = input('Enter a value: ') Ummm.... Since imput eval()s the input, this can be extremely dangerous -- so dangerous that some people think input() should be removed. There have been many prior postings on this subject. tjr From amuys at shortech.com.au Thu Jul 11 19:30:59 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 11 Jul 2002 16:30:59 -0700 Subject: Q: What does "Sparse is better than dense" mean? (Python Zen) References: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: <7934d084.0207111530.130b00b6@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <33803989.0207110328.5ef01f1e at posting.google.com>, > Miki Tebeka wrote: > > > >Although it's in the Humor section I take the Python Zen > >(http://www.python.org/doc/Humor.html#zen) quite seriously. > >However I can understand what does “Sparse is better than > >dense” means. > > To rephrase the dictum another way, "Don't try to stick too much code on > one line." Well seeing as we are discussing Python Zen, the one I don't currently understand is "Flat is better than Nested". I had always thought the opposite was the case, hence "Namespaces are one honking great idea -- let's do more of those! ". Can anyone explain the distinction? Andrae From gerhard.haering at gmx.de Sat Jul 6 09:58:02 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 6 Jul 2002 15:58:02 +0200 Subject: Why self? In-Reply-To: References: Message-ID: <20020706135802.GA5932@lilith.my-fqdn.de> * Roy Smith [2002-07-06 08:44 -0400]: > "David LeBlanc" wrote: > > Now if someone would just stand up and call eXtreme Programming the EXtreme > > BS that it is! :P > > That's kind of like standing up and saying that perl is a stupid > language. The reaction you get will be a very strong function of which > newsgroup you happen to be standing in when you say it. You're quite right. And I experienced that recently when I said in a VB newsgroup what I think of the language and the error handling in particular. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cce at clarkevans.com Wed Jul 24 00:26:14 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Wed, 24 Jul 2002 00:26:14 -0400 Subject: ANN: PyYaml 0.2 Message-ID: <20020724002614.A83207@doublegemini.com> introduction: > I'm happy to announce the first public open source python release "0.2" of YAML Ain't Markup Language (tm). The primary author of this release is Steve Howell. where: > http://yaml.org/python/PyYaml_24jul2002.tgz about: > YAML(tm) (rhymes with "camel") is a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages such as Perl and Python. YAML is optimized for data serialization, configuration settings, log files, Internet messaging and filtering. YAML(tm) is a balance of the following design goals: - YAML documents are very readable by humans. - YAML interacts well with scripting languages. - YAML uses host languages' native data structures. - YAML has a consistent information model. - YAML enables stream-based processing. - YAML is expressive and extensible. - YAML is easy to implement. More information about YAML can be found at http://yaml.org including the specification at http://yaml.org/spec/ any feedback you may have would be very welcome. notes: > This release of the parser/emitter doesn't handle in-line collections, nor does it handle typing well; bugs are to be expected. Best, Clark -- Clark C. Evans Axista, Inc. http://www.axista.com 800.926.5525 XCOLLA Collaborative Project Management Software From gareth.evans at wideawake.co.uk Wed Jul 17 11:43:13 2002 From: gareth.evans at wideawake.co.uk (gareth evans) Date: 17 Jul 2002 08:43:13 -0700 Subject: NetUnjoinDomain causes a memory error References: <3a8be3e4.0207170231.2e05a9c9@posting.google.com> Message-ID: <3a8be3e4.0207170743.2f9a622e@posting.google.com> for the source and pyd please go to http://www.trixibell.co.uk/~scmgre/download.html From fperez528 at yahoo.com Sun Jul 21 20:07:09 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 21 Jul 2002 18:07:09 -0600 Subject: maximum recursion depth References: Message-ID: <3D3B4CAD.5060804@yahoo.com> > I think I will rewrite my code using loops. This will be possible, I just > have to put my braincells back in active mode :-) > I found that a too deep recursion will slow down executing to much. > For now my program works with the recursion limit set at 3000. > However I can think of situations where this will not be enough. Recursion is expensive because function calls are expensive (in general, but especially so in python). Unwinding a stack 3000 layers deep is just asking for trouble. In most cases recursive algorithms are a good choice when you know that you won't go too deep, and when the actual work done at each call is substantial enough that the overhead of calling a function can be ignored. If either of those conditions isn't met, it's probably time to rethink the problem. You may want to look at generators. Since they don't have to build/uwind the stack, they may fit nicely for certain classes of problems. There's a very nice article on generators at IBM Developer Works which a quick google run will point you to. good luck, f. From aleax at aleax.it Thu Jul 25 07:43:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 11:43:51 GMT Subject: xml processing : too slow... References: Message-ID: Shagshag13 wrote: ... > sorry to bother, but i get "ExpatError: junk after document element: line > 1, column 188" and don't understand what it mean... > >>>> t = """ 1 2 3""" >>>> parser.Parse(t, 0) > Traceback (most recent call last): > File "", line 1, in ? > parser.Parse(t, 0) > ExpatError: junk after document element: line 1, column 188 Hmmm... the first time you call parser.Parse(t,0), everything is fine. The SECOND time, though, the parser sees a second toplevel tag, and that's an XML no-no. I know of no way to "reset" an expat parser instance to tell it to start accepting a new document from scratch. A call with a second argument of 1 does not appear to perform a reset, in particular. I guess you could trick the parser by starting with a first parse of, e.g. '' and ending with a last parse of ''. However, with such an approach, many kinds of errors would only be diagnosed at the very end, not for each given noncompliant line. Indeed, parser.Parse with a second arugment of 0 may be able to diagnose SOME errors, such as a tag being closed that was never opened, but not others -- assuming, that is, that you DO need each single separate line to be a well-formed XML documents (and with what other detailed constraints, we still don't know -- your examples show only single digits and spaces as contents, but we have no idea if that's part of the specs or just happenstance from your examples). I suspect you'll need to get a new parser for each line. Take heart, though. On my oldish PC, this script: import time from xml.parsers import expat t = """ 1 2 3""" start = time.clock() for i in range(100000): p = expat.ParserCreate() p.Parse(t,1) stend = time.clock() print stend-start prints 2.16, plus or minus 1/100 of a second. I.e., the pure work of looping 100,000 times, creating as many parser objects and parsing that same line repeatedly, takes a bit over 2 seconds on a cheap PC. I think it scales -- doing it 10,000 times takes 0.22 repeatably. So, for your 2,000,000 lines, instantiation and use of expat instances should be roughly 45 seconds, if your machine is comparable to mine. In fact, wait a minute... yeah, two million iterations DO print 43.11 (CPU seconds) to 43.4 (elapsed according to the time command is 45.12 seconds, using 96% of my CPU). You'll need to do more, of course (I/O, splitting, etc), but for the task of veryfying that each line is indeed well formed XML on its own, this approach seems to be quite viable, and should add less than a minute to your overall program's runtime. Not bad. Alex From theller at python.net Thu Jul 18 10:57:57 2002 From: theller at python.net (Thomas Heller) Date: Thu, 18 Jul 2002 16:57:57 +0200 Subject: property problem References: <3D36C65A.5040300@mplusr.de> Message-ID: Your class proptest must derive from 'object': class proptest(object): ... Quoting from http://www.python.org/2.2.1/descrintro.html#property: """Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its __dict__ without calling the property's set method, and after that, the property's get method won't be called either. (You could override __setattr__ to fix this, but it would be prohibitively expensive.) """ Thomas From emile at fenx.com Sat Jul 13 10:56:50 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 13 Jul 2002 14:56:50 GMT Subject: switch recipe? References: Message-ID: Mark McEahern > Because I want to do something to the zipped items, it doesn't seem like zip > solves all my problems, though. map would, if it had the same behavior as > zip--namely that it stopped once one of the iterators ran out of items. > Below is a version that shows the use of zip. Here are the key lines: > > weaved = zip(iterator, alternator) > generated = [color_item(x, y) for x, y in weaved] > > Perhaps what I'm still looking for is a way to > weave-two-iterators-with-a-function all at once. One solution would be to > modify or wrap repeating_alternator() so that it was finite--then I could > just use map. doesn't this do it? generated = [color_item(x, alternator) for x in iterator] (BTW, I nominate cycler as a name for alternator ;-) -- Emile van Sebille emile at fenx.com --------- From ld at nospam.com Fri Jul 5 20:09:23 2002 From: ld at nospam.com (Larry) Date: Sat, 06 Jul 2002 00:09:23 GMT Subject: idiots guide to python References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: "Mike Johnson" wrote in message news:626290cd.0207051529.518f4ce7 at posting.google.com... > I am starting an A-Level course in computing in september, and i will > need to learn how to use python. I have no previous experience of > programming, but could anyone point me in the direction of an "Idiots > Guide"? http://www.freenetpages.co.uk/hp/alan.gauld/ Look at the left side of the page. Looks like a good basic start for the absolute beginner!! Larry From mike at bindkey.com Wed Jul 31 16:27:47 2002 From: mike at bindkey.com (Mike Rovner) Date: Wed, 31 Jul 2002 13:27:47 -0700 Subject: __slots__ variables and initialization References: Message-ID: "Holden Caulfield" wrote in message news:c2595393.0207311037.5bacf413 at posting.google.com... > Greetings, > I don't recall exactly where I read it, but I had read that ALL the > variables > in __slots__ were initialized to None and are automatically part of > the instance attributes whether they are explicitly created in the > __init__ method or not. > In 2.2.1 this is not what is happening. e.g: > class X(object): > __slots__ = ['_x'] > def get_x(self): > return self._x > > >>> x = X() > >>> x.get_x() > I get an attribute error. Obviously, defining and '__init__' method > and explicitly creating it works. Is this the way it is supposed to > be? You can look at GvR "Unifying types and classes in Python 2.2 (Python Version: 2.2.1)" (http://www.python.org/2.2.1/descrintro.html): Some noteworthy tidbits and warnings about __slots__: a.. An undefined slot variable will raise AttributeError as expected. (Note that in Python 2.2b2 and earlier, slot variables had the value None by default, and "deleting" them restores this default value.) So don't rely on it, it was a bug. WBR, Mike From cliechti at gmx.net Fri Jul 12 17:21:32 2002 From: cliechti at gmx.net (Chris Liechti) Date: 12 Jul 2002 23:21:32 +0200 Subject: switch recipe? References: Message-ID: "Mark McEahern" wrote in news:mailman.1026501403.17010.python-list at python.org: > from __future__ import generators > > def make_switch(*args): > """Return a generator that loops through args.""" > if not args: > raise RuntimeError("Missing parameter: args.") this should be a TypeError, as the builtins raise that too raise TypeError("switch() takes at least one argument") > def switch(): > i = n = 0 > while True: > i = n % len(args) > yield args[i] > n += 1 > return switch > > Is switch a bad name for this? definetly yes ;-) as a C programmer, i expect something completly different... (switch() {case x:}) > Can anyone suggest a better name? how about "repeat"? 'cause that's what it does. > Other improvements? isn't this simpler, more obvious what it does, and still doing what you want: >>> from __future__ import generators >>> def repeat(*args): ... if not args: args = [None] #optionaly to catch empty args ... while 1: ... for x in args: yield x ... >>> zip(range(10), repeat('even', 'odd')) [(0, 'even'), (1, 'odd'), (2, 'even'), (3, 'odd'), (4, 'even'), (5, 'odd'), (6, 'even'), (7, 'odd'), (8, 'even'), (9, 'odd')] >>> chris -- Chris From vraghavan at cnmnetwork.com Wed Jul 31 17:26:48 2002 From: vraghavan at cnmnetwork.com (Srivatsan Raghavan) Date: 31 Jul 2002 14:26:48 -0700 Subject: problems with extending and embedding python on win2k Message-ID: <7b6e2177.0207311326.42397c33@posting.google.com> hello all, i am trying to extend and embed python .. i've used boost::python v1 to extend an existing C++ library to python.. and that works out beautifully :) from the commandline, or from idle i can import the api fine.. and use it great.. but when i embed calls to the python interpreter, i get ImportError's to bring this into the realm of the specific : Logging.dll is located in : C:\Python22\Libs\site-packages ===script.py import Logging def run() : e = Logging.Event() print e.str() ===script.py from the command line, when i do : python site.py , that works fine, and i get some output however, when in my app, when i do : ===LogTestApp\main.cpp std::string m_scriptName("C:\\script.py"); fp = fopen ( m_scriptName.c_str() , "r" ) ; PyRun_SimpleFile ( fp , const_cast ( m_scriptName.c_str( ) ) ) ; ===LogTestApp\main.cpp in the console window that pops up i get this error : Traceback (most recent call last): File "", line 1, in ? ImportError: No module named Logging Traceback (most recent call last): File "C:\projects\PythonLogEndPoint\script.py", line 3, in ? import Logging ImportError: No module named Logging so ,it appears to me that Libs\site-packages\Logging.dll is not being loaded.. which i can't explain, since i created another file that did nothing but print sys.path, and C:\Python22\Libs\site-packages *IS* part of the path .. so it appears the path is being searched, but for some reason my extension module is not being loaded.. i am using Microsoft Visual C++ 6.0 : Service Pack 5 on Windows 2000 : Service Pack 2 .. --vat vraghavan at cnmnetwork.com ==.sig== Evil requires nothing more to win than that good men do nothing. ==.sig== From phil at river-bank.demon.co.uk Mon Jul 8 04:55:05 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Mon, 08 Jul 2002 09:55:05 +0100 Subject: ANN: SIP/PyQt 3.3 Released Message-ID: <3D295369.6050606@river-bank.demon.co.uk> SIP and PyQt 3.3 have now been released and are available from their respective download pages at http://www.riverbankcomputing.co.uk/. Aside from a fairly small set of bug fixes, the highlights of this release are all related to programmer productivity. - Thanks to Detlev Offenbach, eric the debugger is alive and well and greatly enhanced with things like conditional breakpoints and the ability to debug Python console applications. See the screenshots at http://www.riverbankcomputing.co.uk/pyqt/eric.php. - Thanks to Hans-Peter Jansen, a number of examples of Qt SQL classes and data aware widgets have been added. These include a database browser and query submitter in about 180 lines of Python. - Thanks to Christian Bird, you can now enter Python code into Qt Designer and pyuic will extract the code and merge it with that generated automatically from your GUI design. The build system has been completely re-written so that they are now identical under Windows and UNIX. With this comes a number of benefits. - PyQt is now distributed as a single source package less than a fifth of the size of previous versions, instead of a package for each supported version of Qt. - If your compiler and system can handle it, the build system will take a fast build (-c) option. With gcc 2.95.2 on a 750MHz 256M PIII PyQt takes 10 minutes to compile. Phil From peter at engcorp.com Wed Jul 10 22:35:17 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Jul 2002 22:35:17 -0400 Subject: Learning how to program... but what's the best way? References: <3D2BB54C.90500@earthlink.net> Message-ID: <3D2CEEE5.74FAB80E@engcorp.com> Hans Nowak wrote: > > I know a 14-year-old who wants to learn programming. Of course I'd recommend > Python, and I also know the way to all the tutorials, non-programmers > introductions, etc. But... [...] > Besides this, does anyone have ideas about what would be a good starting point > here? When I learned, I started with maintenance rather than by writing new code. I took various games written in BASIC on the early PET machines, like Star Trek, and modified them to fix bugs like the one where you can't shoot an infinite number of photon torpedoes, or the one where your ship actually takes damage when hit by the enemy. (There were a lot of bugs in those games as I recall. ;-) I found this a very effective way to learn an awful lot, while staying very motivated at a time when I was incapable of getting excited by anything I could have constructed on my own. It was several years before I could write something that held my own interest enough to bring it close to usability. -Peter From petrk at pochtamt.ru Wed Jul 24 16:48:55 2002 From: petrk at pochtamt.ru (Petr Klyushkin) Date: 25 Jul 2002 00:48:55 +0400 Subject: threads and Tkinter References: Message-ID: Hello, Alex! >>>>> "Alex" == Alex Martelli writes: Alex> Petr Klyushkin wrote: >> Hello again! >> >> I have one more question about Tkinter. This time it is related >> with threads. I have a program which uses Tkinter as its GUI >> toolkit. It runs a separate "worker" thread for doing some >> time-consuming operation. Sometimes worker thread has to update >> GUI. Alex> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 Alex> It's also in the printed Cookbook, with some minor Alex> enhancements, but you can get the gist from the online-posted Alex> version at this URL. Hmm, two persons already answered on this post here and it seems that none of them even looked below the first paragraph of it because it sounds like a FAQ. I already know about 'periodical queue check' solution. I just want to know whether Tkinter is thread-safe. It seemed to me that it is because of Tcl lock in _tkinter.c I have received an advise by e-mail to unite thread messages and Tk messages handling in one function by overriding mainloop() method in Tkinter.Tk derived class. Here is a code snippet (i've tested it and it works nice for now on Windows and Linux): def mainloop(self, *args): """similar to mainloop, but also checks our Queue""" while not self.__quitMainLoop: while not self.thr_msg_queue.empty(): # process message from thread dispatch = self.thr_msg_queue.get() apply(dispatch[0], dispatch[1:]) # Do one event. Don't block if no events available. # '2' means TCL_DONT_BLOCK: # tcl.h: #define TCL_DONT_WAIT (1<<1) result = self.tk.dooneevent(2) if result == 0: time.sleep(0.020) #sleep for 20ms to allow other threads run if result < 0: break self.thr_msg_queue is Queue.Queue instance used by worker threads to communicate with GUI thread. Messages are really ready-to-use arguments for apply() function: function object and arguments. Are there any caveats and disadvantages in this code comparing to usual 'polling' solution? Alex> Alex -- C'ya, Peter. --=[petrk at pochtamt.ru]=--=[http://petrk.pochtamt.ru]=-- --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=-- From cliechti at gmx.net Fri Jul 26 10:44:55 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jul 2002 16:44:55 +0200 Subject: Best way to populate a wxListCtrl widget from mysql References: <75f0ku48rojqeqo7bs5il2df1vf55bg5pb@4ax.com> <3d415a50.3394307@netnews.worldnet.att.net> Message-ID: wjdandreta at worldnet.att.net (Bill Dandreta) wrote in news:3d415a50.3394307 at netnews.worldnet.att.net: > Hi Arneau, > >>What is the best way to populate a wxListCtrl from a Mysql query (may >>return more that one result). I would then Like to select one or more >>from the displayed results and perform another action on them. Any >>help so that I don't waste alot of time going in the wrong direction. > > Let me preface my remarks by saying that I am a newbie with wxPython. > I am using Boa Constructor to help me build apps and learn. > > I just did what you are trying to do with a wxGrid instead of a > wxListCtrl. > > I have not even looked at the wxListCtrl yet so I don't know if it is > a better choice. the problems i faced with the grid was, that i had crashes when resizing a grid. but i used a custom model for the grid, not the automaticaly generated model. i have now a reasonably fast and stable solution using a virtual wxListCtrl. it's a bit lage to post here (10kB) but i can send it to anyone who's interested. chris -- Chris From phr-n2002b at NOSPAMnightsong.com Thu Jul 4 21:28:42 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 04 Jul 2002 18:28:42 -0700 Subject: [OT] What is Open Source? (fwd) References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> Message-ID: <7xwusbyncl.fsf@ruckus.brouhaha.com> mertz at gnosis.cx (David Mertz, Ph.D.) writes: > |I think Clark was using contract in a metaphorical sense, describing a > |deal made with authors on one side, and society as a whole on the > |other. In what's called the "copyright bargain", society agrees to > |grant limited temporary monopolies, in exchange for increased > |"progress in science and the useful arts". > > Well... I suppose Clark's use is a metaphor. But it is an extremely > *bad* metaphor, one that does far more to conceal what's going on than > reveal. Is it a worse metaphor than "the copyright bargain"? That phrase has been around for decades or centuries and is generally considered apt. > The problem with Clark's metaphor is that it very strongly insinuates > something exactly opposite to the true legal/ethical structure. By > pretending that you "contract" for "intellectual property", you create > the illusion that IP is something inherently in your possession. I can > actually hold my bushel of corn, and as long as I hold it someone else > can't. By pretending IP has the same nature, one falsely > naturalizes--us Lukacsian's say "reify"--the "thing" that one "has." I have a worse problem with "IP" than with "copyright bargain". The copyright bargain is one that society (through its elected legislature) supposedly made with authors. The current problem is that the legislature acted in the interests of lobbyists rather than the electorate. From aleax at aleax.it Wed Jul 10 10:29:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 14:29:01 GMT Subject: newbie: binding args in callbacks References: <3D2C3CAB.BE7084F1@tds.net> Message-ID: Edward K. Ream wrote: > This question was asked a while back, and I don't see it in the FAQ or > in the archives... > > I would like to create a set of Tkinter callbacks that vary only in the > bindings of a single argument. For example, I would like to do: > > for val in vals: > b = Tk.Button(...,command=self.myCallback(val)) > > But this doesn't work: it executes callback, rather than returning the > callback function with the second arg bound to val. Right. > I also tried: > > for val in vals: > callback=lambda None:self.myCallback(x=val) > b = Tk.Button(...,command=callback) > > But that doesn't quite work either. When the callback executes I get: > TypeError: () takes exactly 1 argument (0 given) Indeed, you specified a lambda taking a single argument (accidentally named None just like the popular builtin object) and ignoring it. > Can someone explain how to do this? Thanks. My suggestion: def makeCallback(self, val): def callback(self=self, val=val): return self.myCallback(val) return callback and then: b = Tk.Button(..., command=self.makeCallback(val) ) You don't need the default-values trick in Python 2.2 -- so, if that's what you're using, it would be better to use, instead: def makeCallback(self, val): def callback(): return self.myCallback(val) return callback If you're insistent on using lambda (only sensible reason being that you made a bet about lambda being used here), you _can_, e.g. in 2.2: def makeCallback(self, val): return lambda: self.myCallback(val) but I think the nested-function approach is more readable. Alex From claird at starbase.neosoft.com Thu Jul 11 09:07:20 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 11 Jul 2002 08:07:20 -0500 Subject: Open document formats References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: <6425018709313012.B034167ED9F3563C.A514BB864F414733@lp.airnews.net> In article , David Mertz, Ph.D. wrote: . . . >As far as I know, every OS, since maybe 1985, has had drivers for >postscript printing. Almost all the applications that do not use OS Well, wasn't Windows itself holding out against PS for a long time? OK, I'm not motivated enough to research this myself just now ... . . . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From huaiyu at gauss.almadan.ibm.com Tue Jul 9 17:45:45 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 9 Jul 2002 21:45:45 +0000 (UTC) Subject: Splitting a string every 'n' References: Message-ID: Skip Montanaro wrote: > > Huaiyu> To work with any int n, change to one of these > > Huaiyu> rex = re.compile('.{,%s}'%n, re.DOTALL) # keeps remainder segment > >I think you want {1,%s}. Note the spurious empty string at the end if at >least one character isn't required: Yes, you're right. Teaches me to test before post. Huaiyu From shagshag13 at yahoo.fr Fri Jul 26 07:48:23 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 26 Jul 2002 13:48:23 +0200 Subject: extract elements of n char from a list References: Message-ID: "Shagshag13" a ?crit dans le message de news: ahrchl$v4n9l$1 at ID-146704.news.dfncis.de... > hello, > > i want to efficiently extract elements of n char from a list : > > n = 2 > l = ['this', 'is', 'an', 'example'] > nl = [] > for i in l: > if len(i) == n: > nl.append(i) > > nl = ['is', 'an'] > > but i think that some clever guru could use a map() / reduce() or something like that to speed up the process (which is what i really need...) well, i think that i could use : nl = [e for e in l if len(e) ==n] but is it efficient ? are they more efficient ways ? and when is it good pythoner technique to use list comprehensions ? thanks, s13. From jonathan at onegoodidea.com Fri Jul 26 17:27:23 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 26 Jul 2002 22:27:23 +0100 Subject: python class question References: Message-ID: On 26/7/2002 18:32, in article ahs0to$v8ku5$1 at ID-138381.news.dfncis.de, "Axel Bock" wrote: > But what am I trying to do? I try to assign the reference to a new object > to a member variable - so why does this not work?? Well presumably, and like I say I'm no Zope expert, Zope saves your objects into the database by grabbing the instance variables and "Pickling" them, i.e., writing out the data in such a way that it can re-create the original object again later when it's needed. Database connections can't be saved in such a way, so when you store a database connection into an instance variable of your object it makes it impossible for Zope to save it. Hence the Pickling exception. >> No, I'd say (as above) that 'self.connection' is a string, which means >> that 'self' has a method (or instance variable that refers to a class?) >> called 'MySQL_database_connection'. See what >> 'self.MySQL_database_connection' is. > > This is an instance of "Connection". But why can "dbc()" deliver an > instance of "DB" ??? (DB is a class, I checked) Erm, because that's it's job I guess. You call that to get a connection. >> Then perhaps you should just do the same in the member functions, i.e., >> call the machinery that creates a database connection. You could always >> wrap it in a method that returns a database connection. > > I can always ... how? ;-)) Well just put the code you originally wrote into a method something like so: def getDB( self ): dbc = getattr( self, self.connection ) DB = dbc() return DB Then use this in your methods when you need to talk to the database: def doSomething( self, withThis ): DB = self.getDB() result = DB.query( withThis ) return result.getOne() or something along those lines. I'm not sure I quite understand what you're trying to do in the first place though. Isn't the point of Zope that it manages the database for you and provides an object persistence mechanism? Jonathan From tg5027 at citlink.net Wed Jul 24 17:57:30 2002 From: tg5027 at citlink.net (terry) Date: Wed, 24 Jul 2002 17:57:30 -0400 Subject: Numeric data question In-Reply-To: <3D3F1160.EE1C1C19@cascade-sys.com> References: <3D3EF9AD.A0F661BC@noaa.gov> <3D3F1160.EE1C1C19@cascade-sys.com> Message-ID: >> Of course, such a thing could be implemented in Python as you >> suggest, probably with longs or strings emulating fixed-point >> numbers. James, Do you know if the database internal representations of currency are consistent across many/most databases? It would seem like that would have to be true for a Python to have a chance for an intrinsic implementation that would be relatively universally useful by ODBC connections, wouldn't it? However, interface packages like Pypgsql could translate from Postgres internal to Python internal representations without a problem - if it existed that is :). terry From fperez528 at yahoo.com Fri Jul 26 21:18:43 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 19:18:43 -0600 Subject: performance problem in python 2.2 References: <260720021725073781%mday@apple.com> Message-ID: Mark Day wrote: > > Maybe you missed Tim's comment about putting the loop in a function to > make it faster.??Using?that?trick?made?the?Python?version?as?fast?as > Perl on my machine. > Nice. I did miss that indeed. I guess in general this doesn't matter to me as I almost never have any top-level code, but it's something to be aware of. Out of curiosity, why does this happen? I understand looking up global variables when in a function being expensive, since you first must go through the local dict (and fail). But when the code is itself global and there's no other scope in sight, why is it any slower? In a sense, for global code 'everything is local', so I don't quite understand why the difference. cheers, f. From petrk at pochtamt.ru Mon Jul 22 03:07:58 2002 From: petrk at pochtamt.ru (Petr Klyushkin) Date: 22 Jul 2002 11:07:58 +0400 Subject: __del__ in classes derived from Tkinter classes References: Message-ID: Hello, Fredrik! >>>>> "Fredrik" == Fredrik Lundh writes: Fredrik> Petr Klyushkin wrote: >> So, when will Python object be destroyed? Suppose, I have >> following code: >> >> def f(): test2 = Test() f() >> >> When will test2 (Python object! not a Tk widget it represents) be >> destroyed? Fredrik> maybe when the function returns. maybe somewhat later. Fredrik> maybe when the interpreter exits. possibly never at all. Fredrik> (and using __del__ is usually bad style even outside Fredrik> Tkinter, but that's another story). >> Why? Fredrik> you don't know when they're called, you don't know if Fredrik> they're called, and you don't know in what state the system Fredrik> is when they are called. Fredrik> for more info, search google for "finalizers are bad", or Fredrik> variations thereof. I understand now, thank you for help. -- C'ya, Peter. --=[petrk at pochtamt.ru]=--=[http://petrk.pochtamt.ru]=-- --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=-- From shalehperry at attbi.com Wed Jul 3 15:34:47 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 03 Jul 2002 12:34:47 -0700 (PDT) Subject: REPEAT... UNTIL ? In-Reply-To: Message-ID: > > would be exactly the same as: > > """ > while 1: > ... > ... > ... > if bexpr: break > """ > > no? > that is basically the python idiom. The original poster would do well to search a few archives, this has been discussed at length many times. Just like the GOTO, or any other syntax from another language they belong to other languages and not python. A good coder learns to program in the idioms of the language they are using. Or they just write in the same style everywhere and their perl, C, java, whatever looks like their first language. From johnroth at ameritech.net Mon Jul 29 14:43:11 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 29 Jul 2002 14:43:11 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> Message-ID: "Steve Holden" wrote in message news:7Rc19.92310$724.23106 at atlpnn01.usenetserver.com... > "John Roth" wrote ... > > "Fredrik Lundh" wrote... > > > > What's the problem with that? If we give up the notion > > that anonamous functions need to look like expressions, > > it should be simple. Just stick the function definition inline, > > indentation and all. The only issue is defining a new keyword, > > since lambda doesn't work that way. "def" would probably > > work, since it's only allowed at statement level now. > > > I'd like to see an example of this, since it appears you haven't fully > thought this through. You mean you'd like to be able to write some thing > like the following: > > for word in 'fee fie fo fum'.split(): > Button(frame, command=lambda: > print word) > > This is currently acceptable in Python because the lambda's inside a > parenthesised argument list. How would I add a second line to the lambda? > I'm always suspicious of phrasing like "all you need to do..." or "the only > issue...", since it often indicates that insufficient thought has gone into > a proposal. And the reason I'm suspicious when other people do it is because > I've watched me doing it enough to get into trouble! > > Conclusion: this idea is currently 0.345-baked :-) for word in 'fee fie fo fum'.split(): Button(frame, command = def (): print word ) This isn't really the world's best example, because IMO, the lambda form is easier to read for something this small. However, it does give the guts of the idea: 1. instead of lambda (which needs to stay as is for backward compatibility) it uses 'def' as the keyword. 2. The remainder of the syntax exactly models def, including statement indentation within the expression. Notice that the first statement in the anonamous function has to be indented two from the preceeding line, because the continuation of the expression has to still be indented from the line with the 'def', and dedented from the statements. 3. The use of 'def' here reflects a comment from one of the posters that it's easy for people without experience in languages with first class functions to miss the fact that Python has them. Hope this helps. I considered it simple enough that it really didn't need an example. John Roth From cliechti at gmx.net Mon Jul 29 20:18:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 30 Jul 2002 02:18:11 +0200 Subject: pretty basic: get variable name from list of strings? References: <34kbku4j76104d193oevjfi83mk3olvsbt@4ax.com> Message-ID: chris <> wrote in news:34kbku4j76104d193oevjfi83mk3olvsbt at 4ax.com: > Thanks Andrew, > > I'll definitely look up how to use dicts. an look at list when your at it. it will ease your life too... > Will they also help in iterating other "treat string like code" > situations like wxPython object creation, here where I want to create > 100 radioboxes? > > for j in range(1,100): > varname = 'self.Box'+str(j) > varname = wxRadioBox(self, ID_j, name, wxDefaultPos, > wxDefaultSize, TeamList[j], 1, wxRA_SPECIFY_COLS) > EVT_RADIOBOX(self, ID_j, self.EvtRadioBox_j) box = [] #create an empty list #and populate it: for j in range(1,100): id = wxNewId() box = wxRadioBox(self, id, name, wxDefaultPos, wxDefaultSize, TeamList[j], 1, wxRA_SPECIFY_COLS) EVT_RADIOBOX(self, id, self.EvtRadioBox) self.boxes.append(box) and EvtRadioBox can find out which was the event source, no need to write 100 distict functions... > Surely there's a way to have a string like 'FileCount = 6' and tell > python to execute it. Wait a minute... execute... > > Aha, >>>> exec('horse = 9') >>>> horse > 9 yes, but nobody told you that until now because there is always a better, more powerful way to do it. chris (no, not the OP ;-) -- Chris From eaborges at hotmail.com Wed Jul 31 09:38:34 2002 From: eaborges at hotmail.com (Emanuel Borges) Date: 31 Jul 2002 06:38:34 -0700 Subject: Error including win32net in a Python COM server References: <3D4726D5.7050001@skippinet.com.au> Message-ID: > win32net uses functions only available on Win NT/2k/XP - you should use > win32wnet for Win9x. Thanks Mark but I am using these functions on a Windows 2000 system. The functions themselves work fine. It's when I include them into my COM server that gives me errors. If you register this code in your registry, do you have the same problems? I'm using VBA in Excel to access these methods, if that helps... Thanks, Emanuel Mark Hammond wrote in message news:<3D4726D5.7050001 at skippinet.com.au>... > Emanuel Borges wrote: > > > > The only difference that I have found is that in this particular COM > > server, I am importing win32net. And after doing some debugging I > > have found that the COM server works fine if I remove this import. > > This, however I can't do because I need NetUseGetInfo, NetUseAdd, > > NetUseDel & NetUseEnum for my Server to function correctly. I've > > win32net uses functions only available on Win NT/2k/XP - you should use > win32wnet for Win9x. > > Mark. From achim.domma at syynx.de Sat Jul 6 13:24:06 2002 From: achim.domma at syynx.de (Achim Domma) Date: Sat, 6 Jul 2002 19:24:06 +0200 Subject: swig or something else.... References: <3d26f83a@dnews.tpgi.com.au> Message-ID: Hi, perhaps a look at boost.python (www.boost.org) could help ? Achim "tALSit" wrote in message news:3d26f83a at dnews.tpgi.com.au... > Hi, I'm trying to interface a system i made in C++ with python using swig. > Ok, i've got it working, but I find it pretty ugly. Actually, way ugly. > > Given a C++ class: > > class cNode { > public: > cNode (const std::string & name); > set (const std::string & attr, const std::string & value); > // etc > }; > > Swig generates a series of _functions_, not a class with methods, so in > python I have to do this: > > obj = my_module.new_cNode ("someName") > my_module.cNode_set ("attrib", "value") > > Instead of something more like this: > > obj = my_module.cNode ("someName") > obj.set ("attrib", "value") > > Is this a limitation of swig, python or am I doing it wrong? > Because if it's a swig limitation, I might be able to do a workaround for > the 3-4 classes i need interfacing. If it's python, well, it doesn't matter. > But if it's me, please advise! > > Thanks!! > > > From andymac at bullseye.apana.org.au Sun Jul 14 04:07:46 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 14 Jul 2002 19:07:46 +1100 (edt) Subject: Python Embedded Instances In-Reply-To: Message-ID: On Sat, 13 Jul 2002, Tim Peters wrote: > [Andrew MacIntyre] > > I don't believe the Python core in its current form supports separate > > interpreter instances in the one application (something I understand Tcl > > can support). > > It does, but only at the C level (you can't create a new interpreter from > pure Python code). See the docs for Py_NewInterpreter() in the > "Initialization, Finalization, and Threads" chapter of the Python/C API > manual. Oops. Thanks for straitening that out. Hopefully the OP can take advantage of it. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From martin at v.loewis.de Tue Jul 16 16:55:50 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Jul 2002 22:55:50 +0200 Subject: gettext i18n References: Message-ID: Syver Enstad writes: > Are there any tutorials on this around? I read the i18n chapter in the > python documentation but it doesn't say much about what to do with the > files that pygettext and msgfmt generates. I recommend to read the GNU gettext manual. It is not specific to Python, but the concepts are the same. Essentially, you need to install them in a place where gettext.dgettext finds them. Regards, Martin From aleax at aleax.it Thu Jul 25 08:00:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 12:00:33 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <16Q%8.116512$Jj7.2728704@news1.tin.it> Message-ID: Jonathan Hogg wrote: ... >> I prefer simplicity. "Do the simplest thing that can possibly work". >> As you're showing, __call__ encourages tossing simplicity away. > > Hah. You've got me there :-) > > Yes, I believe in adding infrastructure that I know > the-day-after-tomorrow, I'll be glad I did ;-) Bingo. I had much the same approach for the first 20 years or so of my programming career, then it FINALLY started dawning on me that much of my "sure to be useful eventually" infrastructure WASN'T. When a short time later the XP guys finally started writing this idea down, worded quite well as the "You Ain't Gonna Need It" principle, that was one of the many things they wrote which went *PING!* in my head. I prefer to shorten the principle's name to "Ain't Gonna Need It", because that makes its acronym AGNI (Hindu God of Fire), AND because the "you" is actually redundant if I understand "slang grammar" correctly (isn't the great song's title just "Ain't Misbehavin'" without any pronoun?-). But that's by the by. > 'repr' is one of those things. I do a lot of work > at the prompt and being able to examine objects is a critical part of that > for me. When I write a closure, its repr is the inner function's name and ID, which is most often sufficient. When I need to inspect object behavior, Python makes it a snap to code object inspectors *WITHOUT* loading down the production version of those objects with any complication whatsoever. This "does the simplest thing that can possibly work" for EACH separate need: having objects that work with no extra baggage whatsoever, AND having a nice interactive environment -- the latter's needs vary widely depending on WHAT interactive environment we're talking about, after all (bare Python prompt vs richer IDE's). Admittedly the "infrastructure overhead" is tiny here, anyway. But if I had to make everything a class instance, just to ensure that all relevant state was in nicely named attributes, that pleasant things happen if i print the object or pickle it or add it to a quaternion, I'd never get any real work done. AGNI. Or, Matthew 6:34, if you prefer:-). > I guess we'll just have to agree to disagree on what counts as a "wart" > and "rare and weird" ;-) Yep, we'd better:-). Alex From squelart at hotmail.nospam.com Sat Jul 27 18:48:45 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Sun, 28 Jul 2002 08:48:45 +1000 Subject: xrange questioin References: Message-ID: <3d43234e$1@duster.adelaide.on.net> "Chris Liechti" wrote: > Uwe Schmitt wrote: > > as xrange() comsumes less memory than range() I ask why > > I should use range() at all.... is there any benifit > > from using range() ??? > > with range you get a true list which you can manipulate, sort, reverse, etc > ... you can't do that with xrange. > > chris > > -- > Chris Ok, let me rephrase Chris' question for a simpler case: What is better: for x in range(n) or for x in xrange(n)? (with n is relatively small, like 10 or 100) Cheers, Gerald. From boud at valdyas.org Thu Jul 4 08:40:39 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 04 Jul 2002 14:40:39 +0200 Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: <3d2442bd$0$94925$e4fe514c@dreader3.news.xs4all.nl> Ben Fairbank wrote: > I have several long (thousands of entries) dictionaries of words used > in plays; associated with each word is the number of times it is used > in the play. I have had no problem printing the words alphabetically > (send keys to a list, sort the list, access dictionary by the sorted > key list), but I have not found an elegant way to sort by frequency > of use. The best I have been able to do is a workable but inelegant > kluge that looks more like Basic than Python. Is there a "Python Way" > of doing that? > Well, basically you have table with two columns: word and frequency. Python's dictionary provides for only one index, on the first column. If you want to use the second column, you'll have to invert the dictionary, making it one mapping words on frequencies. That's always going to take some time. You might do something like: w2f={'a': 2, 'b': 2, 'c': 1, 'd': 3, 'e': 3} f2w={} for k, v in w2f.items(): if f2w.has_key(v): f2w[v].append(k) else: f2w[v]=[k] print f2w {1: ['c'], 2: ['a', 'b'], 3: ['e', 'd']} No doubt more elegant solutions exist, and it would be best to fill both dictionaries at the same time. -- Boudewijn Rempt | http://www.valdyas.org From gerhard.haering at gmx.de Sat Jul 20 09:59:10 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 20 Jul 2002 15:59:10 +0200 Subject: Lists & two dimensions In-Reply-To: References: Message-ID: <20020720135910.GA1067@lilith.my-fqdn.de> * Pichai Asokan [2002-07-20 06:46 -0700]: > I am a trainer and in a training session a participant came up with a > problem that stumped me: > -------------------- > board = [[-1] * 3 ]*3 > [...] It's useful to search the FAQ. Actually, I found it very useful to take the time once and read the _whole_ FAQ :-) Your relevant entry is http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.050.htp and it's called "My multidimensional list (array) is broken! What gives?" Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From rs at onsitetech.com Thu Jul 25 18:12:57 2002 From: rs at onsitetech.com (Robb Shecter) Date: 25 Jul 2002 22:12:57 GMT Subject: "Pure" OO Python documentation? Message-ID: <3D4077E8.1020504@onsitetech.com> Hi all, Is there documentation for OO Python that takes a high-level computer science sort of approach? I ask because the problem I see with the docs for many new/OO features: * mix implementation details along with the feature descriptions, and * are typically aimed at programmers migrating code from Python 1.x, or accustomed to programming with 1.x features. I'm thinking, for example, of the PEPs, or things I've generally seen people pointed to when they ask about a new feature like properties. The one document I've found so far that's along the lines of what I need (as a programmer learning the language better) is: http://userpages.umbc.edu/~glong/notes/python/notes11.html But this is fairly casually written, and doesn't cover everything (like staticmethod). Anyhow, if what I'm looking for doesn't exist, I'll probably get started writing it myself... :-) Thanks, Robb From chris.gonnerman at newcenturycomputers.net Wed Jul 31 01:27:16 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 31 Jul 2002 00:27:16 -0500 Subject: MySQLdb DictCursor scrambles field order References: <62e69c0c.0207302037.15c62bf7@posting.google.com> Message-ID: <006201c23852$f5ecb640$0101010a@local> ----- Original Message ----- From: "HW" > Hello, > > I am viewing some MySQL tables via Python CGI; I use the > MySQLdb.DictCursor in order to return the field names as well as the > data, so I can output a table with the field names as column headings. > > Unfortunately, the DictCursor seems to scramble the order of fields, > eg: > "SELECT field1, field2, field3 FROM table" > which returns the fields in order when using a standard cursor, seems > to rearrange the order (randomly?) with a DictCursor. What else did you expect? The fields are returned in the form of a mapping, which has no required or inate order to it. It's a hash. Again, why do you care? Are you iterating over the fields using the record's .keys() method? Keep track of the keys in a list if you need a specific order: keys = [ "field1", "field2", "field3" ] recs = cursor.fetchall() for record in recs: for key in keys: print "%s: %s" % (key, record[key]) (sloppy example I know... hacked it out in a hurry.) > I am using MySQLdb 0.9.1, Python 2.1, 3.23.51-nt under Win XP; I have > had the same trouble in a similarly numbered Linux version. > > Thanks for any help! > > HW Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From K.Rdt at TU-Berlin.DE Wed Jul 3 12:42:56 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Wed, 03 Jul 2002 18:42:56 +0200 Subject: HT clear some wxPython fram? In-Reply-To: Message-ID: Am 03.07.02 18:22:45, schrieb Vadim Zeitlin : >On Wed, 03 Jul 2002 17:05:02 +0200, Klaus Reinhardt wrote: >> HOW I CAN CLEAR SOME FRAME? > >feeling that you mean something completely different -- unfortunately it's not >at all clear what from your message. --------------------------------------------------------------------- Hi My problem is, that the I want to monitor netstat; this is in principle working (s.b.). But I don't want the scrolling frame for 2 reasons. 1.) ergonomic 2.) after a while of outputting the display is stopping, I think for memory-reaons. K at Rdt --------------------------------------------------------------------- # vim:tw=78:ts=3:sw=3: #********* So 30.06.02 17:45-1 ************** . . . . . . . . r 2 . p y w */ from wxPython.wx import * from wxPython.lib.infoframe import * import sys,os,thread import string import time #============================================ . . . . . . . . . . . . . . */ class MyFrame(wxFrame): def __init__(self,output): wxFrame.__init__(self,None,-1,"Close me...",pos=(0,110),size=(300,100)) output.SetParent(self) EVT_CLOSE(self,self.OnClose) EVT_TIMER(self, -1, self.OnTimer) self.timer = wxTimer(self, -1) self.timer.Start(3000) # self.timer.Start(1000) self.save_stdout = sys.stdout sys.stdout = self.output = output self.icon = wxIcon('1_ast.ico', wxBITMAP_TYPE_ICO) self.SetIcon(self.icon) def OnClose(self,event): sys.stdout = self.save_stdout self.output.close() self.timer.Stop() self.timer = None self.Destroy() def OnTimer(self, evt): y=os.popen( 'netstat -a -n','r').read() # self.Clear() # Clear() # frame.Clear() print "--------------------------------------------------------------" yy=y.splitlines() for i in yy: if i[:5]==" TCP": ry=string.split(i) print "%5s %22s %22s %22s" % (ry[0],ry[1],ry[2],ry[3]) #============================================ . . . . . . . . . . . . . . */ class MyApp(wxApp): def OnInit(self): frame = MyFrame(self.stdioWin) frame.Show(TRUE) self.SetTopWindow(frame) return true #-------------------------------------------- . . . . . . . . . . . . . . */ app = MyApp(1) app.MainLoop() #********* So 30.06.02 17:45-1 ************** . . . . . . . . r 2 . p y w */ From marklists at mceahern.com Fri Jul 12 14:46:37 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 13:46:37 -0500 Subject: Input again (!!@#&#$^@#$) In-Reply-To: Message-ID: > input = raw_input('What's your answer? ') When posting questions about syntax, it helps to paste an interactive Python session rather than pseudocode. input is a keyword; probably not a good idea to use it as a variable name. // m - From brueckd at tbye.com Thu Jul 18 23:32:09 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Thu, 18 Jul 2002 20:32:09 -0700 (PDT) Subject: win32com: makepy causes ie problems. In-Reply-To: Message-ID: On Thu, 18 Jul 2002, David LeBlanc wrote: > ie = DispatchEx('internetexplorer.application') > ie.visible = 1 > ie.navigate('http://www.w3.org') > > time.sleep(2) # let the browser get to it, but sloppy - how to wait on > browser ready? > > dom = ie.document > > I'm also interested, as the comment suggests, on how to wait for a browser > to finish navigating before I query it's state? Hi David, I use a function like this: def WaitForDoc(doc, extraDelay=0.0): if extraDelay: time.sleep(extraDelay) while not (hasattr(doc, 'readyState') and doc.readyState == 'complete'): time.sleep(0.1) The only time I use the extraDelay parameter is when the link/button fires some Javascript (e.g. form validation) that in turn loads a new document - without that extra delay the function would return before the new document even begins loading. -Dave From tl_news at nexgo.de Thu Jul 4 22:54:04 2002 From: tl_news at nexgo.de (Tino Lange) Date: Fri, 05 Jul 2002 02:54:04 GMT Subject: Newbie lists question References: Message-ID: Michael Hall wrote: > selectlist = [] > for last in result: > selectlist.append(last) > > produces the result when the list is iterated through and printed, > which looks something like this: > > ('van Rossum',) ('Wall',) ('Lerdorf',) ('Ousterhout',) > I know I could probably strip the round brackets and single quotes out > using a regex, but is there an easier way? Is there something pretty basic > about lists that I've missed here? Not about lists but about tuples :-) Your objects 'last' that you append to selectlist are tuples, not strings. (You get tuples containing just one element, a string with 'lastname' of each MySQL-dataset) So try: selectlist = [] for last in result: selectlist.append(last[0]) or just (with Python > 2.x) selectlist = [last[0] for last in result] Ciao, Tino From jason at tishler.net Tue Jul 2 17:03:30 2002 From: jason at tishler.net (Jason Tishler) Date: Tue, 02 Jul 2002 17:03:30 -0400 Subject: getatime() changes atime on cygwin In-Reply-To: <3D202C8E.6030509@thomas-guettler.de> References: <3D202C8E.6030509@thomas-guettler.de> Message-ID: <20020702210330.GB1776@tishler.net> Thomas, On Mon, Jul 01, 2002 at 12:18:54PM +0200, Thomas Guettler wrote: > time.getatime() (access time) changes the atime on cygwin. > > If a run the following script twice. The atime > got changed by the first run. See the following: http://www.google.com/search?hl=en&lr=&ie=ISO-8859-1&safe=off&q=site%3Acygwin.com+tishler+whacks+st_atime As you can see, I have been in this "special" place before... :,) Specifically, check out this one: http://www.cygwin.com/ml/cygwin-developers/2001-09/msg00076.html My WAG is that you are either running under 9x/Me or NT/2000/XP without ntsec. If so, then just calling Cygwin's stat() via os.path.getatime() will affect st_atime. If you are running under NT/2000/XP, then set CYGWIN=ntsec If you are running under 9x/Me, then you are SOL. > If I use the native version, the access time does not get > changed by calling time.getatime() This is to be expected. See the above. > The next strange thing: 'cat foo.txt' in cygwin does not change the > atime which you get if you call the getatime() in win32 python. > If I open it in an windows application it get changed. I can confirm the above. However, the attached Win32 (i.e., not Cygwin) program does *not* exhibit this behavior -- it properly notices the st_atime change. So, this may not be a Cygwin problem. Sorry, but you will have to dig deeper to solve this mystery. Jason -------------- next part -------------- /* * Copyright (c) 2002 Jason Tishler * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * A copy of the GNU General Public License can be found at * http://www.gnu.org/ * */ #include #define FACTOR (0x19db1ded53e8000LL) #define NSPERSEC 10000000LL long to_time_t (FILETIME *ptr); int main(int argc, char* argv[]) { HANDLE h; BY_HANDLE_FILE_INFORMATION info; BOOL s; time_t t; h = CreateFile( argv[1], GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0x2000000 | FILE_ATTRIBUTE_NORMAL, 0); if (h == INVALID_HANDLE_VALUE) { printf("CreateFile() failed with error = %ld\n", GetLastError()); exit(1); } s = GetFileInformationByHandle(h, &info); if (!s) { printf("GetFileInformationByHandle() failed with error = %ld\n", GetLastError()); exit(2); } t = to_time_t(&info.ftLastAccessTime); printf("access time = %s", ctime(&t)); CloseHandle(h); } long to_time_t (FILETIME *ptr) { /* A file time is the number of 100ns since jan 1 1601 stuffed into two long words. A time_t is the number of seconds since jan 1 1970. */ long rem; long long x = ((long long) ptr->dwHighDateTime << 32) + ((unsigned)ptr->dwLowDateTime); /* pass "no time" as epoch */ if (x == 0) return 0; x -= FACTOR; /* number of 100ns between 1601 and 1970 */ rem = x % ((long long)NSPERSEC); rem += (NSPERSEC / 2); x /= (long long) NSPERSEC; /* number of 100ns in a second */ x += (long long) (rem / NSPERSEC); return x; } From cbbrowne at acm.org Tue Jul 23 09:05:38 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 23 Jul 2002 13:05:38 GMT Subject: SMTP for SOAP in Python References: <3D3D217D.A5572039@lfpt.rwth-aachen.de> Message-ID: Quoth Lars von Wedel : > Hi folks, > > I saw a couple of libraries to support SOAP c/s in Python. > > However, all of them rely on HTTP as a transfer protocol > as far as I have seen. Are there any libs using SMTP? > > Doing my own implementation of SMTP transport, which would > be the best choice of SOAP library in terms of matureness > and extensibility? > > From SOAPpy in the pywebsvcs module it seems, that the biggest > part is the data type handling, whereas the actual data transport > is a fairly small piece of the overall code. Thus, an SMTP > extension should be easy or am I overlooking some details? All the SMTP extension for SOAP::Lite does is to intercept the data and throw it into an email message, perhaps MIME encoding it, so I'd say the answer to that is a pretty clear "yes." The unfortunate thing is that SOAP.py is seeing very scant maintenance, whilst the alternative, ZSI, seems to no longer be seeing maintenance either. -- (concatenate 'string "cbbrowne" "@cbbrowne.com") http://cbbrowne.com/info/soap.html "The chat program is in public domain. This is not the GNU public license. If it breaks then you get to keep both pieces." (Copyright notice for the chat program) From shalehperry at attbi.com Sat Jul 6 11:16:57 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 06 Jul 2002 08:16:57 -0700 (PDT) Subject: jwz threading algorithm in Python In-Reply-To: <20020706065818.GA4611@lilith.my-fqdn.de> Message-ID: On 06-Jul-2002 Gerhard H?ring wrote: > Has anybody implemented Jamie Zawinski's message threading algorithm in > Python, yet and would like to share it? > > Here's the specification: http://www.jwz.org/doc/threading.html > > I'm about half-way thru with converting the Java implementation to > Python (manual translation finished, in testing stage, now), but it > looks like the debugging will take me quite some time still. Also, the > code doesn't look very pythonic. If I could get a finished Python > implementation, this would be much better :-) > well when it is available be sure to put it somewhere public so we can all use it in our cool python email software (-: From fperez528 at yahoo.com Thu Jul 11 19:30:01 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 11 Jul 2002 17:30:01 -0600 Subject: Why self? References: <3D2E11B5.4070502@removethisandallhyphens-o-n-e.net> Message-ID: - c o v e n t r y - wrote: > No, you are only using a convention to let other developers know > that these variables are private - the python interpreter does not > even attempt to hide a '__' variable from other classes or code. > Private members are by convention only in python, they are not > enforced, thus you do not realistically get a similar result. > wrong. The interpreter mangles the __names automagically by adding the class name. You can work around it, but at least it helps to prevent accidents. So it is true that it is only a convention, but the interpreter does go to reasonable lengths to enforce it: In [14]: class foo: ....: def __init__(self): ....: self.__priv = 1 ....: In [15]: x=foo() In [16]: x.__priv --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ? AttributeError: foo instance has no attribute '__priv' In [17]: x._foo__priv Out[17]: 1 cheers, f. From nas at python.ca Wed Jul 31 11:56:27 2002 From: nas at python.ca (Neil Schemenauer) Date: Wed, 31 Jul 2002 08:56:27 -0700 Subject: ZPT Was: Good XML tools? In-Reply-To: <3D480545.8060500@thomas-guettler.de>; from zopestoller@thomas-guettler.de on Wed, Jul 31, 2002 at 05:41:57PM +0200 References: <3D46D1B5.248A2921@q-survey.be> <3D47C373.4040805@thomas-guettler.de> <3D480545.8060500@thomas-guettler.de> Message-ID: <20020731085627.A6314@glacier.arctrix.com> Thomas Guettler wrote: > Does PTL *always* give me the line number where the > error occured? I guess PTL uses eval() somehow. PTL does transformations on the abstract syntax tree before passing it to the code generator. The resulting bytecode is executed by the Python VM. If an error occurs a traceback is generated just like regular Python code. Neil From stagnoNOSPAM at prosa.it Tue Jul 2 13:06:32 2002 From: stagnoNOSPAM at prosa.it (Marco Stagno) Date: Tue, 02 Jul 2002 17:06:32 GMT Subject: [ANN] my_gui v.0.30 : a gui module for MySQL . Message-ID: my_gui.py is a simple Grafic User Interface for MySql It can be used as Python module to create your own MySQL interface. download it at http://www.prosa.it/projects/projects Change Log : ------------ 2002-07-01 * my_gui.py: Release (v.0.30) 2002-06-xx * added UserGrant menu * removed bug about comments * cleaned code * added show as text menu * still working on html menu * found bug about data >250KB; still working on it; red background if data is >250KB * changed GnomePopupMenu in GtkMenu * added tool menu (optimize table, show create, comment..) * added popup menu on notebook pages * removed bug about os.login (with xdm/gdm/...) * removed bug about limit * added icons in directory * added allignment in prefs/filter window * added index info in info menu * added MySQL menu * removed bugs about NULL (="\0") value 2002-06-20: * my_gui.py: FIRST PUBLIC RELEASE (0.24) MAS! From Jonathan_Epstein at nih.gov Wed Jul 17 13:20:59 2002 From: Jonathan_Epstein at nih.gov (Jonathan Epstein) Date: Wed, 17 Jul 2002 13:20:59 -0400 Subject: re/sre woes with Python 2.0 Message-ID: <2KhZ8.22$HD.214554@mencken.net.nih.gov> Hi, Can someone please explain why the following line produces a regular-expression compilation error with Python 2.0, but not with Python 1.5? Is this fixed in any later versions, and/or can you describe how to adjust the RE to make Python 2.0 happy? regexp2 = re.compile (r"(?s)STATE\s*\"([^\"]*)\"\s*(\w*)\s*(\w*)?\s*{(.*?)\n[ \t]*}(?=\s*(?:$|STATE))") TIA, - Jonathan From unlearned at DELETETHIS.learn2think.org Tue Jul 30 15:41:20 2002 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Tue, 30 Jul 2002 13:41:20 -0600 Subject: comparing strings References: <3d46e543$1_9@news.teranews.com> Message-ID: <3d46ebe0$1_3@hpb10302.boi.hp.com> "jadedlime" wrote in message news:3d46e543$1_9 at news.teranews.com... > Hi, I am very new to Python and very new to programming in general. > I need to take a particular string of data and compare it to a dictionary > which will put all matching records in a specific file and all the records > from the string that do not match in another to be dealt with on an > individual basis. > > I appreciate any and all help on this problem, part of the code is included. > this seems to produce the matches, but not the mismatches. > > > > import string, re, codecs > > # create inputs and outputs > > input = codecs.open("/home/jadedlime/Julio/julio.work", "r", > encoding="ISO-8859-1") > output = codecs.open("sec_try", "w", encoding="ISO-8859-1") > output2 = codecs.open("sec_trynotfound", "w", encoding="ISO-8859-1") > > # read and split the lines of the main julio records > > whole = input.read() > lines = string.split(whole, "\n") > > # create the dictionary with regular expressions built in > > dictionary = {"^aarl australian academic & research libraries$" : "10735", > "^acimed$" : "11225", > "^adbs: l'association des professionnels de l'information et > de la documentation$" : "11715", > "^alpha 94. strat\351gies d\222alphab\351tisation et de > d\351veloppement culturel en milieu rural\ > $" : "12205", > "^american archivists$" : "13185", > "^anales de documentaci\363n$" : "14165", > "^annual review of information science and technology > (arist)$" : "14655", > "^aproximaciones a la traducci\363n$" : "15145", > "^apuntes$" : "15635", > "^architectural records conference report$" : "16125", > "^archivaria$" : "16615", > } > > > # take the desired field (journal titles) and put it in a list format > > journallist = [] > for line in lines: > field = string.split(line, '"') > journalitems = string.strip(string.lower(field[23])) > journallist.append(journalitems) > > # compile the dictionary and make it into a list format > > dictionarykeys = dictionary.keys() > dictionarylist=[] > for dictionaryexp in dictionarykeys: > regular = re.compile(dictionaryexp) > dictionarylist.append(regular) > > # run a search that should match all the journal titles in the julio file to > the ones in > # the dictionary, if they match send them to a specific file, if they do > not, send them > # to another file so ajustments can be made. > > for key in dictionarylist: > for item in journallist: > if re.search(key, item): > output.write("found\t" + item + "\n") > else: > output2.write("not found\t" + item + "\n") I'm not sure exactly what you're seeing, but the following appears to work. I added a break under the output.write() call to end the loop prematurely and skip the output2.write() call if the item is found. I bound both output2 and output to sys.stdout and created two fictional lists for testing. If the strings are going to be exact matches as opposed to the key being a regular expression, you don't need re.search at all, but should be able to simply use cmp(key, item) == 0. >>> import re >>> import sys >>> dictionarylist=['abc', 'def', 'ghi'] >>> journallist=['def', 'ghi', 'jkl'] >>> output=sys.stdout >>> output2=sys.stdout >>> for key in dictionarylist: ... for item in journallist: ... if re.search(key, item): ... output.write("found\t" + item + "\n") ... break ... else: ... output2.write("not found\t" + item + "\n") ... not found jkl found def found ghi >>> -- Daniel Fackrell (unlearned at learn2think.org) When we attempt the impossible, we can experience true growth. From wrbt at email.com Wed Jul 31 16:24:34 2002 From: wrbt at email.com (Larry) Date: 31 Jul 2002 13:24:34 -0700 Subject: ASP performance problems Message-ID: <2ec1bc1c.0207311224.62d6c8a7@posting.google.com> I've implemented a web application on an NT/IIS platform using Python and Active Server Pages. Most of the heavy logic and database access is contained in modules that I import on the ASP pages, so the pages are pretty clean. It's usually a function call that returns a list that I loop thru to build tables and what not. My problem is that when heavier usage occurs the web server starts to really bog down. It's almost like a slowly growing thing where it gets slower and slower until it's unusable. It's not a problem with the database because when the production web server is crawling I can still use the development web server and everything is lightning fast. When I look at the task manager the CPU is really pegged, jumping around between 50% and 100%. Has anyone encountered this or does anyone have any thoughts? I realize IIS/ASP isn't the optimum deployment environment but this is killing me that vbscript app we had ran so much better. One question I have is the use of "del" and how important that is. I was under the impression objects would get swept up when I exited the function so I don't use "del" very often at all. Is it possible IIS is somehow becoming less efficient because of this? Thanks in advance. From fredrik at pythonware.com Mon Jul 1 12:15:35 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 16:15:35 GMT Subject: Pyrhon language dedicated Wiki Message-ID: I wrote: > http://www.python.org/cgi-bin/moinmoin btw, there's also: http://purl.net/wiki/python/FrontPage but for some reason, I've always found that one being a bit too twisted for my taste... From cliechti at gmx.net Thu Jul 18 05:56:39 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Jul 2002 11:56:39 +0200 Subject: Newbie : Processes management under W2K References: Message-ID: msachet at hotmail.com (Marc) wrote in news:df5ad326.0207172353.7d4d2fe3 at posting.google.com: > in order to kill a specific app, i'd like to know how to get the list > of all processes currently running under Win2000 with name, pid, etc.. for such things on win32 you'll need win32all: http://starship.python.net/crew/mhammond/ and it looks like there is an example included which lists the processes. chris -- Chris From spam at ob_scure.dk Sun Jul 7 08:29:42 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 07 Jul 2002 14:29:42 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2766B3.1010501@ob_scure.dk> Message-ID: <3D283436.8060308@ob_scure.dk> Alex Martelli wrote: > Thomas Jensen wrote: > ... > >>Oh, I thought Zope was "just" a product. > It's a product. Not sure what the "just" means here. I didn't known there was a Zope Corporation :-) >>I'm sorry I didn't make myself clear (in Denmark usually 5 nines means >>uptime or accesability for web services). Actually I belive we "only" >>guarantee 99,99% to our customers :-) > > That's quite another issue, and mostly related to setting up redundance > suitably (no single point of failure). And one in ten thousands IS much > more reasonable / achievable than one in a hundred thousands. I guess it is, and we do have redundancy on most of our systems. (We are currently looking into total redundancy, but it quickly adds up). [snip - VB6, etc] > I won't. But -- any opinion on the VB7, aka VBNET, release? On paper > it looks better than VB6 (it should -- they made two dozen incompatible > changes, each taking it a bit closer to Python:-) but I have no idea > about the reliability of the implementation, not having yet had to use it. Me neither. I think there are fundemental problems in basing a professional programming language on Basic, but they may have twisted the Basic part so much it is actually getting better :-) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From merkosh at hadiko.de Thu Jul 25 18:22:11 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 25 Jul 2002 15:22:11 -0700 Subject: DLL files Message-ID: hi, is it possible to write Windows DLL files in python? if yes - where do i have to look for documentation? thanks Uwe From fredrik at pythonware.com Sat Jul 13 09:10:01 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 13:10:01 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: Message-ID: Jonathan Hogg wrote: > Perhaps I'm missing something blindingly obvious here, but what benefits > would I gain from coming up with my own format? > > [Other than people who have some kind of allergic reaction to XML would like > it more.] - readability for humans: compare Python's current syntax with an XML-based representation of Python's AST, or some variant thereof... - readability for computers: no matter what compression you use, it's a lot easier for a computer to read pixels if you store them as bytes than if you store them as XML elements... but between the extremes, XML wins most of the time (especially if you stay away from SAX and DOM, and either use higher-level APIs, or more Pythonic low-level ways to access the infoset). but you knew that already, of course ;-) From danieleburrow at yahoo.com Fri Jul 19 01:01:45 2002 From: danieleburrow at yahoo.com (Daniel E. Burrow) Date: 18 Jul 2002 22:01:45 -0700 Subject: HTML DOM parser? References: <7xwursj0a4.fsf@ruckus.brouhaha.com> <3D373D7C.2237E7A3@engcorp.com> <7xvg7ck6dq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xvg7ck6dq.fsf at ruckus.brouhaha.com>... > Peter Hansen writes: > > How about automating IE using Python? > > > > from win32com.client import DispatchEx > > > > ie = DispatchEx('internetexplorer.application') > > ie.visible = 1 > > ie.navigate('http://www.nightsong.com') > > dom = ie.document > > > > etc... > > > > Access to the DOM tree of the document might be too slow for your > > needs, but if it's not, you definitely get a lot of bang for the buck... > > That's a really interesting idea and I might try it. I had been > thinking in terms of a Linux solution, but automating IE might be > ok for this particular application. Thanks. Greetings! My present task requires the automation of IE. After much prayer, I found that the "dom = ie.Document" assignment IS case sensitive. The lower case form of "ie.document" just would not work for my ActiveState ActivePython 2.2.1 distribution. Joyfully About Alerio's Business, Daniel From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 23:35:21 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 20:35:21 -0700 Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: <7xd6tyuc1y.fsf@ruckus.brouhaha.com> William Park writes: > I've found a partial solution. I'm now using, > ntpdate time.apple.com time.windows.com time.nrc.ca ntp1.cmc.ec.gc.ca > where 'ntpdate' comes from NTP package. Still, shell solution would be > desireable, because I sometime don't have access to Perl, Python, or NTP > packages. But, I do have access to shell all the time. > > I'll update when I find solution. :) I didn't know about ntpdate. I don't know of any way to open sockets from a shell script without something like perl, but maybe there is one. Awk might be another possibility. From edream at tds.net Fri Jul 26 16:35:20 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 26 Jul 2002 20:35:20 GMT Subject: Guide to the python interp. source? References: Message-ID: Actually, the documentation for PyDict_GetItemString is at http://python.org/doc/current/api/dictObjects.html#l2h-530 Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From fperez528 at yahoo.com Thu Jul 11 22:24:32 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 11 Jul 2002 20:24:32 -0600 Subject: Accessing stack (context) frames References: Message-ID: Ingo Blank wrote: > Hi, > > I wonder how it is possible, to access the current context (stack) frame > in Python. > In Smalltalk, there is (mostly) a "thisContext" method, from which one > can retrieve informations like the of the currently executed method. > > And that's exactly what I need. Retrieving the of the method, > currently > executed. > > def someFunction(): > myName = ... # How ? you want sys._getframe(): In [115]: sys._getframe ? Type: builtin_function_or_method Base Class: String Form: Namespace: Currently not defined in user session. Docstring: _getframe([depth]) -> frameobject Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack. This function should be used for internal and specialized purposes only. Disregard that warning, it's extremely useful if you know what you're doing :) f. From zopestoller at thomas-guettler.de Wed Jul 10 09:19:20 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 10 Jul 2002 15:19:20 +0200 Subject: Hierarchical Editor Message-ID: <3D2C3458.1090902@thomas-guettler.de> Hi! Does someoone know an editor for editing hierarchical text data? I need it for something like a todo-list. One task can have several subtasks. Should be a GUI, not an web application. Thank you thomas From cliechti at gmx.net Tue Jul 30 19:32:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Jul 2002 01:32:05 +0200 Subject: wxPython printing help References: Message-ID: CJ wrote in news:r65ekuoa4695hhru8ctlsh9urmupibj1k3 at 4ax.com: > iIs this even possible or am I wasting my time? sure you can print with wxPython. its almost like drawing on the screen, you just need some set up before. have you looked at the examples/demo that were installed along with wxPython? it contains a working printing example from which you can start. chris -- Chris From duncan at NOSPAMrcp.co.uk Tue Jul 9 09:29:18 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 13:29:18 +0000 (UTC) Subject: sorting many arrays from one... References: Message-ID: Alex Martelli wrote in news:nYAW8.59639$vm5.2174555 at news2.tin.it: > Shagshag13 wrote: > >> hello, >> >> i'm looking for an "efficient" way of sorting many arrays driven by one, >> for example >> >> drive = [1, 4, 2, 3] >> other1 = [a, b, c, d] >> other2 = [ k, j, h, l ] >> other3 = [14, 18, 19, 11] >> >> and i get : >> >> drive = [1, 2, 3, 4] >> other1 = [a, c, d, b] >> other2 = [ k, h, l, j] >> other3 = [14, 19, 11, 18] > > aux_list = zip(drive, other1, other2, other3) > aux_list.sort() > Fine so far. > for i in range(len(drive)): > drive[i], other1[i], other2[i], other3[i] = aux_list[i] A shorter way is: drive, other1, other2, other3 = map(list, zip(*aux_list)) and if you don't mind them turning into tuples you can even do: drive, other1, other2, other3 = zip(*aux_list) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From glace at users.sourceforge.net Mon Jul 8 05:08:34 2002 From: glace at users.sourceforge.net (glace) Date: 8 Jul 2002 02:08:34 -0700 Subject: Chinese language support of Python? References: Message-ID: <9d7d4fb3.0207080108.64f83695@posting.google.com> There will not be a GB version for chinesepython. GB support is invoked by the '-g' flag when you starts the chinesepython interpreter. {'-b':"for BIG5(default)", '-g':"for GB"}. For source files stored with different encodings, "#--GBK--" and "#--BIG5--" magic comment strings should be place in sources to indicate the respective encodings used. Try again ^_^ glace guidance_shanghai at yahoo.com.cn (Leon Wang) wrote in message news:... > I installed ChineseCodecs1.2.0 into lib/encodings, it converts GB2312 > (simplified Chinese) to UTF-8, and I can use this: > > root.title(unicode('中文',"eucgb2312_cn")) > > Great! I can put whole raw Chinese string in source now! > Before that, I also tried ChinesePython, a Chinese translation version > of Python 2.1, it even enabled this: > > root.title('中文') #directly put Chinese in normal string! The Best!! > > But a little pity, it translated all prompt/error messages into BIG5 > (Traditional Chinese), I can not view them in my GB Windows > environment, and no GB version available now yet. I have to uninstall > it and adopted the first solution. > > More pity: the "Python GUI" utility -- IDLE, can not handle Chinese > string in source file(seems bit7 removed), neither the Python2.2.1 > from python.org nor above chinesepython versions. If I open my source > with IDLE and save back, all Chinese string will be changed, this > means I cannot use it even for edit. Then, how can I debug the script > in GUI? > > Thanks! > Leon Wang > From brueckd at tbye.com Mon Jul 15 14:52:58 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 15 Jul 2002 11:52:58 -0700 (PDT) Subject: HTTP_USER_AGENT Parsing In-Reply-To: <3d32f2ac$1@pull.gecm.com> Message-ID: On Mon, 15 Jul 2002, Olly Smith wrote: > I'm a bit of a newbie to Python, and in my quest to generate nice HTML > content, I need a way to work out what browsers clients are using from their > HTTP_USER_AGENT strings. > > Any pointers? - Googling for lists of User Agent strings will give you sample Javascript to determine client platform and browser based on user agent value - this is pretty easy to port to Python. - The same Google search will turn up lists of known user agent strings, which will be useful for your test code. - User agent strings are not 100% reliable, but few people change them, so they are fairly accurate (you can generally even detect browsers like Opera, even when they are reporting themselves as IE). - Also check the HTTP spec, as it list the official format of user agent strings. It's basically a list of names, each followed by an optional version number and an optional list of additional info. On the end of the line can be an optional language code too, I think, e.g. "[en]". - For most people it's not worth the effort to invest too much time doing browser-specific HTML. ;-) HTH, -Dave From doru-cat at ifi.uio.no Tue Jul 30 09:44:10 2002 From: doru-cat at ifi.uio.no (Doru-Catalin Togea) Date: Tue, 30 Jul 2002 15:44:10 +0200 Subject: Good XML tools? In-Reply-To: References: Message-ID: > Can you recommend any good XML packages for Python? I looked at the > PyXML but it seems to be lacking proper documentation (=unusable). A short while ago, somebody posted the following links to online tutorials for pyxml ++. I downloaded them (after a rather bothersome registration and "type your password many times" procedure) and they seem to be both acurrate and somewhat comprehensive. I did not read them thoroughly yet. ------------------- Python and XML development using the open source 4Suite toolkit 4Suite is an open source, comprehensive library and toolkit for XML processing in Python. 4Suite implements various open standards related to XML. This series of tutorials introduces 4Suite and gives practical examples of XML development using 4Suite and Python. Part 1: PyXml There are various DOM implementations, in varying computer languages. Here, we will be introducing PyXml. This particular implementation is written in Python. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/28BEDEE3E7219EB386256AE300743B69 ?Open&t=gr,lnxn28,p=PyXml Part 2: 4XPath and 4XSLT This tutorial introduces 4XPath and 4XSLT . If you plan to use Python in association with XML processing, these are useful tools to get to know. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/BE1A7E60838F9F7686256AF400523C58 ?Open&t=gr,lnxn28,p=4XPath4XSLT Part 3: 4RDF This tutorial will go into detail on RDF, with hands-on examples of how to use the various RDF facilities available with Python. http://www-105.ibm.com/developerworks/education.nsf/xml-onlinecourse-bytitle/8A1EA5A2CF4621C386256BBB006F4CEC ?Open&t=gr,lnxn28,p=4RDF ------------------- Catalin <<<< ================================== >>>> << We are what we repeatedly do. >> << Excellence, therefore, is not an act >> << but a habit. >> <<<< ================================== >>>> From SSchukat at dspace.de Mon Jul 22 04:49:33 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Mon, 22 Jul 2002 09:49:33 +0100 Subject: Python to Excell Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B236@PDC-DSPACE> Search for excel8/9/10.olb an run makepy on it. There you'll have all the classes available from Excel. or run "win32com.client.EnsureDispatch('Excel.Application', 0)" and search the [PYTHON_ROOT]\Lib\site-packages\win32com\gen_py directory for the generated module. or use the macro recorder of excel and translate it to python code or use the excel online help or buy a book "Python Programming on Win32" or ... Stefan -----Original Message----- From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] Sent: Monday, July 22, 2002 8:33 AM To: python-list at python.org Subject: Python to Excell Hi all, I want to use Python to automate Excell. What I want to do is writing a script which updates an Excell sheet and which prints it out then. I know the stuff about DispatchEx but I do not know the interface which is exposed by Excell. Can anybody help me further on this one? Thanks, Henk -- http://mail.python.org/mailman/listinfo/python-list From andreas at kostyrka.priv.at Thu Jul 25 13:33:39 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 25 Jul 2002 19:33:39 +0200 Subject: Python UDDI implementation In-Reply-To: <3D3D4BBC.D4A650CF@xrce.xerox.com> References: <3D3C104D.1EDB2D48@xrce.xerox.com> <915a998f.0207220933.44a332ef@posting.google.com> <3D3D071F.BADCBD13@xrce.xerox.com> <6E449FA9D58D737A.5DF5F4A9FA118F2D.539821FD244E28D6@lp.airnews.net> <3D3D4BBC.D4A650CF@xrce.xerox.com> Message-ID: <1027618306.8774.132.camel@vaio2> Am Die, 2002-07-23 um 14.27 schrieb David Levy: > thanks !! > > no python implementation on the way ? !! > my boss don't like *Java* > hihi Well, then go with Jython/Java :) Andreas From mwh at python.net Thu Jul 25 10:33:47 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 25 Jul 2002 14:33:47 GMT Subject: Q: indent settings for Python C style (pep 7) References: <33803989.0207210230.6b9ec0c3@posting.google.com> Message-ID: tebeka at cs.bgu.ac.il (Miki Tebeka) writes: > Hello All, > > I recall seeing settings for indent (http://www.gnu.org/software/indent/) > to make it produce pep-7 compatible code. > Can't find it now. > > Any pointers? I think they were posted to python-dev at some point. Can't find them now, though, so I might be making that up. Cheers, M. -- The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offence. -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5 From duncan at NOSPAMrcp.co.uk Tue Jul 23 10:01:09 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 23 Jul 2002 14:01:09 +0000 (UTC) Subject: Python very slow on the Sharp Zaurus - any idea why? References: <7xfzybii29.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in news:7xfzybii29.fsf at ruckus.brouhaha.com: > Is the idea here to discover if a*b overflows 32 bits, if a and b are > 32 bit ints? > > On compilers supporting 64-bit (long long) ints, it may be faster to > use them instead of floating point for this check. I think that > includes GCC and current Microsoft compilers among others. The Microsoft compiler certainly can do that. I think the code below does all the overflow checking, and the Microsoft compiler just uses the native multiply opcode to implement it: #include #include int safemultiply(__int32 a, __int32 b, __int32 *res) { __int64 product = (__int64)a * b; __int32 low, hi; low = (__int32)(product & 0xFFFFFFFF); hi = (__int32)(product >> 32); if (hi == 0) { if (low < 0) return 0; } else if (hi == -1) { if (low >= 0) return 0; } else return 0; *res = low; return 1; } int main(int argc, char**argv) { /* Some tests */ __int32 res; assert(safemultiply(1, -2147483648, &res)); assert(res == -2147483648); assert(!safemultiply(-1, -2147483648, &res)); assert(!safemultiply(-2, -2147483648, &res)); assert(!safemultiply(-2147483648, -2147483648, &res)); assert(!safemultiply(-2, -2000000000, &res)); assert(safemultiply(5, 5, &res)); assert(res == 25); printf("All tests passed\n"); return 0; } -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From dark_phenix_98 at yahoo.fr Wed Jul 24 10:44:07 2002 From: dark_phenix_98 at yahoo.fr (ferreira jorge) Date: Wed, 24 Jul 2002 16:44:07 +0200 Subject: error code Message-ID: <3d3ebee7$0$4203$afc38c87@news.easynet.fr> Hi I want to get the code of an error . how can I do that ? With "sys.exc_value" and "sys.exc_type" I have a String . But I want a Integer Thanks From johnroth at ameritech.net Sun Jul 7 19:01:59 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 7 Jul 2002 19:01:59 -0400 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> Message-ID: "Roy Smith" wrote in message news:roy-482A07.16532307072002 at reader2.panix.com... > Peter Hansen wrote: > > We put all of ours in a subdirectory called "unit" [...] we similarly > > use "_user" or "_accept" at the end > > That makes sense. > > > As for getting out of sync -- this is not a problem if you always > > write the test code before the application code > > I know that's the way it's supposed to happen, but somehow we never seem > to quite reach that particular state of bliss :-) Well, that's because the only people I know who always do this are XP people practicing test driven development. Otherwise, it's simply more interesting to jump right into the code, and hammer on it later to make sure it works. > > We modify PYTHONPATH to include ".." first and run from the folder > > containing the tests. Then the "import module" is all we need. > > Seems reasonable. > > > By the way, you might encounter problems with "module-test.py" as > > a file name at some point... you couldn't import it, for example. > > Use underscores instead of hyphens... > > Good point; I hadn't thought of that. We've been using the > "filename-test" convention with our TCL stuff, and I brought it over > from that. > > Thanks for the input. From peter at engcorp.com Thu Jul 18 18:13:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Jul 2002 18:13:16 -0400 Subject: HTML DOM parser? References: <7xwursj0a4.fsf@ruckus.brouhaha.com> Message-ID: <3D373D7C.2237E7A3@engcorp.com> Paul Rubin wrote: > > Anyone know of a Python-callable HTML DOM parser? I mean a serious > one that tries to understand the crappy malformed out there in the > real-world Web, the way a browser does. If it can interpret > Javascript that's even better. This is for a consulting client, so a > commercial library would be acceptable (though not preferred). How about automating IE using Python? from win32com.client import DispatchEx ie = DispatchEx('internetexplorer.application') ie.visible = 1 ie.navigate('http://www.nightsong.com') dom = ie.document etc... Access to the DOM tree of the document might be too slow for your needs, but if it's not, you definitely get a lot of bang for the buck... -Peter From nas at python.ca Tue Jul 16 11:50:41 2002 From: nas at python.ca (Neil Schemenauer) Date: Tue, 16 Jul 2002 08:50:41 -0700 Subject: Session ID & Security In-Reply-To: ; from thefogger@web.de on Tue, Jul 16, 2002 at 05:33:20PM +0200 References: Message-ID: <20020716085041.A11455@glacier.arctrix.com> Jan Felix Reuter wrote: > Now I'm concerned about security, because with this sheme an attacker could > easily get access to a user's session by just guessing its ID. Use a larger random session ID. 64 bits should be enough for most situations. Neil From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 09:59:17 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 08:59:17 -0500 Subject: Newbie: How to touch "global" variables In-Reply-To: <3D46836B.2506F469@lmco.com> (Jeff Layton's message of "Tue, 30 Jul 2002 08:15:39 -0400") References: <3D4568D5.3254F968@lmco.com> <3D46836B.2506F469@lmco.com> Message-ID: >>>>> "Jeff" == Jeff Layton writes: Jeff> If you have a few moments, could you help me understand Jeff> this a bit better and apply it to what I need? The basic Jeff> concept is I need some kind of "container" class that holds Jeff> variables that are defined in the code (the variables will Jeff> not be known a priori). I would then pass that class to a Jeff> function in a module that would perform some operations Jeff> based on the variables, but not necessarily change the Jeff> variables (I may change my mind on that at a later date). Jeff> So, I would need a class that would allow me to "add" Jeff> variables do it and store all of the information about it's Jeff> state (I assume using Alex Martelli's Borg Class). I could Jeff> then pass the instance of the class to other functions on Jeff> other modules for their use. Does this make sense? Hi Jeff In the future, please respond to the group. That way other people can contribute to and learn from the dialog. Don't be shy -- everybody was a newbie once. There are 2 good ways to do what you want. A simple class (not borg) or a borg. Which one you choose depends on your application and data. Think about your container class -- should all your classes and functions see the same data and do you want changes made in one place to be reflected everywhere? Are you sure there is only one unique instance of that container? If so it's a borg, if not a class. Example: Suppose you had a class City. That class might contain a lot of data -- a list of residents, an integer specifying a zip, a string specifying the name of the city, etc... You could pass around instances of that class c1 = City('New York') to a function, which might call c1.add_resident('Bill'). By passing instances of c1 around, other functions, classes and code could access and/or change the data in c1. But City is not a Borg, because you might want to make a second city c2 = City('Chicago'), which would function independently of c1. On the other hand, if you made a class Chicago, that would be a Borg, because there is only one Chicago. In the case above c1 and c2, are instances of the class City and are different and can hold different information. Changes made to c1 are not seen in c2. If Chicago is a Borg, all instances will be the same. So if you say c1 = Chicago() and c2 = Chicago() and c1.add_resident('Bill') then c2 will know about Bill. Below is some example code, using Name as a regular class and MyShared as a Borg. There are 3 files: the main code, a file containing some functions and a module MyShared containing the Borg. A Borg should be placed into a module so other modules can load it. This example was made just to show the effects of modifying and accessing instances of classes and borgs from code that may live in a different module. In real life, you want to be careful about modifying instances in functions. If you do, make sure the functions are clearly named, like add_resident. John Hunter -- begin main_borg.py --- # this is the main level code from MyShared import MyShared from somefuncs import func1, func2 # A plain old class class Name: def __init__(self, first, last): self.first = 'John' self.last = 'Hunter' def __str__(self): return '%s %s' % (self.first, self.last) m = MyShared() n1 = Name('John', 'Hunter') n2 = Name('Joe', 'Bloggs') print n1 func1(n1) # adds a middle initial print n1.middle # changes made in func1 are preserved at the main level #print n2.middle # this is an error; n2 doesn't have a middle initial func1(n2) print n2.middle # this is ok now # MyShared is a borg, so changes made in func2 are accessible in # the main level, and vice versa. We don't have to pass m to the # function func2() print 'main: ', m.y m3 = MyShared() # create a new instance of MyShared print 'main: ', m3.y # still the same.... -- end main_borg.py --- --- begin MyShared.py --- # You want all everyone to be able to see this class and all instances # should be identical class MyShared: __shared_state = {} y = ['A', 'list', 'of', 'strings'] def __init__(self): self.__dict__ = self.__shared_state # this is the heart of the borg # double underscore is private; can only be accessed through # get and set self.__x = 1 def get(self): return self.__x def set(self, x): self.__x = x --- end MyShared.py --- --- begin somefuncs.py --- from MyShared import MyShared def func1(n): print 'func1: the first name is %s' % n.first n.middle = 'D.' # I can add a middle initial and the main level # will see it. def func2(): # m2 this is the same as m in the main code m2 = MyShared() m2.y.append('func2 was here') print 'func2: ', m2.y --- begin somefuncs.py --- From nookieNOSPA_M at online.no Mon Jul 8 06:27:41 2002 From: nookieNOSPA_M at online.no (Erlend J. Leiknes) Date: Mon, 08 Jul 2002 10:27:41 GMT Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: <3D2968E7.3010106@online.no> Thinkit wrote: > These people are dangerous, and will boot you if you do not agree to > their narrow worldview. They are an affront to the python > language--especially "dash". dash is an *evil* AI written for destruction of your mind! oh, its not true that you need to agree, they dont kick you if you think of their "reccomondations" as the absolute truth (they dont even have @'s, just to make the channel a bit friendlier place to be), they are good programmers and you should concider their opinions. -- Noen From bokr at oz.net Wed Jul 17 11:56:49 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Jul 2002 15:56:49 GMT Subject: Making code faster References: <3d3445f9_7@news.newsgroups.com> <3d353fee_10@news.newsgroups.com> Message-ID: On Wed, 17 Jul 2002 12:06:39 +0200, JB wrote: >Bengt Richter wrote: > >>>[,] >> - Do you mean that literally? I.e., would >> "['abc','def']\n" >> be a valid example? >> - Why do you have to eval() it? That is probably >> timeconsuming compared to alternatives. > >I thought, that would be fast. I can choose the format that >is best. (But probably, I 'd like to have a text format.) >So I could shoose >abc def Simple is generally good ;-) >too. > >> - Are there always two elements in the list? >Yes. > >Now I have changed my program to > > i = -1 > print 'loading file' > def tmp1(s,color=self.sv.lv.newColor): > global i > i += 1 > j = string.find(s,' ') > return QSimpleViewItem(i,color,[s[:j],s[j+1:-1]]) Replacing the above 2 lines with the following one should be faster: return QSimpleViewItem(i,color,s.split()) It assumes you have an s from your file that looks like Where is one or more optional white space characters [ \t\r\n\f] and is at least one white space character. Note how split() works: >>> 'abc def'.split() ['abc', 'def'] >>> 'abc def\n'.split() ['abc', 'def'] >>> ' abc def \n'.split() ['abc', 'def'] >>> ' abc def \n '.split() ['abc', 'def'] >>> > > try: > myfile = open(filename) > except: > pass > else: > tmp = myfile.readlines() > print 'lines loaded' > myfile.close() > self.sv.lv.rows = map(tmp1,tmp) > self.sv.lv.visible = range(len(self.sv.lv.rows)) > print 'lines decoded',self.sv.lv.rows[0].col[0] > >This is really faster. I did not undertand, how to get rid >of the global variable , but even if I do not use i at >all and replace it by 0, the time I need is the same. > That was a good experiment, showing that global/local is insignificant compared to other overheads in this particular loop. But if you have a loop where the other stuff is really fast, you will notice a difference when you execute enough loops. Regards, Bengt Richter From aleax at aleax.it Fri Jul 26 03:14:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 07:14:05 GMT Subject: new module and class/type unification. References: Message-ID: <1F609.141869$vm5.4633059@news2.tin.it> Fredrik Stenberg wrote: > > Morning.. its 04:26 localtime so my intellect is not on top. > Anyway.. I'm playing with the class/type unification and i don't > understand why the following code doesn't work (2.2) > > import new > new.instance(str,None) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: instance() argument 1 must be class, not type > > > Is this is a bug? or am i missing the big picture > in type/class unification and the new-module? > > /fredriks alias princeps... new.instance only supports classic classes, that's all. Nothing mysterious at all. Alex From alexandrecourbot at linuxgames.com Mon Jul 22 17:21:53 2002 From: alexandrecourbot at linuxgames.com (Alexandre Courbot) Date: Mon, 22 Jul 2002 23:21:53 +0200 Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: References: Message-ID: <20020722232153.36089051.alexandrecourbot@linuxgames.com> > [Anders J. Munch] > > Python uses floating point to check for integer arithmetic overflow. > > [Bernhard Herzog] > > Not any more. This change was introduced in 2.1 IIRC. > > This is complicated. First, scratch "integer arithmetic overflow", > because it's too broad. Only integer multiplication is relevant here. > > Python used to use float arithmetic to detect int mult overflow, but > that didn't work correctly on some 64-bit boxes. > > It got replaced by over 100(!) lines of all-integer int mult > overflow-checking code, and I believe that's still in 2.1.3. > > But that had an obscure endcase bug too, and it get replaced in 2.2 by > a new float method that doesn't make unwarranted assumptions about the > relative sizes of C longs and C doubles, and usually gets out quickly > -- provided float arithmetic isn't pig slow. Oh. Maybe it'd be worth to do some profiling there. I'll try to compile it again for the Zaurus with profiling information to see where it exactly slows down. Thanks to everybody for the many answers! :) Alex. -- http://www.gnurou.org From jromero at platea.pntic.mec.es Mon Jul 15 21:57:28 2002 From: jromero at platea.pntic.mec.es (Joaquin Romero) Date: Tue, 16 Jul 2002 03:57:28 +0200 Subject: maaxlength in Entry() / Tkinter References: Message-ID: Thanks! From amutch at tln.lib.mi.us Wed Jul 31 22:10:15 2002 From: amutch at tln.lib.mi.us (Andrew Mutch) Date: 31 Jul 2002 19:10:15 -0700 Subject: mozilla wrapper for python ? References: Message-ID: Not sure how this relates to Python but K-Meleon is not dead. We are actively developing. The news on the front page is a bit misleading. http://sourceforge.net/projects/kmeleon/ Andrew Mutch "Clark C . Evans" wrote in message news:... > Hello. I was wondering if anyone is actively working or has > developed a python wrapper for mozilla, preferably with wxpython? > I see a few "related" projects that appear to be abandoned: > > - http://sourceforge.net/projects/pygecko/ > - http://sourceforge.net/projects/wxmozilla/ > - http://sourceforge.net/projects/pyleon/ > - http://sourceforge.net/projects/kmeleon/ > > To related projects which appear to be active: > > - http://aspn.activestate.com/ASPN/Downloads/Komodo/PyXPCOM/ > - http://www.iol.ie/~locka/mozilla/mozilla.htm > > Thanks, > > Clark From tdelaney at avaya.com Tue Jul 9 20:44:12 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 10 Jul 2002 10:44:12 +1000 Subject: Converting a hex string to a number Message-ID: > From: Matt Gerrans [mailto:matt_gerrans at hp.com] > > Anyway, that's assuming you have no control over the input; > if that is the > case, you could filter it easily enough: > > if re.match(r'0x(\d|[a-f])*', string, re.I ): > n = eval(string) > else: > n = 0 # Could alternatively raise a ValueError, or > something like that, > here. > > You could change this to allow for decimal input, etc., while > still not > inviting a nefarious chunk of code. I'm really hoping there's a missing smiley here ... How the hell is the above better in any way shape or form than: # assumes s is a string of form 12345 i.e. any 0x has been trimmed from the start n = long(s, 16) ??? Tim Delaney From lcullip at techie.com Fri Jul 26 05:58:06 2002 From: lcullip at techie.com (Lee Cullip) Date: Fri, 26 Jul 2002 10:58:06 +0100 Subject: What am I doing wrong ? Message-ID: <007c01c2348a$f1976fc0$7c24f80a@PC10821> Hi all, I'm really new to Python programming, only been tinkering with it a couple of days. I started writing this program and can't quite work out what I'm doing wrong. I want the user to enter the details in the dialog box and then when they hit execute it runs the telnet stuff and writes the output back to a file. I'm obviously doing something really stupid and need some help. Any pointers would be great. Cheers Lee My code : import telnetlib import sys import Tkinter from Tkinter import * def detail() : telnet = telnetlib.Telnet(HOST) telnet.read_until("login: ") telnet.write(USER + "\n") telnet.read_until("Password: ") telnet.write(PASSWORD + "\n") telnet.write("ls -l /etc/init.d/oracle.sh\n") telnet.write("ls -l /etc/rc3.d|grep orac\n") telnet.write("cat /etc/oratab\n") telnet.write("exit\n") info = telnet.read_all() file = open('c:/temp/listing.txt', 'w') #write info to file file.writelines(info) file.close() login = Tk() Label(login, text="User Name:").grid(row=0, sticky=W) Label(login, text="Password:").grid(row=1, sticky=W) Label(login, text="Host:").grid(row=2, sticky=W) entry_ln = Entry(login) entry_fn = Entry(login) entry_ph = Entry(login) USER = entry_ln.grid(row=0, column=1) PASSWORD = entry_fn.grid(row=1, column=1) HOST = entry_ph.grid(row=2, column=1) b_execute = Button(login) b_execute['text'] = "Execute" b_execute['command'] = detail b_execute.pack() b_execute.grid(row=7, column = 1) login.mainloop() The errors I'm getting: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "C:\python scripts\teltest.py", line 9, in detail telnet.read_until("login: ") File "C:\Python22\lib\telnetlib.py", line 294, in read_until while not self.eof and apply(select.select, s_args) == s_reply: File "C:\Python22\lib\telnetlib.py", line 260, in fileno return self.sock.fileno() AttributeError: 'NoneType' object has no attribute 'fileno' Process terminated with exit code 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dutoitc at hotmail.com Sun Jul 14 12:37:45 2002 From: dutoitc at hotmail.com (Cedric Dutoit) Date: Sun, 14 Jul 2002 18:37:45 +0200 Subject: ANN : PyUt 1.1 - UML editor with roundtrip Message-ID: PyUt 1.1 is available at http://pyut.sf.net PyUt 1.1 ======== - is a little UML 1.3 editor which support class diagram and use-cases. - is written in Python - is GPL, free - works under Linux, Unix, Windows (the linux and unix version is a rpm which need wxPython-http://www.wxpython.org; a Macintosh version of wxPython is under construction) Functionalities : =============== - Class diagram - Use-cases - Export to bmp, jpg, ps - REVERSE-ENGINEERING java, python - CODE GENERATION java, python, C++ - XMI import (compatibility with Rational Rose - i18n (French-English) - Plugins support (python) Links ===== PyUt's website : http://pyut.sf.net Direct download : http://sourceforge.net/project/showfiles.php?group_id=39548 For PyUt's team, C.Dutoit - dutoitc at hotmail.com PyUt's team is composed of 6 students at EIVD - Ecole d'ing?nieurs du Nord Vaudois, Suisse (www.eivd.ch) (~Computer high school) This project is active and will continue ! From mcfletch at rogers.com Wed Jul 3 13:47:45 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 03 Jul 2002 13:47:45 -0400 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> <3D229458.719D4A7B@vip.fi> Message-ID: <3D2338C1.1070804@rogers.com> Pekka Niiranen wrote: > Please make also example of recursive decent parser, for example LL(k) > > -pekka- ... Hmm, it would seem a bit out-of-scope to create an example of a hand-coded recursive descent parser for a parser-generator system. After all, the idea is to _avoid_ writing your own recursive descent parsers as much as possible :) ;) . As for LL(k), I've never been able to determine what the grammar classification of SimpleParse grammars is. The algorithm doesn't seem to match closely enough with the standard parsing algos (which all seem to be tokeniser based). If you were to just lex the file with your generated grammar, then your post-processing functions could use whatever algo they wanted (even Earley (sp?)), but then you would lose much of the speed of the C engine, so you'd likely want something where you match all non-ambiguous grammar constructs with the generated system, and use Earley (or whatever) for the ambiguous or more context-sensitive stuff. That said, I normally let the C engine do all the parsing, but I deal with simple, data-format-style grammars most of the time. Of course, if someone with a yen for traditional parsers wanted to, they could write a parser-generator of their own to fit into the system in a few hours. They'd basically just create a new objectgenerator.py for their system, a Parser-sub-class to do the transformation from ebnf to their new generators (such as seen in simpleparsegrammar.py) and create their own sub-class of the "Parser" class to use that grammar by default. Aside: I'm wanting look at SPARK's code after the 2.0 release of SimpleParse and see what would be necessary to auto-generate SPARK parsers from EBNFs (then see about making it an optional generation option for SimpleParse). Anyone who wanted to beat me to the punch would be welcome :) . Anyway, to work, to work, it's off to work I go... Enjoy, Mike From b.maryniuk at forbis.lt Tue Jul 9 03:44:28 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 09:44:28 +0200 Subject: Why self? In-Reply-To: <000d01c226b5$8c68f520$bd5d4540@Dell2> References: <000d01c226b5$8c68f520$bd5d4540@Dell2> Message-ID: <200207090944.28597.b.maryniuk@forbis.lt> On Monday 08 July 2002 21:27, Brian Quinlan wrote: > Two leading underscores make the instance variable private. And only for this... Actually they are not private as they should be. :) -----------------8<----------------- class stuff: def __init__(self): self.bar = 'bar' self.__baz = 'baz' __spam = 'spam' stf = stuff() print stf.bar print stf._stuff__baz print dir(stf) -----------------8<----------------- Prints this: -----------------8<----------------- bar baz ['_stuff__baz', 'bar'] -----------------8<----------------- May be it is possible to access even __spam variable somehow... > Python forces you to be explicit. That way we will know what you are > doing, right or wrong. That what I love Python -- C/C++ is very "buggy". :) -- Sincerely yours, Bogdan M. Maryniuck "Linux poses a real challenge for those with a taste for late-night hacking (and/or conversations with God)." (By Matt Welsh) From martin at v.loewis.de Tue Jul 30 14:08:49 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 20:08:49 +0200 Subject: Unicode classes of characters in Pythons' re's like in Perl? References: Message-ID: Roman Suzi writes: > Probably, there should be pre-compiled categories somewhere in > the standard library... Say, in RE module. Feel free to submit a patch to sourceforge. A decision on that will be made by Fredrik Lundh, so you may want to contact him in advance. Regards, Martin From phil at river-bank.demon.co.uk Wed Jul 24 09:20:50 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Wed, 24 Jul 2002 14:20:50 +0100 Subject: GUI toolkits References: <3d3e8e2e_4@news.newsgroups.com> <6BD35F86024903BE.21C9C2AF4CD75C43.49FE3231C518DCC1@lp.airnews.net> Message-ID: <3D3EA9B2.5060402@river-bank.demon.co.uk> Stefano Vedovelli wrote: > Hello all > > well, thanks for the feedbacks. > > In general I am more confident with PyQT, as there is good documentation > available, as I can also read the C/C++ documents, for instance > "Programming With Qt" from O'Reilly, which I bought. And before Boudewijn jumps in, don't forget "GUI Programming with Python: Qt Edition" at http://www.opendocspublishing.com/pyqt/. Phil From milos.prudek at tiscali.cz Fri Jul 26 05:56:45 2002 From: milos.prudek at tiscali.cz (Milos Prudek) Date: Fri, 26 Jul 2002 11:56:45 +0200 Subject: Rating a developer Message-ID: <3D411CDD.7010308@tiscali.cz> Hi, This should be fun: I would like to know how I rate as a Python developer. I think I'm a poor developer, so you can't hurt my feelings! Attached is a small program that I created. The task that it should solve is described below. THE TASK: Technical translators often translate texts with repetitive phrases. This program must scan a plain text file word by word and find repeated words. Then it must scan the same file letter by letter and find repeated phrases and repeated parts of words. COMMENTS: My solution is very slow. It is all I could create within 8 hours. I could optimize it more, but it would take considerably more time, given my IQ. 1. Rate me as a developer on a scale of 9 to 1, where 9 is "a genius I would die to hire", 5 is "an average guy, could be hired for grunt work", 1 is "not skilled enough to be a developer". 2. Estimate pay rate I could earn (hourly, daily, or monthly). Consider that the attached program took me 8 hours to create and debug. -- Milos Prudek -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: amacro.py URL: From aleax at aleax.it Tue Jul 16 04:54:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 16 Jul 2002 08:54:55 GMT Subject: namespaces in python References: Message-ID: Jeff Davis wrote: > Is there a way to put functions and variables in a different namespace > without putting it in a seperate file or instantiating a new object? Is Yes, class scope being an example. > there a way to have static methods that don't require instantiating the > object first? class Namespace(object): def afunction(): print 'here' afunction = staticmethod(afunction) Namespace.afunction() > I just want a clean way to divide up my modules a bit without cluttering > up the filesystem (or requiring seperate i/o operations to fetch several > files). "import-from-zipfile" is another interesting possibility, but it's not part of standard Python right now -- still, you can install it, see e.g. http://www.mcmillan-inc.com/iu.html Alex From aleax at aleax.it Wed Jul 17 04:15:04 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 17 Jul 2002 08:15:04 GMT Subject: gettext i18n References: Message-ID: Syver Enstad wrote: > Are there any tutorials on this around? I read the i18n chapter in the > python documentation but it doesn't say much about what to do with the > files that pygettext and msgfmt generates. I once posted a small walked-through example, see: http://groups.google.com/groups?selm=9fkubv0i48%40enews2.newsguy.com Some readers found it helped them get started. Alex From whisper at oz.net Fri Jul 26 17:38:31 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Jul 2002 14:38:31 -0700 Subject: ?Module re documentation bug, error, or misunderstanding? In-Reply-To: <3D41B265.AD56FF90@email.sps.mot.com> Message-ID: > So, what am I missing below as both searches "should" succeed? > > % python2.1 > Python 2.1 (#2, Apr 24 2001, 11:33:06) > [GCC 2.95.3 20010315 (release)] on hp-uxB > Type "copyright", "credits" or "license" for more information. > >>> import re > >>> re.search("(.+) \1", '55 55') > >>> > >>> re.search("(.+) (.+)", '55 55') > Your quantifiers are greedy, so the first + matches the whole string. "\1" is "55 55", not the "55" you expect. Try it with a non-greedy quantifier: +? -> r"(.+?) \1" or r"(.+?) (.+?)". (BTW, it's a good habbit to always make re strings raw: r"".) Of course, this might not work either - it's asking a lot to want an "any character" specifier with a "one or more" quantifier to magically decide that it should stop on a space. I think I've gotten this to work by using \s (or \s*) in preference to a litteral space following a .* or .+ match element. David LeBlanc Seattle, WA USA From maxm at mxm.dk Wed Jul 3 09:37:06 2002 From: maxm at mxm.dk (Max M) Date: Wed, 03 Jul 2002 15:37:06 +0200 Subject: what's up with 'patterns'? References: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> <3D22F5FF.9070408@mxm.dk> <3d22fb61$0$235$4d4ebb8e@news.nl.uu.net> Message-ID: <3D22FE02.6050106@mxm.dk> Guyon Mor?e wrote: > is this something i should really look into or is it something that only is > usefull when i am designing large systems and such? You should definetively look into it, but only if you have allready written some applications with objects. The leap from functional to patterns is probably to big. But if you have done some apps with objects it might be a valuable experience rewriting one, or part of it with the "Programming Patterns" book in one hand. regards Max M From emile at fenx.com Mon Jul 1 12:06:49 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 01 Jul 2002 16:06:49 GMT Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: Steve Holden > There did used to be a MoinMoin-based Wiki somewhere under www.python.org, > but a recent (i.e. 3 mionutes ago) search of the site failed to find it, and > it certainly wasn't used whewn it was there (I recall my own last posting > being along the lines of "This isn't a very useful Wiki if nobody knows > about it and nobody tries to keep it up to date". > > I'm sure a Wiki *could* be very useful. > I'm sure it will be done sooner or later, but do you think it would be more useful than a good posting guidelines that's put out every few weeks and google? ISTM that there's already enough SIGs, lists, irc's, etc that can't be followed... http://groups.google.com/advanced_group_search?as_ugroup=comp.lang.pytho n -- Emile van Sebille emile at fenx.com --------- From claxtonr at beer.com Thu Jul 18 20:16:19 2002 From: claxtonr at beer.com (hejduk) Date: 18 Jul 2002 17:16:19 -0700 Subject: starting other programs from within python References: <20020716.171155.619290071.333@beer.com> <3D349AA0.1AE34452@engcorp.com> <20020717.123645.824272813.337@beer.com> Message-ID: > > If your goal is simply to execute applications from a menu, threads seem > like overkill to me. I'd simply use the usual fork/exec methods. In > Python, these are in the os module along with the spawn methods you refer > to. > > --frank i thought that fork/exec involved a lot more overhead in terms of cpu usage and memory? From sandysj at juno.com Wed Jul 17 12:53:35 2002 From: sandysj at juno.com (Jeff Sandys) Date: Wed, 17 Jul 2002 16:53:35 GMT Subject: Calling Python from Allegro Lisp References: <3D2EC4B5.1070605@thomas-guettler.de> Message-ID: <3D35A10F.93A01B0E@juno.com> Thomas Guettler wrote: > > I have an old application which needs to call python. > The old app is written in allegro lisp. > This is how I call Python programs from Lisp in Unix. The short (two line) test Python program (ltest.py) is: #!/bin/usr/env python print "Hello World" In Lisp I call the program with run-shell-command: LISP(2): (setq lout (excl:run-shell-command "ltest.py" :output :stream :wait nil)) # LISP(3): (read-line lout) "Hello World" NIL With Windows you will probably need to use "python ltest.py" as the run-shell-command. Thanks, Jeff Sandys From mnations at airmail.net Wed Jul 24 11:25:18 2002 From: mnations at airmail.net (Marc) Date: 24 Jul 2002 08:25:18 -0700 Subject: Need a better way to pause a thread References: <4378fa6f.0207231456.3057babe@posting.google.com> Message-ID: <4378fa6f.0207240725.2e589b1e@posting.google.com> Thanks Chris, and you hit upon something I've been wondering about for a while. I've used queues before to do simple things like strings and variables when I simple wanted to display or use something. But when I tried to do whole commands, it got klunky. The only way I had found to do it was putting the commands in a string and using eval() on the command on the other side. This was too painful to use in large applications. However you did it the following way: > #now you can feed your thread with work: > q.put( (time.sleep, 1) ) > q.put( (sys.stdout.write, "Hello its the thread speaking up") ) Basically it appears the format is the command placed in nested () with things that would be passed thru as parameters being delimited by commas. Is this a general format that will work for all commands, or is there a place I can check the format? There are several examples of queues I've found but none showing all the ways you can pass commands through. Marc From sholden at holdenweb.com Tue Jul 2 08:42:52 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 2 Jul 2002 08:42:52 -0400 Subject: Simple Conceptual Pickling problems References: <3d217732$0$4276$afc38c87@news.easynet.co.uk> <3d2194c1$0$4280$afc38c87@news.easynet.co.uk> Message-ID: "chris lyon" wrote ... > > > > SystemError: Failed to import class Programme from module __main__ > > > > This is the hint. The module's name when the pickle was created was > > __main__, which only happens when the module is not imported, but is run > > directly. You need to pickle and unpickle from within the same context, > > eg, use import in both cases. > > > > HTH, > > > Emile van Sebille > > emile at fenx.com > > So , if I understand you, Because I ran the original code using the > Pythonwin environment, I produced the objects in module __main__ NOT in the > module I though they were being created in ( in my case a module called > octavia which contains the class Programmes). > > When I then ran with my test module, which imported octavia, The Unpickle > process believed it was trying to unpickle objects defined in __main__ NOT > from within octavia ? > > So should I then have a module 'above' my octavia module which will import > octavia for it to work? > Correct. The unpickling will, if you let it, immport the module in which the classes of the unpickled objects were defined. This means that they must be recognisably from their defining module when you pickle them. As long as the program that writes the pickle imports octavia you should be good to go. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From pde at cs.mu.oz.au Mon Jul 1 02:01:24 2002 From: pde at cs.mu.oz.au (Peter Eckersley) Date: Mon, 1 Jul 2002 16:01:24 +1000 Subject: Partial Parsing of Python In-Reply-To: <20020630094833.B20310@prim.han.de> References: <20020629141507.GA6507@luminance.reworld.org> <20020630094833.B20310@prim.han.de> Message-ID: <20020701060124.GA9937@luminance.reworld.org> On Sun, Jun 30, 2002 at 09:48:33AM +0200, holger krekel wrote: > That's great! I can offer you code which will help you. > Moreover some of us had good discussions at EuroPython about *exactly* > this type of project. For a start look at my alpha-version of a new > command line completer: > > http://home.trillke.net/~hpk/rlcompleter2.py > > Michael Hudson moreover has done nice work with replacing readline > with curses. > > http://starship.python.net/crew/mwh/hacks/pyrepl.html Excellent. Thanks for the pointers.... > > Actually the problem goes deeper. Have a look at my TryParser class > in rlcompleter2.py for a start. It does handle many cases and should > give you some more ideas :-) Agreed. Although pyrepl seems about on par with what I'd tried, TryParser seems to handle lots of trickier cases. > > Actually the REAL problem to solve first is to have Multi-Line editing. > Then all sorts of partial parsers *and* partial evaluation. Python is > just too damn dynamic to have that one easily. > Oh, which reminds me of something else. I also have problems with side-effects ("heisenberg" effects)-- it will be necessary to get rid of these. My feeling was that this could be done using purity analysis and return-type annotation. Many of the important cases can be handled by just adding information about the builtin modules, but it might also be possible to do generalised python purity analysis. Has anyone tried this? > So what to do? Our idea at EuroPython was to use PyGame (the wrapper > around SDL) to get rid of the uglyness and restrictiveness of > readline and curses alltogether. We want to have a REAL playground > and concentrate on our ideas. Hmmm, I agree that one needs to escape readline/curses - but SDL sounds like overkill, since I imagine you'll have to re-implement lots of basic widgets on top of it. I picked GTK, and have found it generally suitable, despite a few quirks. Having said that, there are still some issues I need to resolve, so I shouldn't start counting chickens... A copy of my (pre-pre-alpha) code is available at http://www.cs.mu.oz.au/~pde/src/gush-0.003.tgz (it's currently called gush - the Grand Unified SHell - although I think somebody might have already used that name), so you can see how GTK works for this. All completions except obj.attr are currently turned off. In order to run it, you'll need the latest version of pygtk (1.99.10 or later), from ftp://ftp.gtk.org/pub/gtk/python/v2.0/ . I haven't dealt with multi-line editing yet, but GTK should certainly keep this simple (just replace the GtkEntry for the command with a GtkTextView). I've been using up/down cursors to cycle through completions, but they should really be used for the history, so adding multi-line editing will make them triply-overloaded :) > > Once i slow down from the mind-blowing EuroPython discussions and talks > i check how easy that is. > > Drop me a note if you are interested to stay tuned. > Definitely... -- Peter Eckersley Department of Computer Science & mailto:pde at cs.mu.oz.au IP Research Institute of Australia http://www.cs.mu.oz.au/~pde The University of Melbourne From eugene1977 at hotmail.com Sat Jul 20 18:31:40 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sat, 20 Jul 2002 17:31:40 -0500 Subject: can i make a p2p application in python? Message-ID: like kazaa or napster.. is it possible? thank you From brueckd at tbye.com Fri Jul 19 16:48:53 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 19 Jul 2002 13:48:53 -0700 (PDT) Subject: A better self In-Reply-To: <3D385A46.6DC47857@astro.cornell.edu> Message-ID: On Fri, 19 Jul 2002, Tom Loredo wrote: > > t, x, y, z=self.t, self.x, self.y, self.z > > result=sin(t)*x**y+sqrt(z) # A pretend formula [snip] > to return various quantities. In a language that boasts of how > simple and straightforward it is, and how it shrinks code size (by > omitting braces, declarations, etc.), [snip] The 'boasts' of course apply in the general sense, and in the general sense they are very true. From your perspective this is quite a nuisance because the combination of the types of programs you write and your design style make you encounter this problem often. >From your posts it sounds like you're trying to remain pretty positive about this nuisance (good job!), but I hope you also realize that for a lot of people writing a lot of programs there is no 'problem' - from my perspective I hope that this whole 'self' thing never changes at all. > in every one of many member functions, often with the same variables. > You look at that code, with all those redundant lines of negligible > content, and it yells out to you: something is missing here that > should make this silly copying unnecessary in order to have expressions > that are easy to read/understand. Hehe... well, changing the language is of course only one of your options, and probably the least likely to ever pan out, especially for the aforementioned reason that lots of people and lots of code already use and/or like the other way. Every time this topic comes up I'm surprised at how desperately some people want the language changed (not necessarily you, since you've already said that it's not enough of a nuisance to abandon Python), and I'm equally surprised that no combination of the following alternatives are acceptable: 1) Learn to like it - I've spent more time reading about getting rid of self than time actually typing 'self.' (i.e. the costs are minimal and it makes my code more readable and explicit - it's worth it to me!) 2) Learn to just accept it (perhaps you find it annoying, but at least it's not something you deal with on every line of code) 3) Use the smarts of your editor - macros, special syntax highlighting, etc. 4) Use a shorter name than self, e.g. 's' 5) Use the x,y,z = self.x, self.y, self.z idiom 6) Have Python generate the function bodies for you, e.g: class SomeClass: method = MyCoolUnboundMethodMaker('arg:x = y*z + t*arg') 7) Change your design - if something is awkward it *may* be a flaw in the language, but there's also a really, really good chance that a different approach to your program would be best. > The language is so great in other respects, and on a fundamental level > the arguments for "self." are so sound, that I just live with this. Fundamental, *and* practical, IMO. -Dave From akakakhel at attbi.com Fri Jul 26 23:14:18 2002 From: akakakhel at attbi.com (Ali K) Date: Sat, 27 Jul 2002 03:14:18 GMT Subject: Image Loading Message-ID: How do you load a picture inside a frame? Please Reply! Thank You! From rahvee at yaahhoo.com Tue Jul 2 19:39:22 2002 From: rahvee at yaahhoo.com (rahvee at yaahhoo.com) Date: Tue, 2 Jul 2002 19:39:22 -0400 Subject: help using (x)inetd Message-ID: I have xinetd accepting a tcp connection on some port, and spawning a process that I wrote. The process wants to have a conversation. It can take input, it can make output, but when it prints some output, that output gets buffered by xinetd, and it is never received by the client until the process closes. My process is written in python. How can I signal inetd to flush the buffer? Thank you. From opus at value.net Thu Jul 4 04:14:21 2002 From: opus at value.net (Opus) Date: Thu, 4 Jul 2002 01:14:21 -0700 Subject: Using .UDL files with Python Message-ID: <3D23A16D.22930.783E2F4@localhost> Is there anything for Python that allows the usage of a .UDL to describe the connection to a database? I'm writing a program that uses a database (right now MySQL), and I want to be able to make it as generic as possible. It seems that the .UDL files give the user/admin person a nice GUI for setting up this data. Is there anything out there for Python to parse that file type? Or would the ConfigurationParser be the best bet? Thanks. --Opus-- Priests have no hats, Cardinals have those little red beanies, the Pope has a collection of big hats...God must have a huge frigging Sombrero up there in heaven. - Unknown -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From rob Sat Jul 6 11:26:19 2002 From: rob (Rob Andrews) Date: Sat, 06 Jul 2002 15:26:19 GMT Subject: first experiences with Python References: <2259b0e2.0207060253.1723a696@posting.google.com> Message-ID: Your story reminds me a lot of my own. I even recall thinking the documentation could be a little better when I first started, although I did wind up changing my mind after I thought about it some more. Fortunately, there are also plenty of Python resources out there, such as the Python Tutor email list, comp.lang.python (which is newbie-friendly in the extreme by usenet standards), three not-insignificant source code collections that I can think of off the top of my head, and there are an amazing number of tutorials on the web written by people who just love the language. Python's also a great way to get started in programming in a meaningful way. I'm in a summer-long intensive introduction to C++ (covering 9 months of computer science in about 8 weeks), and we're about half-way through. Thanks to Python helping me to understand the basics of what's happening during the software development process, I've been holding down a perfect score so far. And I sometimes show people in the class how to do something in Python that we just did in C++, which seems to impress them more than a little. Python's fun, and it gets the job done! It's a language so good that I feel I can be a Python zealot without having to insult other languages to get my point across. Rob http://uselesspython.com mis6 at pitt.edu (Michele Simionato) wrote in news:2259b0e2.0207060253.1723a696 at posting.google.com: > I became aware of the existence of Python a couple of months ago. > The reason was an exceptional wave of heat in Pittsburgh, my problem > the conversion from Fahrenheits to Celsius (I recently moved from > Europe to the States and I hate Fahrenheits !). From correia_j at hotmail.com Wed Jul 10 11:58:47 2002 From: correia_j at hotmail.com (Jose Correia) Date: Wed, 10 Jul 2002 15:58:47 GMT Subject: win32com and internet explorer References: <3d235b64$1@post.usenet.com> <6vZU8.409778$cQ3.28013@sccrnsc01> Message-ID: Hi, You're very close. > doc = ie.Document > doc.forms(0).uf.value = "username" #from name = "uf" refer HTML above > time.sleep(1) > doc.tcforms.gf.value = "Password" #from name = "gf" refer HTML ^^^^^^^ This is wrong. This line should read: doc.forms(0).gf.value = "Password" Both the uf and gf fields are on the same unnamed form (form 0) I tried the above on my side and it works. (Don't forget the submit() ) TIP: If you set ie.Visible=1 you can toggle to the browser and watch the text being entered into the fields by your program. (set your sleep between commands to 5 seconds, say, and watch the browser window). This is great for debugging and initial experimentation. > P.S , what does HTH mean? HTH = Hope That Helps. :-) > Also, the links to MSDN give me 404 error... Unfortunately the message breaks the URL into 2 lines due to the length of the URL so you can't just click on it. Cut and paste the first line into the browser, then cut and paste the 2nd line onto the end of it, then try nav to it. Make sure there is no line-feed character between the pastes. Both links work on my side. Here they are again: Link 1 (both lines): http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/ reference/objects/obj_document.asp Link 2 (both lines): http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/ webbrowser/reference/ifaces/IWebBrowser2/IWebBrowser2.asp HTH, :-) Jose From phr-n2002b at NOSPAMnightsong.com Mon Jul 1 12:37:05 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 01 Jul 2002 09:37:05 -0700 Subject: I'd give up Perl tomorrow if only... References: Message-ID: <7xadpbl80e.fsf@ruckus.brouhaha.com> brueckd at tbye.com writes: > Just to chime in - Aahz hit the nail on the head here... for whatever > reason, *not* having a CPAN thingy just isn't that painful right now. > Maybe someday it will be, and when that time comes we'll build one, but > among long-time Pythonistas there just aren't that many people who are > clamoring for it, including those who were long-time Perl folk in a > previous life. I think it's not so painful now because there isn't as much Python code around as Perl code, so there isn't as much need for a CPAN-like thing to keep it organized. I don't know if it's just a matter of time for more libraries to be developed or if it's somehow inherent in the Python language and implementation that not as much seems to get done with it. Most likely it's a combination of both. From cliechti at gmx.net Sat Jul 27 09:55:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Jul 2002 15:55:11 +0200 Subject: Python script that writes to an Excel file References: <67f6bbe5.0207270544.696f6076@posting.google.com> Message-ID: keilj_33 at yahoo.com (Jeffrey Keil) wrote in news:67f6bbe5.0207270544.696f6076 at posting.google.com: > Greetings: > > I'd like to have a Python script open a text file, process the data in > the text file and then write a report to an Excel file. I'm not sure > how I would write to an Excel file from a Python script. Is there any > books that would give me details on doing this? you could use COM. but i think its simpler to write the output to a text file again. use tabs to separate columns and name it .csv - excel will autodetect the format and load it correctly. chris -- Chris From ods at fep.ru Fri Jul 12 11:19:33 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Fri, 12 Jul 2002 19:19:33 +0400 (MSD) Subject: XPM In-Reply-To: <3D2EEF90.60408@xontech.com> Message-ID: On Fri, 12 Jul 2002, Chad Pettit wrote: CP> Does Python 2.2 support XPM image formats? CP> CP> If so, how can I load an existing xpm image independent of CP> the current CP> working directory? (Import like functionality) Look at PIL (http://www.pythonware.com/products/pil/), supported formats are listed at http://www.pythonware.com/library/pil/handbook/image-file-formats.htm -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From karaatanasov at hotmail.com Fri Jul 19 07:18:53 2002 From: karaatanasov at hotmail.com (Kiril Karaatanasov) Date: 19 Jul 2002 04:18:53 -0700 Subject: regex substitution question References: Message-ID: <71a1c515.0207190318.3f5e3dc3@posting.google.com> > but the last "44444" would never get substituted. What would be the easiest > way to accomplish this? Change the RE from 'x([^x]*)x[^x]*x' to 'x([^x]*)x' Simply you do not seem to have another sequence after 44444 that is why it does nt work :) From wdraxinger at darkstargames.de Fri Jul 12 18:33:41 2002 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sat, 13 Jul 2002 00:33:41 +0200 Subject: prevent loading of specific modules Message-ID: <3D2F5945.7050200@darkstargames.de> Say I've several different interpreters, and I want to prevent them to load specific modules, maybe because another loaded module conflicts with it. How can I do this? E.g. I wrote a small extension module, say "spam" in it's void init_spam(void) { Py_InitModule("spam", spam_methods); /*do something, that "eggs" cannot be loaded*/ } I want to prevent python to load "eggs", on a low level C basis, something like a hook on PyImport_ImportModule() or something else. My first idea was to override sys.import with a custom function, e.g. spam.import that calls PyImport_ImportModule(). However if the script does a del sys import sys reload(sys) my override is lost, and thus spam could conflict with eggs if both loaded. A similair problem is, that I override e.g. sys.stdout with my own stuff, but this is lost when something like above is done. How can I prevent this? -- +------------------------------------------------+ | +----------------+ WOLFGANG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From fperez528 at yahoo.com Sun Jul 21 15:36:24 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 21 Jul 2002 13:36:24 -0600 Subject: Renting CPU time for a Python script References: <25c15ddd.0207190852.2aecc26c@posting.google.com> <698f09f8.0207192212.76272194@posting.google.com> Message-ID: <3D3B0D38.4010606@yahoo.com> > 1- code in automatic checkpointing and self-restarting abilities. It's fairly >> easy to do, and saves a lot of headaches. > > > Do you know of any examples of this in available code, or could you > outline how you would implement something like that? I have a project > right now that such a capability would come quite useful in, but > rather than hazard my own implementation right off, I'd like to try > and leverage some other efforts. The specifics depend too much on the details of the problem, but the principle is simple. First, you decide how much time you are willing to lose in the event of a crash, balancing the cost of the checkpointing operation with running time (you don't want to checkpoint every 10 minutes if checkpointing itself takes 10 minutes!). For the OP with 5-12 day long runs, I'd guess a checkpoint every 6-12 hours should be enough, and no big deal even if it costs a few minutes to do it. A rule of thumb is that the checkpointing operation shouldn't add more than ~1-2% to your running time. Think of it as the monthly percentage of your income you're willing to spend on insurance. Then you need to identify what data in your code defines the state of the program. Globals, counters, progress markers, etc. Come up with a format to save it and dump it to a file, with a suitable naming convention (typically encoding the input parameters of the run into the filename is a good idea, so that multiple parallel runs with different parameters can all checkpoint into a common directory without clobbering each other). If your code is well designed, this could be as simple as dumping a single object with pickle, or dumping a state object plus a few binary data files. Then your code is written so that: 1- if successful, it deletes the checkpoint file and leaves something like 'checkpoint_filename.success' in its place, a zero-sized file. This way you can know immediately which runs finished correctly. If you want to get fancy, you can run a cgi script which allows you to check over the web the status of your entire run set: for each parameter set identifying a run, a green marks it as successfully finished, yellow as in progress, blue as not started yet and red as crashed. Then you can simply click on the red ones and resubmit them for re-run. 2- at startup, each run looks at the checkpoint directory to make sure there's no .success file (to avoid repeating a run accidentally). Then it looks for a .chkpoint file, and if it finds one that means the same run had been started and crashed partway. At that point it invokes the restarting routine and picks up at the chekcpoint and runs until completion. 3- if desired (I've done this in the past) you can have each run submit the next one in the run stream when finished. This allows you to keep a set of parallel running streams going, using as many machines as you have available but with each machine doing one run at a time. With this kind of scheme you can very easily manage a project which involves hundreds of long-running jobs on a distributed and possibly unreliable network over several months, with minimal fuss. Good luck, f. From smouttebolleke at hotmail.com Sun Jul 7 14:10:22 2002 From: smouttebolleke at hotmail.com (MontrezVosSeins) Date: 7 Jul 2002 11:10:22 -0700 Subject: Why is it crashing? (newbie) References: Message-ID: "Charles Mantha" wrote in message news: > > menu() > menu_choice = int(raw_input("Choose one of the options: ")), > while menu_choice != 3: > if menu_choice == 1: > run_test(get_questions()) maybe this should do it, menu() menu_choice = input("Choose one of the options: ") if menu_choice == 1: run_test(get_questions()) elif menu_choice == 2: ... elif menu_choice == 3: print "Byee" else: print "Whoops, illegal choice, try again." From daniel.dittmar at sap.com Wed Jul 10 09:05:34 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 10 Jul 2002 15:05:34 +0200 Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: Fredrik Lundh wrote: >> maybe we should start here: >> >> http://www.python.org/cgi-bin/moinmoin/Python >> >> and see what happens... > > from what I can tell, nothing happened. > > I'll restore the wiki to it's original "historical" state, when > I find the time. Could you wait a few days more? I didn't follow that link when I searched for it, but used the search function on python.org. And that led me only to the old version. I promise to sketch a topic guide for web development in the next two days. Maybe that gets something started. Daniel From jb at cascade-sys.com Wed Jul 31 06:17:26 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 31 Jul 2002 03:17:26 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitete ch.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <3D475AB5.2060207@nowhere.org> <1028096804.836.1812.camel@lothlorien.colorstudy.net> Message-ID: <3D47B936.1AFA8DB8@cascade-sys.com> Ian Bicking wrote: > > Decades before anyone implemented a programming language, Alonzo Church > > boiled all the control structures down to just one: lambda. Lambda and the Lambda Calculus have nothing to do with "control structures," per se. The lambda notation itself allowed the definition of True and False, predicates and a conditional expression, the value of which is one of two sub expressions based on a governing predicate. Technically, however, there's no 'control,' as everything was evaluated, even the sub expression that was discarded. There is no looping either, only recursive applications of lambda. Conditional expression and recursion have some vague similarities to if/then/else and while, respectively. But in a purely functional language like the Lambda Calculus, it seems a gross distortion to call them 'control structures'. When everything is an expression, there's no "flow" to "control". Lisp actually added "PROG" and other constructs as alternatives to lambda in order to overcome this limitation of pure lambda forms. > And Smalltalk *pretends* to implement something like the lambda calculus > -- but deep down, they had to use the same if statements we all use (for > performance reasons). I don't see why you say "pretends". Smalltalk IMO actually does an excellent job generalizing the notion of Lambda and integrating it with arbitrary sequences of code. Smalltalk's "blocks" are more powerful than Python's Lambda and even Church's Lambda notation. Actually, in function they resemble some of the extensions proposed earlier in this thread, in that they may appear anywhere an expression may be used, they associate a formal argument list with an arbitrary statement sequence, they optionally may be assigned to a variable and they can be evaluated at a later time given an actual arg list. This language design task was simplified by the fact that the executable portion of Smalltalk consists of sequences of message sends (which essentially are expressions). Smalltalk code "block": [ :x :y | sequence of expressions in x and y and others ] The block can be assigned to a name: egBlock := [ :x :y | sequence of expressions in x and y and others ] and then evaluated at a later time: egBlock value: 3 value: 5 Smalltalk's control structures have no pretension whatsoever to be related to lambda (or anything else I've ever seen before). Some examples: count timesRepeat: [ block of code ] [ count <= max ] whileTrue: [ another block ] x < 10 ifTrue: [ true block ] ifFalse: [ false block ] Furthermore, I dare say Smalltalk's choice of these constructs were dictated by the language's universal object/message metaphor, having little or no bearing on performance. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From bh at intevation.de Thu Jul 25 12:03:54 2002 From: bh at intevation.de (Bernhard Herzog) Date: 25 Jul 2002 18:03:54 +0200 Subject: Speed up Python by up to 5% ? References: Message-ID: <6qd6tbbxqt.fsf@abnoba.intevation.de> "Edward K. Ream" writes: > The byte > code is littered with SET_LINENO opcodes. Has anyone considered moving the > test: > > if (things_to_do || --tstate->ticker < 0) > { /* handle periodic things */ } // not usually executed. > > out of the main loop an into the case for SET_LINENO? The code might be > executed slightly less regularly, but would that matter? Yes. When python is started with the -O option there are no SET_LINENO instructions at all. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From dinceraydin at softhome.net Tue Jul 30 14:40:09 2002 From: dinceraydin at softhome.net (Dincer Aydin) Date: 30 Jul 2002 11:40:09 -0700 Subject: ICQ package anywhere ? References: Message-ID: <3112302e.0207301040.4b4a5944@posting.google.com> > I'm actually building a monitoring system that sends mail alerts to > sysadmins. > I'd like to add ICQ messages and didn't find python packages (google, > parnassus, sourceforge) to send alerts to ICQ recipients. Three are two at sourceforge: http://sourceforge.net/projects/pycq/ http://sourceforge.net/projects/py-icq/ I tried both of these once, just for fun. One worked at first attempt (which one I do not remember), the other did not. From aleax at aleax.it Fri Jul 19 07:49:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 19 Jul 2002 11:49:18 GMT Subject: file ops on the fly ? References: Message-ID: <21TZ8.101254$vm5.3505549@news2.tin.it> Shagshag13 wrote: > hello, > > is it possible (and how) to do "on the fly" reading and updating on file ? You can open a file for 'r+b' and then call both read and write on it, moving around with seek and possibly tell. This is hardly ever useful on a text file, though. But I guess much depends on what you mean by "on the fly" in this context -- maybe the simulation of inplace edits for text files offered by standard module fileinput is all you need? Alex From maxm at mxm.dk Mon Jul 15 05:14:01 2002 From: maxm at mxm.dk (Max M) Date: Mon, 15 Jul 2002 11:14:01 +0200 Subject: i come back to python; just some questions References: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> Message-ID: <3D329259.3080908@mxm.dk> Duncan Booth wrote: > ppcdev at hotmail.com (ppcdev) wrote in >>i was working on an old pentium II and wanted to send a very long >>string in the USER parameter but it made my computer bug.. is it >>normal??? >> >>str='a'; r=range(1024); >>for x in r[:]: >> str=str+str >> >>but it even bugs with a value of 512 and 256 for r=range(..) > > You are doubling the length of the string each time, so with a range of > 1024 you are attempting to create a string that is The code should probably be expressed as:: str=''; r=range(1024); for x in r[:]: str = str + 'a' Then you only add one character at a time. This will still create a lot if temporary strings in the process of building up that one string. str = '' str = '' + 'a' # New string assigned to str str = 'a' + 'a' # New string assigned to str str = 'aa' + 'a' # New string assigned to str ... The second to last string will be 1023 characters long. This will give you an execution time that slows down with the square value of r. A better approach is to use a list that you then join in the end. This is _much_ faster. letters=[]; r=range(1024); for x in r[:]: letters.append('a') letterStr = ''.join(letters) regards Max M From aleax at aleax.it Sat Jul 27 04:02:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 08:02:35 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: Carl Banks wrote: ... >>> sort a bunch of strings starting with the second letter: ... > First, this has a pitfall: if x is not sortable for some reason, then ...then x is not a string, therefore the specs ("sort a bunch of strings starting with the second letter", as above quoted) do not apply. Actually, the sort-with-argument solution proposed by the original poster didn't meet the OP's specs: it ONLY sorted on the second letter, giving an unspecified ordering to strings whose second letters are equal -- no "starting with". I read the specs as meaning "as if each string started with its second letter and then continued with the actual string", but one could read them in other ways, e.g., sorting x[1:] (the slice that starts with the second letter). > the "right" way can throw an exception due to lexical ordering of > tuples. I encountered this when trying to sort classes that didn't > have a __cmp__ method. It seems that a better way is to use id(x) as > the second element and x as the third: (x[1], id(x), x) That would go back to unspecified ordering for strings with equal second letters -- hardly sensible behavior. It's just as much (or as little) effort, if you DO want the second letter to be the ONLY (rather than STARTING) sort key, to get a STABLE sort: aux = [ (x[i][1], i) for i in xrange(len(a)) ] aux.sort() a[:] = [ a[i] for __, i in aux ] > Second, if you're going to do it right often, you might want to wrap > it up in a function like this: > > def sort_the_right_way (f, a): > aux = [ (f(x), x) for x in a ] > aux.sort() > a[:] = [ x for __, x in aux ] You can do that, but then you risk 'freezing' in your higher order function a suboptimal way to proceed -- e.g., no way this function can be told to produce stable sorts, while keeping DSU inline it's trivial to ensure the sort is stable. The temptation to overgeneralize often accompanies the decision to freeze some idiom into a higher-order function. Keeping the idiom inline avoids temptations to overgeneralize. Thus, while it does fly in the face of accepted wisdom, in Python sometimes it's wiser to NOT refactor too many idioms and design patterns into ambitious frameworks. It's an observation which Tim also makes in his chapter intro in the Cookbook, by the way -- with Python it's often simpler to code idiomatically than to learn and adopt a framework ambitious enough to cover all needed cases. I would add the comment that developing such frameworks is such child's play in Python, and FUN, that one does it anyway -- even though they may not seem much use afterwards:-). > In which case, the temptation to use lambda returns: > > sort_the_right_way (lambda x:x[1], a) Somebody ambitious enough to encapsulate DSU should surely proceed by encapsulating typical accessors to be used with it in closure factories, e.g. sort_the_right_way(make_items_acessor((1,)), a) thereby avoiding lambda again. It's only when stuff gets wrapped at once too much (by freezing some subset of DSU into a higher order function) AND not enough (by not supplying other higher order functions to go with it by building needed closures) that the _temptation_ of lambda'ing around perks up. Easily avoided by noting that even in that case one more def does it, of course. It takes one more line -- saving lines is probably the core fetish of lambda-enthusiasts, after all. I propose again the hypothesis that such obsession may be linked to traumas in one's childhood... Alex From ulbi at ivs.tu-berlin.de Tue Jul 23 06:04:25 2002 From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich) Date: Tue, 23 Jul 2002 12:04:25 +0200 Subject: Jython: any workaround for the missing array module References: <20f81d64.0207221651.6d57a39@posting.google.com> Message-ID: <3D3D2A29.7000906@ivs.tu-berlin.de> Philip Tsai wrote: > Hello group, > > I learned from Jython's documentation that the Python array module is > currently unsupported. I am writing to see whether you would happen > to know a clean, good workaround? So, instead of "import array" in > the *.py, one can perhaps do something about equally easy and > efficient in Jython.... > > Thanks much! > Philip There is a jarray module. You can use it to build a Java-array and then use everything Java provides to deal with arrays (so it's fairly efficient). But you probably knew this already ... From gleki at gol.ge Wed Jul 3 11:10:59 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Wed, 03 Jul 2002 17:10:59 +0200 Subject: newbie question on Fredrik Lundh's simple script References: Message-ID: <3D231402.81C0E715@gol.ge> Fredrik Lundh wrote: > John Boik wrote: > > > Here is the problem. The frame pops up OK, but when I press the Quit button > > nothing happens. When I press it twice, Python shuts down. > > I assume "Python" means "the IDLE environment" ? > > IDLE executes Python code inside it's own interpreter, and > is also using Tkinter. If you run a program inside IDLE that > shuts Tkinter down, you'll also shut IDLE down. > > That's really IDLE's fault, not Tkinter's... > > I recommend running the samples in a stand-alone Python > interpreter, from the command line. > > (or use an IDE that knows how to run Python programs in > a separate process...) > Would you like to tell me which are such IDEs, and among them, which are freeware? Thank you. Giorgi > > From jb at cascade-sys.com Fri Jul 26 22:09:46 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 26 Jul 2002 19:09:46 -0700 Subject: calendar lameness! References: Message-ID: <3D4200EA.32C7497C@cascade-sys.com> Tim Peters wrote: > [James J. Besemer] > > ... > > And don't get me started on when Easter is. > > That's easy! Sunday. Yeah, but which Sunday? Hint: the Catholic church went to great lengths attempting to define Easter in such a manner that (among other things) it could never occur on the same day as Passover. Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From charles_mantha at hotmail.com Fri Jul 5 22:39:53 2002 From: charles_mantha at hotmail.com (Charles Mantha) Date: Fri, 5 Jul 2002 22:39:53 -0400 Subject: problems with a for loop (noobie) Message-ID: <1IsV8.42194$Fc1.850199@wagner.videotron.net> Reading the Python Tutorial by Guido van Russom and there's an example that I don't get, and seems to not be explained (at least not enought for me). >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 The line < ... if n % x == 0: >, what does the % do? Also I just seem to not get the logic of this program. Would be nice if someone would explain it to me. Thanks Charles Mantha ps : and for some reason, the output is not the same as in the tutorial when I try this. From as at ctes.com Fri Jul 19 18:10:59 2002 From: as at ctes.com (Arneau Starl) Date: Fri, 19 Jul 2002 15:10:59 -0700 Subject: Need some help please Message-ID: <2j2hju8c1btu76tu896cuc9qg6oeep9uoi@4ax.com> I have a stripped down (minimal software on it) ftp server that does have python 2.2 on it.. Here is what I need to do: There is no gui on this redhat machine so I need to have a simple commandline process to add ftp user accounts I could do this by hand but then I would have to make them all , I need be be able to make it easy so another less unix savvy person can create accounts I need to be able to execute a python script (mkacnt) with 2 arguments username and email address. The script does 4 things ("mkacnt name email") 1: create ftp user account with "adduser" 2: create random password 3: execute "passwd username " and then update the password with the one just generated. 4: Email the username and password to the email address supplied above. I have 1 ,2 & 4 working I cannot figure out a way to do the password without Expect (which I cannot install on that machine). Is there a way around this? Arneau From mcherm at destiny.com Wed Jul 24 13:58:09 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 24 Jul 2002 13:58:09 -0400 Subject: How to get the method/function which called a function? Message-ID: <3D3EEAB1.5050307@destiny.com> Try reading http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 and see if that helps. -- Michael Chermside From jadedlime at hotmail.com Tue Jul 30 15:13:05 2002 From: jadedlime at hotmail.com (jadedlime) Date: Tue, 30 Jul 2002 15:13:05 -0400 Subject: comparing strings Message-ID: <3d46e543$1_9@news.teranews.com> Hi, I am very new to Python and very new to programming in general. I need to take a particular string of data and compare it to a dictionary which will put all matching records in a specific file and all the records from the string that do not match in another to be dealt with on an individual basis. I appreciate any and all help on this problem, part of the code is included. this seems to produce the matches, but not the mismatches. import string, re, codecs # create inputs and outputs input = codecs.open("/home/jadedlime/Julio/julio.work", "r", encoding="ISO-8859-1") output = codecs.open("sec_try", "w", encoding="ISO-8859-1") output2 = codecs.open("sec_trynotfound", "w", encoding="ISO-8859-1") # read and split the lines of the main julio records whole = input.read() lines = string.split(whole, "\n") # create the dictionary with regular expressions built in dictionary = {"^aarl australian academic & research libraries$" : "10735", "^acimed$" : "11225", "^adbs: l'association des professionnels de l'information et de la documentation$" : "11715", "^alpha 94. strat\351gies d\222alphab\351tisation et de d\351veloppement culturel en milieu rural\ $" : "12205", "^american archivists$" : "13185", "^anales de documentaci\363n$" : "14165", "^annual review of information science and technology (arist)$" : "14655", "^aproximaciones a la traducci\363n$" : "15145", "^apuntes$" : "15635", "^architectural records conference report$" : "16125", "^archivaria$" : "16615", } # take the desired field (journal titles) and put it in a list format journallist = [] for line in lines: field = string.split(line, '"') journalitems = string.strip(string.lower(field[23])) journallist.append(journalitems) # compile the dictionary and make it into a list format dictionarykeys = dictionary.keys() dictionarylist=[] for dictionaryexp in dictionarykeys: regular = re.compile(dictionaryexp) dictionarylist.append(regular) # run a search that should match all the journal titles in the julio file to the ones in # the dictionary, if they match send them to a specific file, if they do not, send them # to another file so ajustments can be made. for key in dictionarylist: for item in journallist: if re.search(key, item): output.write("found\t" + item + "\n") else: output2.write("not found\t" + item + "\n") From davidw at uq.net.au Sun Jul 28 20:50:26 2002 From: davidw at uq.net.au (David Wright) Date: Mon, 29 Jul 2002 10:50:26 +1000 Subject: turtle module information References: <13285ea2.0207261327.2827b3a6@posting.google.com> <13285ea2.0207272317.39a94189@posting.google.com> Message-ID: "J.Jacob" wrote in message news:13285ea2.0207272317.39a94189 at posting.google.com... > [David Wright] > > Hi, > > Since you have been using turtle.py, could you please tell this newbie how > > to import it into IDLE and start using the turtle commands. Where do the > > graphics appear? > > If you run idle you can type at the ">>>" prompt: > >>> import turtle > >>> turtle.write('David') > Now you will see a separate window popping up with 'David' in it. Cool. It works! Many thanks. DW From martin at v.loewis.de Wed Jul 24 02:15:25 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Jul 2002 08:15:25 +0200 Subject: What unicode character has a certain value? References: Message-ID: Gerhard Haering writes: > > a unicode string to an ascii string (if possible); > > .encode(encoding, conflict_strategy=None) > > for example: u"foobar".encode("utf-16") Of course, if it is really ASCII (American Standard Code for Information Interchange) that is desired, it is always u"foobar".encode("ascii") Regards, Martin From eay at oclearnet.com Mon Jul 15 16:32:19 2002 From: eay at oclearnet.com (Eric Yohanson) Date: Mon, 15 Jul 2002 13:32:19 -0700 Subject: how can I do this? Message-ID: I would like to know if it is possible in python 2.21 to make a text entry widget that initially show nothing but when the user type the first character displays a template like "00#00:01+2" for the previous I have only enter the numbers 1 & 2. the numbers would need to enter from right and travel to the left as more are entered replacing the "0" place holders. How difficult would this be to do and what should my approach be to this. Any help wuld be great. EAY From deathtospam43423 at altavista.com Fri Jul 19 13:38:37 2002 From: deathtospam43423 at altavista.com (netvegetable) Date: 19 Jul 2002 17:38:37 GMT Subject: newby's tut for tkinter? Message-ID: Is there a nice simple tut for newby programmers to learn Tkinter? If not, is there any chance of somebody clever writing one? -- netvegetable at excite.com From Tom_Good1 at excite.com Tue Jul 23 17:28:08 2002 From: Tom_Good1 at excite.com (Tom Good) Date: 23 Jul 2002 14:28:08 -0700 Subject: Make me beautiful (code needs help) References: Message-ID: Mark wrote in message news:... > Ok, I have the following data: > > data["A"] = [1,2,4,10,50] > > and I want to get: > > data["new"] = [?, 1, 2, 6, 40] > Maybe this is close to what you want: from __future__ import generators def processPairs(x, func): for i in range(len(x)-1): yield(func(x[i], x[i+1])) def difference(x, y): return y-x if __name__ == '__main__': test = [1, 2, 4, 10, 50] print [i for i in processPairs(test, difference)] > Now, the other problem, is that in general, I want to fill data["new"] with > an arbitary function of the values in data["A"]. Create any function taking two arguments and call it instead of difference(). Hope this helps. (This code will not put the "?" in as the first element, but you could add that in if it is important.) Tom From b.maryniuk at forbis.lt Mon Jul 8 11:18:10 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 8 Jul 2002 17:18:10 +0200 Subject: Using Python for processing of large datasets (convincing managment) In-Reply-To: <20020708081830.A4427@glacier.arctrix.com> References: <3D27152C.8020108@obscure.dk.X> <3D282290.1050101@ob_scure.dk> <20020708081830.A4427@glacier.arctrix.com> Message-ID: <200207081718.10066.b.maryniuk@forbis.lt> On Monday 08 July 2002 17:18, Neil Schemenauer wrote: > What's wrong with fork()? Certainly resources. Maybe... ;) -- Sincerely yours, Bogdan M. Maryniuck "What you end up with, after running an operating system concept through these many marketing coffee filters, is something not unlike plain hot water." (By Matt Welsh) From mwh at python.net Thu Jul 25 13:29:54 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 25 Jul 2002 17:29:54 GMT Subject: Refer to function name (newbie ques) References: <805bee23.0207250649.5a4d89d0@posting.google.com> <3D401AF0.8090003@shinners.org> Message-ID: Pete Shinners writes: > the traceback module was added sometime around python-2.1 (i think?) > so this won't work with older pythons. docs are here, Older than that, by a long way... [CVS grovelling] ... first checked in in 1994, in time (I think) for version 1.1. Version compatibility *not* a problem here, I think. Cheers, M. -- No. In fact, my eyeballs fell out just from reading this question, so it's a good thing I can touch-type. -- John Baez, sci.physics.research From bhan at andrew.cmu.edu Wed Jul 31 19:59:57 2002 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Wed, 31 Jul 2002 19:59:57 -0400 (EDT) Subject: copy.deepcopy(): is it bug or intended behavior? Message-ID: This is an abstract of the actual code: --- cut here --- import copy class Foo: def clone (self): return copy.deepcopy(self) class Bar (list): pass class Const: def __init__ (self, data): self.data=data def __repr__ (self): return str(self.data) n1=Foo() n1.t=[] c=Bar() c.append(Const('1')) n1.t.append(c) n2=Foo() n2.t=[] c=Bar() c.append(Const('2')) n2.t.append(c) g=Foo() g.hd=[] g.hd.append(n1) g.hd.append(n2) print g.hd[0].t,id(g.hd[0].t) print g.hd[1].t,id(g.hd[1].t) print '----------------------------------------------------------------------' h=g.clone() print h.hd[0].t,id(h.hd[0].t) print h.hd[1].t,id(h.hd[1].t) --- cut here --- Running on Python 2.2.1 gave the following output: [[1]] 135743596 [[2]] 135759124 ---------------------------------------------------------------------- [[1]] 135505252 [[1]] 135793916 But the last line should have "[[2]]...". Am I missing something here? Thanks, Ben From andymac at bullseye.apana.org.au Sat Jul 27 21:06:06 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 28 Jul 2002 12:06:06 +1100 (edt) Subject: Slow program exit on Dec Alpha 4.1 OSF In-Reply-To: Message-ID: On 26 Jul 2002 renez at lightcon.xs4all.nl wrote: {...} > and i run it on part of the repository for 500 files > and it came back with my message (and last statement!) > Done 500 file 485 tags > > Then the program sits for a long time (1 min and more) > before it gives me back the shell prompt. > If i look at ps it says > ... size WCHAN ... > ... 25M nxmbloc ... I think you are running into an odd problem with the behaviour of free() on your OS (FWIW, I've seen similar behaviour on Solaris 2.5.1). It appears some platform free() implementations try to coalesce small blocks when free()ing, for better malloc()/realloc() performance. Python is free()ing lots of small blocks as it shuts down. You could try configuring with PyMalloc (--with-pymalloc option to ./configure) to see whether this helps. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From printers at sendme.cz Wed Jul 31 14:54:41 2002 From: printers at sendme.cz (A) Date: Wed, 31 Jul 2002 20:54:41 +0200 Subject: Problem - how to solve it ? Message-ID: <3D484E91.4394.15F5A3@localhost> Hi, I have a program that I compiled( with Installer) into exe for using on Win32 systems. It works well on Windows Me, Windows 9x but on some computers with Windows 2000 it causes General Protection Error and the programs is finished. It would be nice if the program wrote a line number or something similar that could help a user find out which command caused that General Protection Error. Is there any solution for that? Thank you for help Ladislav From jdhunter at nitace.bsd.uchicago.edu Tue Jul 16 11:08:00 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 16 Jul 2002 10:08:00 -0500 Subject: map del efficiency python2.2 and 2.1 Message-ID: I have a file formatted like word1 int1 word2 int2 with 800,000+ lines like that. I want to load that file into a map m[word] = int and my original implementation was quite slow. So I have been experimenting with the most efficient way to load it and found that the best way was to load the entire file as a string, split it, and then iterate over the sequence with a stride of 2. With this approach I was able to initialize the entire map in 3.5 - 4s (if anyone has any further suggestions, please jump in, but I am reasonably satisfied with this performance). In the process of profiling, however, I found something surprising. Most of the total execution time of the code is spent clearing the map from memory, after all the lines in my script have executed (ie, the equivalent of calling __del__ on a dictionary type. In python 2.1, here is a typical execution time profile time to read file as string and split into seq: 1.000s time to create map: 2.960s total execution time: 9.87s 5.9s of the total runtime occurred *after* all the lines of my code had executed. Since my program does nothing after reading the map, I assume most of this time is spent freeing the map. If I comment out the part of my program that creates the map, I do not have that long delay at the end of the script. Finally, this time is dramatically longer in python 2.2. Here are typical runtimes in 2.2 time to read file as string and split into seq: 0.980s time to create map: 2.650s total execution time: 27.87s These runtimes are highly consistent (the machine isn't doing much else). So 2.2 does about 10% better in filling the map, but then takes 24s to shut down. Here's the script: import time def pairs(l): return [(l[i], l[i+1]) for i in range(0, len(l), 2)] start = time.clock() file = '/home/jdhunter/dict/meta/allwords.dat' fh = open(file, 'r') # this takes 0.97s s = fh.read() seq = s.split() readTime = time.clock()-start print 'seq has %d items; elapsed time is %1.3f' % \ (len(seq), readTime) m = {} #this takes 13.9 s #for (key, val) in pairs(seq): # m[key] = int(val) #this takes 2.9s for i in xrange(0,len(seq),2): m[seq[i]] = int(seq[i+1]) mapTime = time.clock() - readTime print 'map has %d keys; time to load map is %1.3f' % \ (len(m.keys()), mapTime) #cruncher1:~/dict/test> time python2.1 test_allwords.py #seq has 1712676 items; elapsed time is 1.000 #map has 856338 keys; time to load map is 2.960 #4.400u 0.480s 0:09.87 49.4% 0+0k 0+0io 298pf+0w #cruncher1:~/dict/test> time python2.2 test_allwords.py #seq has 1712676 items; elapsed time is 0.980 #map has 856338 keys; time to load map is 2.650 #13.390u 0.500s 0:27.87 49.8% 0+0k 0+0io 350pf+0w John Hunter From mertz at gnosis.cx Thu Jul 4 13:24:38 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 04 Jul 2002 13:24:38 -0400 Subject: [OT] What is Open Source? (fwd) References: <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp> <7x65zv5254.fsf@ruckus.brouhaha.com> Message-ID: |mertz at gnosis.cx (David Mertz, Ph.D.) writes: |> The only problem with this belief is that it is completely, totally, |> 100% wrong. A copyright is, quite simply, a legally enforced artificial |> monopoly--not a contract. These are quite different things. Paul Rubin wrote previously: |I think Clark was using contract in a metaphorical sense, describing a |deal made with authors on one side, and society as a whole on the |other. In what's called the "copyright bargain", society agrees to |grant limited temporary monopolies, in exchange for increased |"progress in science and the useful arts". Well... I suppose Clark's use is a metaphor. But it is an extremely *bad* metaphor, one that does far more to conceal what's going on than reveal. Here's a better one: Copyright is like blue cheese. (OK, I guess you can say it's a simile, since it uses 'like'). I admit this isn't a very -good- metaphor (but both are, indeed, smelly and created by molds :-)... but I *like* blue cheese, so there's a flaw... well, maybe not, since both are bad for me). The problem with Clark's metaphor is that it very strongly insinuates something exactly opposite to the true legal/ethical structure. By pretending that you "contract" for "intellectual property", you create the illusion that IP is something inherently in your possession. I can actually hold my bushel of corn, and as long as I hold it someone else can't. By pretending IP has the same nature, one falsely naturalizes--us Lukacsian's say "reify"--the "thing" that one "has." If you want a metaphor that is actually good, use the one I did in my last post. The government's prohibition on copying words (absent an elaborate system of authorization) is VERY similar to the government's prohibition on individual's possessing drugs (absent an elaborate system of authorization; i.e. medical control schedules, prescriptions, etc). Yours, David... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From gerhard.haering at gmx.de Sun Jul 28 15:21:49 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 28 Jul 2002 21:21:49 +0200 Subject: Help! Python to compare dates in diff. timezones In-Reply-To: <8f8ffe67.0207280817.6fc327b8@posting.google.com> References: <8f8ffe67.0207280817.6fc327b8@posting.google.com> Message-ID: <20020728192149.GA902@lilith.my-fqdn.de> * Sunit Joshi [2002-07-28 09:17 -0700]: > Hello All > > I have problem which is like this: > I have two sites A & B which are in diff. countries in diff. > timezones. > Now both sites have same drawings (Microstation files with same names) > whose revision dates (as integer since epoch) are stored in a table in > database at both sites. The database structure is same on both sites > with identical table names. Is there some sort of replication taking place? > Now since the sites are different timezones, I was wondering what > would be the best way to compare drawings, using Python, that have > changed between two sites; for e.g. if site A wants to gets a list of > all models that have changed at site A. Just normalize the dates to use GMT, so that you can compare them. > I'm open to any suggestion like using a query over HTTP, using XML, > etc. It sounds easiest to just make both db servers accessible at sites A and B and let that do somebody who knows their stuff about security (I'm not saying you don't). Another transport layer like HTTP doesn't add any value for database access, IMO. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 23.3 ?C Wind: 1.6 m/s From steve.menard at polyester.com Wed Jul 31 15:44:31 2002 From: steve.menard at polyester.com (Steve Menard) Date: Wed, 31 Jul 2002 15:44:31 -0400 Subject: __slots__ variables and initialization References: Message-ID: <5%W19.2969$672.1132655@news20.bellglobal.com> "Holden Caulfield" wrote in message news:c2595393.0207311037.5bacf413 at posting.google.com... > Also, when is the '__' bug in the '__slots__' variable list going to > be fixed? I am currently embarking on a large project and would like > to nail down the convention of '__' for private variables in a class, > quickly. If the bug fix is going to be further down (2.2.2?) then I > would like to change our convention to something else. > That what I have been told. The fix has already been put in the 2.2.2 and 2.3 source trees. As 2.2.2 is the next release, how much earlier could it be? ;) Steve From max at alcyone.com Mon Jul 8 16:22:16 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Jul 2002 13:22:16 -0700 Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: <3D29F478.4528312C@alcyone.com> Gerhard H?ring wrote: > Their twisted worldview? You can safely ignore twisted, if you're not > into > network programming. At least I do and I still feel safe, despite not > agreeing > with dash and moshez on everything :-) And I don't think anybody gets > kicked > there unless (s)he's trolling repeatedly. I eventually gave up (and later found out I was banned, I don't know what effect that was supposed to create). My impression is that they are a bunch of very young, very idealistic, very naive folks, most of which who aren't even old enough to be doing programming professionally and so have a very limited worldview, who are very eager to prove to the world how smart they are, usually by getting into pointless quibbling arguments boiling down to, "If you don't agree with me, you're wrong." The point at which I actually saw them kick and ban someone for asking about someone else's car is when I realized that I had been wasting my time. I enjoyed helping newbies with their Python questions, but dealing with the overinflated egos of these kids was like constant fingernails on a chalkboard. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From comcol at ukmail.com Sun Jul 7 06:12:40 2002 From: comcol at ukmail.com (Comcol) Date: 7 Jul 2002 03:12:40 -0700 Subject: sqlite-python-0.2.0.win32-py2.2.exe fails References: <1b8c5fe1.0207060550.72952217@posting.google.com> Message-ID: <1b8c5fe1.0207070212.679882af@posting.google.com> Gerhard H?ring wrote in message news:... > * Comcol [2002-07-06 06:50 -0700]: > > I tried to run > > sqlite-python-0.2.0.win32-py2.2.exe > > on a Windows 95 machine, but it failed due to a page fault. *Sigh* > > Did you know that we have a list for users of PySQLite at > http://lists.sourceforge.net/lists/listinfo/pysqlite-users ? I didn't! Thanks, that could come in handy. > I only have Windows XP Pro, one other developer has Windows 98, so we > didn't test on Windows 95, yet. > Only Python and PySQLite are required. Date and time data types are > supported if mxDateTime is installed. Much appreciated! > Now that doesn't solve your problem. What we need to debug your problem > is a core dump, or DrWatson file, or whatever it's called on Win95. Does > anybody here know by chance how to produce it? Before we do this ... The actual problem is with the original exe itself (i.e. the INSTALLATION program - the self-extracting executable). It reports an unhandled exception (COMCTL32.DLL) 0xC0000005: Access Violation. I don't think that this is of use to you, though. As far as I know there's nothing wrong with PySQLite itself, but with the self-extracting installation program. If the distribution had been available as a zip file then I would probably be able to install it. > > Comcol, would you be willing to install gdb and run a debug build of > PySQLite so that we could get at the backtrace of your page fault? If > yes, then I could try to assemble the necessary instructions for you. See comments above. > PPS: Have you installed all updates for Windows 95? Service Pack 1? Good Lord no. I don't know where one could get a service pack anyway. mcref01x From sholden at holdenweb.com Mon Jul 1 11:55:49 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 11:55:49 -0400 Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> Message-ID: <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> "Cameron Laird" wrote in message news:53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5 at lp.airnews.net... > In article , > Kerim Borchaev wrote: > >Hello there. > > > > It seems to me that C.l.py is too overloaded today. > > Wouldn't it be nice if someone(not me - I think I don't have > > resources for it) bothered to setup a wiki for discussion about python language? > . > . > . > I've been considering it. If I hear enthusiasm, I'm > more likely to do so; if anyone else wants the privi- > lege, I'm less likely. There did used to be a MoinMoin-based Wiki somewhere under www.python.org, but a recent (i.e. 3 mionutes ago) search of the site failed to find it, and it certainly wasn't used whewn it was there (I recall my own last posting being along the lines of "This isn't a very useful Wiki if nobody knows about it and nobody tries to keep it up to date". I'm sure a Wiki *could* be very useful. not-volunterring-you-understand-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From mark.charsley at REMOVE_THIS.radioscape.com Fri Jul 12 09:44:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Fri, 12 Jul 2002 14:44 +0100 (BST) Subject: Debugging Embedded Python Message-ID: We've got a (win32) C++ program that has an embedded python interpreter that runs a bunch of scripts. We've been asked to enable it's users to run the python scripts under a debugger, allowing the users to put in breakpoints, examine/alter values etc. Now the C++ program basically does the following... - Initialises some C++ stuff - loads in the python DLL - initialises some python stuff - starts a long complicated bunch of processing that bounces between python and C++ One way to get the python running under a debugger is to tweak the system so that the C++ executable becomes a C++ DLL that can be loaded as a python extension. Then it's just a case of having a tiny python script that - initialises some python stuff - loads in the C++ DLL - initialises some C++ stuff - starts a long complicated bunch of processing that bounces between python and C++ It's then a simple matter of running the above python script in a python debugger. While this would work, it has two irritants 1) the work required to change the C++ executable into a python extension DLL 2) the python debugger will (presumably) be built to use release-build DLL's. Which means that any build where we can run the whole thing under a python debugger (i.e. a release build) can't easily be run under a C++ debugger and vice versa. Are there any win32-compatible python debuggers out there which can a) do an "Attach to process" and debug any executable that's using the python DLL and/or b) have source or pre-built debug builds available? Many TIA -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From andreas at kostyrka.priv.at Tue Jul 30 16:41:00 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 30 Jul 2002 22:41:00 +0200 Subject: How to detect the last element in a for loop In-Reply-To: <3D4388C8.6040005@nowhere.org> References: <3D4388C8.6040005@nowhere.org> Message-ID: <1028061748.4359.17.camel@vaio2> Am Son, 2002-07-28 um 08.00 schrieb Bryan Olson: > Tom Verbeure wrote: > [...] > > I am not familiar with iterators as objects in Python. I understand that > > > > for a in myList: > > ... > > > > will result in an implicit iterator on myList. > > For a simple solution, how about: > > for a in myList[:-1]: > do_stuff(a) > special_stuff(myList[-1]) Breaks on myList=[] Better: for a in myList[:-1]: do_stuff(a) for a in myList[-1:]: special_stuff(a) That works, because slicing an empty list always returns an empty list, while accessing an nonexistant element throws an exception. :) Andreas From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 20:25:45 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 19:25:45 -0500 Subject: Newbie question: unexpected diagnostic when subclassing In-Reply-To: <3d472b34$1@news.rivernet.com.au> ("Jeff Melvaine"'s message of "Wed, 31 Jul 2002 10:28:08 +1000") References: <3d472b34$1@news.rivernet.com.au> Message-ID: >>>>> "Jeff" == Jeff Melvaine writes: Jeff> I think I must be doing something basically wrong, but Jeff> ... ??? I'm running Python 2.1 on Windows 98. I create a Jeff> file x.py in which I declare Jeff> class x: ... Jeff> I then create a file y.py in which I declare Jeff> class y(x): ... Jeff> When I try to create an instance of y, I get the diagnostic Your class syntax is find. At the top of y.py did you 'from x import x'? 'import x' won't do with your syntax In y.py you either need from x import x class y(x): pass import x class y(x.x): pass JDH From mfranklin1 at gatwick.westerngeco.slb.com Thu Jul 11 06:29:24 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 11 Jul 2002 10:29:24 +0000 Subject: Pmw.Counter and Pmw.ScrolledCanvas questions In-Reply-To: <200207110825.g6B8P4728314@helios.gatwick.geco-prakla.slb.com> References: <18692175.0207102141.1d5279c1@posting.google.com> <200207110825.g6B8P4728314@helios.gatwick.geco-prakla.slb.com> Message-ID: <200207110933.g6B9XA708329@helios.gatwick.geco-prakla.slb.com> On Thursday 11 Jul 2002 9:21 am, Martin Franklin wrote: > On Thursday 11 Jul 2002 5:41 am, John McMonagle wrote: > > My first question is to do with Pmw.Counter. I am creating a > > Pmw.Counter like so (see below code sample): > > > > > > Because the label spans two text lines, the entryfield is also > > expanded to this height. > > > > Is it possible to set the height of the entry field so as to only > > appear as a single line ? Another way to say it is can the frame > > component height and position be changed within the hull component ? > > I just had some more thoughts on the Counter problem. Pmw uses the grid geometry manager and presumably for the Counter has a sticky='news' option which would account for what you are seeing, It should be possible to change this. Ok from the source:- self._counterEntry.grid(column = 1, row = 0, sticky = 'news') This depends which orientation you are asking for but it's that sticky='news' that is causing your problem, what to do??? I would start by changing it to just sticky='ew' and see what happens. Martin. From cliechti at gmx.net Tue Jul 23 19:32:10 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 01:32:10 +0200 Subject: Need a better way to pause a thread References: <4378fa6f.0207231456.3057babe@posting.google.com> Message-ID: mnations at airmail.net (Marc) wrote in news:4378fa6f.0207231456.3057babe at posting.google.com: > Hi: > > I am trying to find the best way to pause one of my threads. In most > areas where the modules are small or in loops, I have an event created > that I just event.wait() for. This works very well. However, in > another area of code I have a long series of unique commands. I want > to avoid having to place event.wait() dozens of times. I tried the > following: [snipped events example] > Either way, under Windows with Python there's no way to create a > thread and just pause execution of the thread from an os level. So is > there a better way to be able to pause a long series of unique > commands without having to sprinkle holds everywhere? have a look at Queue.Queue. here is an example: import sys, threading, Queue, time def runme(): while 1: whatdodo = q.get() #blocking if whatdodo is None: #this is for a graceful shutdown break #do whatever needed with or without "whatdodo" #example with callable, expected is a sequence (cmd, arg1, ...) whatdodo[0](*whatdodo[1:]) #or use apply q = Queue.Queue() t = threading.Thread(target=runme) t.start() #now you can feed your thread with work: q.put( (time.sleep, 1) ) q.put( (sys.stdout.write, "Hello its the thread speaking up") ) print "main is talking" #or shutdown the thread: q.put(None) print "main finished, waiting for worker" ### you can put just a marker into the queue or a data object if the thread knows to handle it or you can pass callables like shown above which the thread executes then... chris -- Chris From aleax at aleax.it Mon Jul 8 02:10:56 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 06:10:56 GMT Subject: Can raise only "classic" classes? References: Message-ID: Holden Caulfield wrote: > Greetings, > I have run into a slight problem. Is it true that you can only raise > exceptions that are "classic" classes? Yes, at this time. Specifically, you should only raises [instances of] subclasses of the builtin class Exception, which is itself a classic class as of 2.2 (and 2.3, at least judging from what's in CVS now). This is not (yet?) strictly enforced, but the fact that the class of what you raise must be of the same object-model as Exception (which, currently, means classic) IS. Alex From ppcdev at hotmail.com Sun Jul 14 12:08:20 2002 From: ppcdev at hotmail.com (ppcdev) Date: 14 Jul 2002 09:08:20 -0700 Subject: i come back to python; just some questions Message-ID: <2fa5f3a9.0207140808.e4d7d38@posting.google.com> hi. i used to develop little windows application in python some years ago. today i come back to this language because i 'd like to test the security of some ftp servers. it's really easy to connect to a ftp server with python (for newer newbies here it is ): import socket; s=socket.socket(socket.AF_INET, socket.SOCK_STREAM); vr=s.connect(('127.0.0.1',21)); s.setblocking(0); s.send('user user1\r\n'); d=s.recv(1024); print d; i was working on an old pentium II and wanted to send a very long string in the USER parameter but it made my computer bug.. is it normal??? str='a'; r=range(1024); for x in r[:]: str=str+str but it even bugs with a value of 512 and 256 for r=range(..) thanks From dieter at handshake.de Thu Jul 18 15:07:53 2002 From: dieter at handshake.de (Dieter Maurer) Date: 18 Jul 2002 21:07:53 +0200 Subject: Exploit for a security hole in the pickle module for Python versions <= 2.1.x References: Message-ID: Jeff Epler writes on Wed, 17 Jul 2002 07:47:14 -0500: > Exploit for a security hole in the pickle module for Python versions <= 2.1.x Thank you for the precise problem statement! > ... > Because a "class constructor" is > simply a callable object, > a pickle can be written that names any function > and gives it arbitrary arguments. But this need not be the case! A "class constructor" is quite a special "function". Its "type" is "ClassType" (at least until Python 2.2). Dieter From trentm at ActiveState.com Wed Jul 24 15:36:40 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 24 Jul 2002 12:36:40 -0700 Subject: Strange Queue error In-Reply-To: <4378fa6f.0207241120.1876187b@posting.google.com>; from mnations@airmail.net on Wed, Jul 24, 2002 at 12:20:04PM -0700 References: <4378fa6f.0207241120.1876187b@posting.google.com> Message-ID: <20020724123640.A18586@ActiveState.com> [Marc wrote] > I was attempting to use the Queue and came across a strange error. Why > is Python wanting a Queue instance as an argument and not accepting > the tuple. I was simply trying to put this on the queue: > > > qlist.put( (sleep, 5) ) > > Here is the error. > > C:\Python22\CAP v1.0\queue>python temp2.py > Project is a go > in check > Exception in thread Thread-1: > Traceback (most recent call last): > File "C:\Python22\lib\threading.py", line 408, in __bootstrap > self.run() > File "C:\Python22\lib\threading.py", line 396, in run > apply(self.__target, self.__args, self.__kwargs) > File "temp2.py", line 586, in launch > main.launchUTStest() > File "main.py", line 31, in launchUTStest > eval( modules.securityFunctions[mod] )(gui, qlist) > File "security.py", line 35, in uid_gen_format > qlist.put( (sleep, 5) ) > TypeError: unbound method put() must be called with Queue instance as > first argu > ment (got tuple instance instead) > > Does anyone know what this means? It likely means that you are passing around a Queue *class* object instead of a Queue class *instance*. You probably have a qlist = Queue somewhere instead of: qlist = Queue() Trent -- Trent Mick TrentM at ActiveState.com From bergeston at yahoo.fr Tue Jul 2 12:26:59 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Tue, 2 Jul 2002 18:26:59 +0200 Subject: Where python especially good ? References: Message-ID: "Andrey Koubychev" wrote in message news:afrmbm$d28$07$1 at news.t-online.com... > Hello everyone, > > What do you think, at what tasks pythons shows great benefits comparing to > other script languages ? > Any task that you want from a programming language except: - spent an unused budget before the end of the year, - give occupation to a lot of people for a simple task, - write unmaintainable programs, - give you the opportunity to discuss endlessly of the best way to program something : the pythonic one IS the good one (OK, now you have to discuss what is the pythonic one but this is one level of abstraction above - please don't flame me with that, only joking - can't resist - I KNOW that the pythonic way is obvious ! it's even probably its best definition) - ... More seriously: - scripting - glu between other programs - server-side application with a more special skill to internet application (see Zope or other frameworks) - scientific applications - ... Enjoy P. B. > -- > Best regards, > Andrey Koubychev > > From mwh at python.net Fri Jul 26 06:18:46 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 10:18:46 GMT Subject: memory leak Py_initialize+Py_Finalize??? References: Message-ID: siugarc at interserv.com.tw (??????) writes: > I call only Py_Initialize() and Py_Finalize() in VC. > Many memory leaks are showed in BoundsChecker. These are probably interned strings. You can google for a deeper explanation. > If I call Py_Inisialize() and Py_Finalize() repeatedly, more memory > leaks are made. Who know if this is the bug of python? What version? I think various bugs of this kind were fixed for ... erm ... 2.1? Certainly before 2.2.1, anyway. Cheers, M. -- SPIDER: 'Scuse me. [scuttles off] ZAPHOD: One huge spider. FORD: Polite though. -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 31 17:32:59 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 31 Jul 2002 21:32:59 +0000 Subject: Python Questionnaire In-Reply-To: <20020731091858.48784.qmail@web40301.mail.yahoo.com> References: <20020731091858.48784.qmail@web40301.mail.yahoo.com> Message-ID: <200207312033.g6VKXK006205@helios.gatwick.geco-prakla.slb.com> On Wednesday 31 Jul 2002 9:18 am, Marta Gutierre wrote: > Does any body know of any code in python for questionnaires ??? > > Tipicall web-forms with questions and storing results in files or things > like that If you mean basic cgi type stuff then there are some how-to's here:- http://www.python.org/topics/web/basic-cgi.html Martin From martin at v.loewis.de Wed Jul 31 02:52:17 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Jul 2002 08:52:17 +0200 Subject: newbie : unicode References: <3D473933.8040306@wanadoo.fr> Message-ID: polux writes: > I'm using IDLE for windows and when i'm using a char like ? or ? (i'm > french :)), i get the error message : UnicodeError: ASCII encoding > error: ordinal not in range(128) > > but if i've understood, Python works with unicode, so there should be > no problem ! The problem is that Python does not know what encoding to use for those characters; by default, it assumes ASCII, but ASCII does not support those characters. A work-around is described in http://www.python.org/doc/FAQ.html#4.102 Regards, Martin From ld at nospam.com Mon Jul 1 20:41:27 2002 From: ld at nospam.com (Larry) Date: Tue, 02 Jul 2002 00:41:27 GMT Subject: File read problem in Windows References: <20020702121832.51ed39eb.larooy@xtar.co.nz> Message-ID: "John La Rooy" wrote in message news:20020702121832.51ed39eb.larooy at xtar.co.nz... > On Tue, 02 Jul 2002 00:11:17 GMT > "news" wrote: > perhaps the file has the windows EOF character in it? ctrl-D or ctrl-Z i think. > try > > f=open('myfile','rb') That did the trick!!! Thank you so much!!! Larry From gumuz at looze.net Wed Jul 3 08:51:56 2002 From: gumuz at looze.net (Guyon Morée) Date: Wed, 3 Jul 2002 14:51:56 +0200 Subject: what's up with 'patterns'? Message-ID: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> i've seen several topics referring to 'patterns'. i am unfamiliar with this. could someone explaint to me what this is all about? thanx, Guyon From r_olson at sandiego.edu Mon Jul 22 21:11:58 2002 From: r_olson at sandiego.edu (Rick Olson) Date: 22 Jul 2002 18:11:58 -0700 Subject: Problem EmbedingPython w/ Tkinter in C on Linux Message-ID: Hi-- I'm using Python 2.2 on a machine running Red Hat 7.2. I have some Python scripts that use Tkinter that I would like to use as the elements for the interface for a large C program. Consequently, I'm trying to embed the Python/Tkinter into C. It isn't practical for me to try to extend the C routines from Python. To complicate things, I an relatively green at Linux. I was able to run the embedding demo program. I also built a 3 line pythohn script that justs opens a Tkinter window. It runs fine using Idle. Next I tried using RunPy_SimpleFile to run the script. I ran into problems, so I backed . I can compile, but something is missing as when I try to run the program I get: Traceback (most recent call last): File "test.py", line 1, in ? File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: /usr/lib/python2.2/lib-dynload/_tkinter.so: undefined symbol: _Py_NoneStruct I attempted to add tcl and tk libraries to the demo makefile and am now using the makefile below. Can someone help identify where I'm running into problems? Thanks in advance-- Rick Olson # Makefile for embedded Python modified to include tk and tcl. CC= gcc # Python version VERSION= 2.2 # Top of the build tree and source tree blddir= /usr/lib/python2.2/config srcdir= /usr/include/python2.2 # Compiler flags OPT= -g INCLUDES= -I$(srcdir)/Include -I$(blddir) -I$(srcdir) CFLAGS= $(OPT) $(INCLUDES) # The Python library LIBPYTHON= $(blddir)/libpython$(VERSION).a # XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile TKLIBS= -ltcl8.3 -ltk8.3 LIBS= -lnsl -ldl -lreadline -ltermcap -lpthread -lieee -lutil SYSLIBS= -lm MODLIBS= ALLLIBS= $(TKLIBS) $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS) # Build the demo application all: CallTkinter CallTkinter: CallTkinter.o $(CC) CallTkinter.o $(ALLLIBS) -o CallTkinter # Administrative targets test: CallTkinter sh make ./CallTkinter clean: -rm -f *.o core clobber: clean -rm -f *~ @* '#'* CallTkinter From maxm at mxm.dk Wed Jul 3 09:02:55 2002 From: maxm at mxm.dk (Max M) Date: Wed, 03 Jul 2002 15:02:55 +0200 Subject: what's up with 'patterns'? References: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> Message-ID: <3D22F5FF.9070408@mxm.dk> Guyon Mor?e wrote: > i've seen several topics referring to 'patterns'. > i am unfamiliar with this. could someone explaint to me what this is all > about? Well people have been doing object oriented programming for several years by now, and some programmers have noticed that patterns are starting to emerge in how they use objects to reach their goals. That is as they try to solve different problems they often use the same method of solving their problem. These patterns has been described and named in litterature, so that programmers can refer to them under their pattern names. Try to google on "Programming Patterns", that will most likely turn up more info than you care to shake a stick at ... regards max M From m.faassen at vet.uu.nl Tue Jul 9 18:57:46 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 9 Jul 2002 22:57:46 GMT Subject: openprojects python room is ruled by dangerous people References: <3eeda89d.0207070906.1fa45916@posting.google.com> Message-ID: Martijn Faassen wrote: [snip] > They do kick you out a bit readily, I agree. I got somewhat annoyed > when I got kicked out while apologizing for spamming with a misfired > copy & paste buffer. This is a vile PSU accusation! It was some evil automated system that did not allow me to apologize, apparently, and I misattributed this to a human agent. Again proof of the evil robot conspiracy against mankind. My new complaint about #python is a rather locker-room atmosphere that seems to have snuck into the place over time. I suspect this is yet more proof of the evil robot conspiracy. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From skip at pobox.com Sun Jul 28 16:59:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 28 Jul 2002 15:59:08 -0500 Subject: Guide to the python interp. source? In-Reply-To: <1027848147.20536.125.camel@vaio2> References: <1027848147.20536.125.camel@vaio2> Message-ID: <15684.23324.498143.792539@localhost.localdomain> >> I noticed, but thought that I just had missed it. I thought there >> must be some where for such a large project. But the problem is >> ofcourse ever present, "nobody likes to do documentation" Something occurred to me last night... How about a PyVM Wiki? Once the content is there we could see about organizing it in a suitable form for inclusion in the standard document set. I started things off with some notes I wrote a few months ago: http://manatee.mojam.com/pyvmwiki/ -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From warkid at storm.ru Mon Jul 1 09:29:52 2002 From: warkid at storm.ru (Kerim Borchaev) Date: Mon, 1 Jul 2002 17:29:52 +0400 Subject: Pyrhon language dedicated Wiki Message-ID: <18729.020701@storm.ru> Hello there. It seems to me that C.l.py is too overloaded today. Wouldn't it be nice if someone(not me - I think I don't have resources for it) bothered to setup a wiki for discussion about python language? Best regards, Kerim mailto:warkid at storm.ru From sdrake at knology.net Tue Jul 30 11:22:42 2002 From: sdrake at knology.net (Steve Drake) Date: 30 Jul 2002 08:22:42 -0700 Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3 References: Message-ID: Martin's suggestion solved my problem. BTW, entering the commands that Jonathan mentioned in an earlier post still shows pyexpat.__version__ as 2.57. However, I've got two pyexpat shared objects: $ diff `find . -name pyexpat.so -print` Binary files ./site-packages/_xmlplus/parsers/pyexpat.so and ./lib-dynload/pyexpat.so differ Thanks! loewis at informatik.hu-berlin.de (Martin v. L?wis wrote in message news:... > sdrake at knology.net (Steve Drake) writes: > > > I am having a problem using PyXML with tutorial code that I got at > > http://www.ibm.com/developerWorks. Although this code works on > > Windows with python-2.2.1, and works on RH 7.3 with python-1.5.2, I > > get an error when attempting to use python-2.2.1 on RH 7.3. I tried > > installing python-2.2.1 and PyXML-0.7.1 from source, but I get the > > same error as when using rpm packages. > > Please install from sources, and make sure that the pyexpat extension > is built; do so by adding --with-pyexpat to the setup.py command line. > Then double-check that it it is really build - you need to find > pyexpat.so in your build directory. Reinstall, then retry your test. > > It is a bug in PyXML 0.7.1 that setup.py won't build pypexpat when it > should. > > Regards, > Martin From pyth at devel.trillke.net Sat Jul 13 10:55:40 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 13 Jul 2002 16:55:40 +0200 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: ; from huaiyu@gauss.almadan.ibm.com.trillke.net on Fri, Jul 12, 2002 at 05:45:15PM +0000 References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <20020713165540.Y10625@prim.han.de> Huaiyu Zhu wrote: > Readability for machines does not have to come at the expense of readability > for humans. A few years back I experimented with an indentation based data > format that is: > > - as readable as emacs's outline mode > - reduce to common conventions like this paragraph for simple cases > - allow mixed nested structures of set, sequence, dictionary, and seqdict > - can include binary data > - can handle different encodings/encryptions in different elements > - with average less than 5% bloat, in contrast to XML's over 100% bloat do you have any code or design documents for this? Sounds quite interesting. holger From davidw at uq.net.au Sat Jul 27 01:10:44 2002 From: davidw at uq.net.au (David Wright) Date: Sat, 27 Jul 2002 15:10:44 +1000 Subject: turtle module information References: <13285ea2.0207261327.2827b3a6@posting.google.com> Message-ID: "J.Jacob" wrote in message news:13285ea2.0207261327.2827b3a6 at posting.google.com... > The turtle module is very nice. I would like to know if there is any > more information about the turtle module available? Of course there > is the turtle.py file in C:\Python*\Lib\tk* but I am also interested > in things like who wrote it and design decisions. > > Is it possible to change the font used by turtle.(Raw_Pen).write() ? Hi, Since you have been using turtle.py, could you please tell this newbie how to import it into IDLE and start using the turtle commands. Where do the graphics appear? Many thanks. David From aleax at aleax.it Sat Jul 27 03:21:57 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Jul 2002 07:21:57 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: Steve Holden wrote: ... >> for word in 'fee fie foo fum'.split(): >> Button(frame, command=lambda: print word) >> >> The poster is typically nonplusses that all buttons print 'fum'. >> > I would be nonplussed if that code even *compiled*, given that "print" is > a keyword and lambda takes an expression not a statement. Right - you caught my little trap. I don't regret using it, though, because it DID catch a couple of lambda-lovers... and it also shows a real issue with lambda. Sure, you get a SyntaxError and that's that. But if you want to use lambda, you have to keep dismantling and restructuring to change to def'd functions each time you need a statement there (and print is a good example here, as it does help debugging). >> Lambda's scope (or 'scope') has taken another victim. >> > This is not to say, of course, that newbies don't try to write exactly > such incorrect code, and this is probably one of the reasons why Guido > continues to suggest it's a wart (albeit one we're going to have to > continue to live with). I think the reason why Guido suggests it's a wart is that it IS a wart. Sure, backwards compatibility mandates lambda stay, but I think it's worth emphasizing that it's there ONLY for backwards compatibility, and using def is better. > not-like-you-to-propagate-syntax-errors-ly y'rs - steve Right. Inserting subtle traps in my examples, however, IS a think I've been known to do. Sometimes it helps drive a point home. Alex From imbosol at vt.edu Fri Jul 26 19:15:05 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 26 Jul 2002 19:15:05 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: Britt A. Green wrote: > So I know what lambda functions are, they're syntax and how they're used. > However I'm not sure *why* one would use a lambda function. What's the > advantage that they offer over a regular function? It's for lazy people. I am a lazy person. Feel free to never use it, if you don't want. -- CARL BANKS http://www.aerojockey.com From pinard at iro.umontreal.ca Mon Jul 8 15:14:19 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 15:14:19 -0400 Subject: `~/.pythonrc' `from __future__ import' In-Reply-To: References: Message-ID: [Tim Peters] > All the -Q options are documented in the division PEP: > http://www.python.org/peps/pep-0238.html Thanks for the reference, I'll take a look. One one hand, a future-related option is not going to be extensively documented in the reference manual. On the other hand, thinking about it, it could probably be documented at least in the Python `man' page, since the option exists as of now. Probably not worth the fuss? :-) > > However, it wonder if this is all fully right. [...] to check at run > > time what features are currently available in the running Python. > You could, although [...] It was emphatically not the intent of > future-statements to create multiple "pick and choose" dialects of Python. > Its only design goal was to provide a transition period between flat-out > incompatible semantics [...] Let me thank you, Tim, for this comprehensive and enlightening answer! I'm carefully saving it for later meditation. :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From ipmynp at yahoo.com Sat Jul 27 06:54:25 2002 From: ipmynp at yahoo.com (ipmynp at yahoo.com) Date: Sat, 27 Jul 2002 12:54:25 +0200 Subject: Start Making Money in 30 mins or less - Instant Download 3934 Message-ID: <15utha.0222.ln@linproxy.jackstaedt> http://ebook.best2web.com/ - Instant Download - Instant Download - Instant Download Free Download The Absolute Beginner's Guide to Starting a Web Site Totally Free Web Resources Unlimited Profits 7 Secrets To Unlimited Traffic Scientific Advertising How to Start Your Own Traffic Virus Marketing Warriors Tips eBookoMatic eBook Submitter The Best of Web Gold On Line Stealth Marketing and more http://ebook.best2web.com/ - Instant Download - Instant Download - Instant Download vycoxbbfvhvnxcmoxukiuhcznyptodrkibmmwblschnjrylizskzomytejhigugxfzlzivtvrosylcuznmc From paragate at gmx.net Mon Jul 22 16:43:20 2002 From: paragate at gmx.net (Wolfgang Lipp) Date: Mon, 22 Jul 2002 22:43:20 +0200 (MEST) Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: Message-ID: "Terry Reedy" wrote in news:tRe_8.181317$iB1.9982565 at bin4.nnrp.aus1.giganews.com: > > "Wolfgang Lipp" wrote in message > news:Xns9250DFB43AB73lippatpostde at 213.73.102.4... >> i am currently concerned with the problem of how to read > > PyOneWire is new to me, Google, and probably most readers here. Find > the author/distributor. terry, can't be... check out the current thread --- my reference wasn't really all THAT farfetched, after all On 6 Jun 2002 04:56:02 -0700, python at tykebsd.net (Dave Moor) wrote: >Hi > >I have just started producing a PyOneWire module it currently can >search the one wire network for families of devices and read the >temperatures from DS1820 devices. What platform are you wanting to >run it on, I could send you a prerelease versiob to try. >Date: 2002-06-07 00:55:16 PST >Hi Everyone >Since one or two people are interested in this I have put a page on my >website (http://www.tykebsd.net) with some info and some files to From h_j_fong at hotmail.com Sat Jul 27 17:48:56 2002 From: h_j_fong at hotmail.com (Chris) Date: Sat, 27 Jul 2002 17:48:56 -0400 Subject: wxPython TextCtrl overwriting References: Message-ID: Thanks Chris, I'll give that a try. BTW, any idea why python usually crashes so horrendously while running my GUI in windows? It seems like if I click on my python window or anything like that while the GUI is up, everything crashes fierce; yet the GUI seems to be "bugfree" - if that state even exists. Is there some exception handling I can insert that will avoid this? It's a pain to have to restart IDLE and my program 9 times out of the 10 I run it. Cuts my productivty in half. Chris On 27 Jul 2002 22:52:01 +0200, Chris Liechti wrote: >Chris wrote in >news:res5ku4e8agpfikcscrv872s67lu1bng4g at 4ax.com: > >> In my GUI I'm using a fairly standard dirDialog to get a path, with a >> line for manual entry or the browse button beneath. How do I write >> the selected path *over* the default text currently in the box. Seems >> like it should be a one-liner (.replace, .erase, .clear, >> .overwrite???). Currently I am using .write, which appends it. > >.SetValue() and .GetValue() should help > >chris From mwh at python.net Wed Jul 3 09:36:15 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 3 Jul 2002 13:36:15 GMT Subject: EuroPython 2002 diary Message-ID: I've put the notes I took during the (fantastic!) EuroPython 2002 conference online here: http://starship.python.net/crew/mwh/europython.html They're subjective and not comprehensive. Cheers, M. -- If you have too much free time and can't think of a better way to spend it than reading Slashdot, you need a hobby, a job, or both. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq From zeitlin at seth.lpthe.jussieu.fr Mon Jul 1 08:58:42 2002 From: zeitlin at seth.lpthe.jussieu.fr (Vadim Zeitlin) Date: Mon, 1 Jul 2002 12:58:42 +0000 (UTC) Subject: wxFont-question References: Message-ID: On Mon, 01 Jul 2002 12:29:56 +0200, Klaus Reinhardt wrote: > I want to change the font to equal letters, If I understand you correctly, you need the font family of wxTELETYPE and not wxMODERN. Regards, VZ -- GCS/GM d? H+ s++:-- p2 au--- a- w+ v C+++ UBLS+++ P- L++ N++ E--- W++++ M? V-- -po+ R++ G`` !tv b+++ D--- e++++ u++ h--- f+ r++ n- y? From fperez528 at yahoo.com Mon Jul 8 17:05:47 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 08 Jul 2002 15:05:47 -0600 Subject: List assignment, unexpected result References: Message-ID: Steve Coates wrote: > A friend of mine recently sent me some code and asked if I could > predict what it would do. I guessed wrong. Code as follows:- > > grid = [['.'] * 4 ] * 4 > grid [0][0] = '0' > grid [1][1] = '1' > grid [2][2] = '2' > grid [3][3] = '3' > for i in grid: print i If this will be done for large grids, I suspect you're better off using Numeric arrays for it. You can later always write a special print method which gives you the '.' output as needed: In [2]: diagonal_matrix (arange(5)) Out[2]: array([[0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 3, 0], [0, 0, 0, 0, 4]]) In [3]: @psource diagonal_matrix def diagonal_matrix(diag): """Return square diagonal matrix whose non-zero elements are given by the input array.""" return diag*identity(len(diag)) Cheers, f. From bokr at oz.net Mon Jul 15 22:35:28 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2002 02:35:28 GMT Subject: Newbie: Capture output of compile_dir References: Message-ID: On Mon, 15 Jul 2002 14:04:28 -0700 (PDT), Becky Hehn wrote: >In-Reply-To: >MIME-Version: 1.0 >Content-Type: text/plain; charset=us-ascii > >Thanks for the response. I tried the code you gave >me, but it didn't quite work like I wanted. I created >a syntax error in my python file (left out a quotation >mark) and tried the code. Below is the information >from my interpreter session: > Idle or console window? > >>>> import sys >>>> from cStringIO import StringIO >>>> from compileall import compile_dir >>>> path='/home/hehn/test' >>>> orig_so = sys.stdout >>>> sys.stdout = captured = StringIO() At this point the interactive loop is echoing your keystrokes, so presumably it has a a private reference to the old sys.stdout for that purpose, but if you typed print 'hello' the output would go to the StringIO() instance. >>>> compile_dir(path,force=1) Still echoing, but the next 3 lines probably went to sys.stderr >File "/home/hehn/test/me.py", line 2 >Write('status) >Syntax Error: invalid token >>>> sys.stdout = orig_so Now old stdout should be active again >>>> output = captured.getvalue() >>>> output >'Listing /home/hehn/test . . . Compiling >/home/hehn/test/me.py' > > >If an the prompt I just type the compile command, I >get all the output at once(see below). I would like >the output variable to contain all this feedback from >the compile_dir command. Not just the initial two >lines. Any thoughts on what I did wrong? Thank you >in advance. > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> from cStringIO import StringIO >>> orig_so = sys.stdout >>> orig_se = sys.stderr >>> sys.stdout = so = StringIO() >>> sys.stderr = se = StringIO() >>> print '-- firt line --' >>> 1/0 >>> print '-- 2nd line --' >>> print '-- 3nd line but without eol --', >>> sys.stdout = orig_so >>> sys.stderr = orig_se >>> so.getvalue() '-- firt line --\n-- 2nd line --\n-- 3nd line but without eol --\n' >>> se.getvalue() 'Traceback (most recent call last):\n File "", line 1, in ?\nZeroDivisionError: in teger division or modulo by zero\n' Hm, I didn't expect a '\n' on that 3rd line. StringIO doesn't seem to define softspace, so I wonder how you can capture an accurate copy of what would go to stdout using print without that.... A quick experiment: >>> class X: ... def __init__(self): ... self.s = [] ... self.softspace=0 ... def write(self,x): self.s.append(x) ... >>> sox=X() >>> sys.stdout = sox >>> print 'hello', >>> print 'hello', >>> sys.stdout = orig_so >>> sox.s ['hello', '\n', 'hello', '\n'] >>> print 'hello',;print 'hello' hello hello >>> sox=X() >>> sys.stdout = sox >>> print 'hello',;print 'hello' >>> print 'hello',;print 'hello' >>> sys.stdout = orig_so >>> sox.s ['hello', ' ', 'hello', '\n', 'hello', ' ', 'hello', '\n'] >>> sox=X() >>> sys.stdout = sox >>> print 'hello',;sys.stdout.softspace=0;print 'hello' >>> print 'hello',;print 'hello' >>> sys.stdout = orig_so >>> sox.s ['hello', 'hello', '\n', 'hello', ' ', 'hello', '\n'] Nope, seems to be looking at original sys.stdout.softspace irrespective of redirection. And I'm still not sure that third line is right. Why should the interactive echo to the next line make a difference to softspace when stdout is re-directed? Or is that what does it? It seems like a bug someplace... BTW, running python with the -u switch might be something to try also, to get a better handle on the sequencing of outputs to stdout and stderr. Regards, Bengt Richter From jhalttun at pp.htv.fi Tue Jul 23 11:52:13 2002 From: jhalttun at pp.htv.fi (janne halttunen) Date: Tue, 23 Jul 2002 18:52:13 +0300 Subject: curses and terminal resize References: <3D3D61D1.8010600@pp.htv.fi> Message-ID: <3D3D7BAD.7050804@pp.htv.fi> Michael Hudson wrote: > janne halttunen writes: > > >>Hello all, >> >>I am writing a curses widget library. The trouble I am having is to >>obtain new values for lines and columns in terminal after resize >>event. I have a short program below that should demostrate the problem: > > [...] > >>Any help is appreciated, > > > Does this: > > http://groups.google.com/groups?selm=uk7xtwasm.fsf%40python.net > > help? > > Cheers, > M. > Indeed, it does the trick. Thanks, janne From eric.brunel at pragmadev.com Tue Jul 30 11:08:43 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 30 Jul 2002 17:08:43 +0200 Subject: How to execute an external binary reading from standard in References: <3D46A6FC.AA068BC8@iki.fi> Message-ID: Markus O Kaukonen wrote: > Dear all, > > How to execute a exeternal (binary) program reading from standard input > in a python code ? > For example : /home/mok/my_prog.bin < my_input.txt > > My system is Linux and the binary is written originally in fortran 90 > (if that should matter). > > I tried > os.popen('/home/mok/my_prog.bin < my_input.txt ') > with no success No need for popen here. Doing a: os.system('/home/mok/my_prog.bin < my_input.txt ') should work. You may also do it "by hand" by doing: p = os.popen('/home/mok/my_prog.bin', 'w') p.write(open('my_input.txt').read()) p.close() which is exactly the same thing as above, but done with Python. But the os.system above really should work... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From donn at u.washington.edu Mon Jul 15 18:42:36 2002 From: donn at u.washington.edu (Donn Cave) Date: 15 Jul 2002 22:42:36 GMT Subject: Making code 2.1 compatible References: Message-ID: Quoth Tim Peters : | [Donn Cave, on the Python Business Forum] |> Interesting, but only in the sense of "tantalizing". It reads |> like the author (Michael Hudson?) already knew about the basic |> idea, and assumed the reader does too. | | Laura Creighton wrote the FAQ: | | http://pbf.nuxeo.org/faq.html Thanks. That does get fairly specific, 18 month release cycle and limited new features. I infer from the language that they understand that the new features part has potential problems. |> And the choice of 2.2 doesn't help clarify it, since it's a pretty new |> release. | | What's to clarify? The 2.2 line is the most stable Python there is. | They're business people, not Luddites . Matter of perspective. I would probably have picked 2.2 if it had been left to me, just because it's current. But when I've proposed it in the past I've suggested the recently out-of-current release, because that makes it immediately an issue. Either way, not on the basis of any technical properties of the releases in question. I don't even know what "stable" means, rather ambiguous if you ask me. | Indeed. The PBF is a wonderful thing, and wouldn't exist without Laura's | vision and energy. Good deal. Donn Cave, donn at u.washington.edu From b.hall at irl.cri.nz Wed Jul 10 21:31:01 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: Thu, 11 Jul 2002 13:31:01 +1200 Subject: Com Exceptions from Excel Message-ID: <3D2CDFD5.7193B8BE@irl.cri.nz> I would appreciate some advice in how to use information about COM exceptions generated from MS Excel. Based on "Python: programming on win32", Ch 12, p212 I have written the following exception handler def comExceptionHandler(e) : hr,msg,exc,arg = e sys.stderr.writelines( 'COM call failed: (HRESULT=%s) %s\n' % (hr,msg) ) if (arg != None and arg != -1): sys.stderr.writelines( 'Argument: %s\n' % arg ) if exc != None: wcode, source, text, helpFile, helpID, scode = exc sys.stderr.writelines( 'Error wcode=%s scode=%s\n' % (wcode,scode) ) sys.stderr.writelines( 'Error source: %s \n' % source ) sys.stderr.writelines( '%s \n' % text ) sys.stderr.writelines( 'See also: %s (id=%d) \n' % (helpFile,helpID) ) The information this gives is hard to deal with. For example, I have an instance of MS Excel open and I try to save the current workbook, wb.SaveAs(filename) Lets say filename identifies a file that exists already, so Excel asks me with a dialog box if I want to overwrite or not. I click on 'No' and an exception is raised. The handler above produces the following mesage: COM call failed: (HRESULT=-2147352567) Exception occurred. Error wcode=1004 scode=0 Error source: Microsoft Excel SaveAs method of Workbook class failed See also: XLMAIN8.HLP (id=0) My problem is that I can't figure out how the numerical error code relates to the MS Help files. I realise that the HRESULT value is DISP_E_EXCEPTION (from the win32 book), but how does wcode or scode relate to the Excel documentation? I can find nothing in either XLMAIN.hlp or VBAXL8.hlp to shed light on this! Obviously it would be nice to identify types of error so that appropriate action can be taken! In this case, change the file name. From Gabe.Newcomb at noetix.com Mon Jul 22 19:43:09 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Mon, 22 Jul 2002 16:43:09 -0700 Subject: Tkinter question: how to make hotkeys work Message-ID: <0C7CA8D8DF75494EB09AB6016990107F016F610C@NOXMAIL.noetixad.com> (I'm working in Win2k) I've found how to underline a letter on a Button widget, but I can't seem to use the hotkey to trigger it (Alt + underlined key). What am I missing? Additionally, if there is a Tkinter mailing group, please let me know. Thanks, Gabe From merman at snafu.de Sun Jul 7 13:03:01 2002 From: merman at snafu.de (T. Kaufmann) Date: Sun, 07 Jul 2002 19:03:01 +0200 Subject: constructors in python Message-ID: <3D287445.6000202@snafu.de> Hi folks, thanx for hints & good ideas! It helps very much! o-o Thomas ps: ... yes alex, the second param is false ;-). From mnations at airmail.net Mon Jul 29 15:36:10 2002 From: mnations at airmail.net (Marc) Date: 29 Jul 2002 12:36:10 -0700 Subject: Tkinter and Window's controls Message-ID: <4378fa6f.0207291136.2d003a4d@posting.google.com> Hi, I am having trouble with the X button - exit button on upper right of the windows created by Tkinter. I was able to 'bind' to the 'Destroy' event, so I know when the window is going to be destroyed, and I can perform some cleanup What I want to do, is do the same thing I do on my menu exit button: throw up a pop-up and ask 'are you sure' yes-no.... The destroy event that i bound to, comes after python has started to shut everything down - not first, like I expected. So my question is, how do I bind or have control over the X button? Thanks, Marc From imunitic at dijana.vest.hr Sat Jul 6 08:05:58 2002 From: imunitic at dijana.vest.hr (Ivica Munitic) Date: 6 Jul 2002 12:05:58 GMT Subject: Tkinter Text Widget Tag Problem Message-ID: Hello boys and girls :))) I have a question about the Text widget in Tkinter. I have a link tag called hlink in my class(self.text.tag_configure("hlink", foreground="blue")), and a alink when i go over a link with the mouse pointer self.text.tag_configure("alink", underline=1, foreground="red"). The problem is when two links are to close to each other then the event never occures. I have a and methods. def onEnter(event): start, end = self.text.tag_prevrange("hlink", self.text.index("@%s,%s" % (event.x, event.y))) self.text.tag_add("alink", start, end) self.start, self.end = start, end def onLeave(event): self.text.tag_remove("alink", self.start, self.end) When two links are positioned like this: link1 link2 the Leave event of the first one never occurs if i go down with the cursor from link1 to link2. But when i move the cursor away form the the links the Leave method occurs, and I get back the blue foreground with no underline. Can any one tell me how to resolve this problem. Tnx in advance!! From i.linkweiler at gmx.de Wed Jul 3 13:10:06 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Wed, 03 Jul 2002 19:10:06 +0200 Subject: PythonWin + other GUIs = CRASH! Message-ID: <3D232FEE.3010606@gmx.de> Hi, when using the PythonWin IDE with other GUI-Toolkits (Qt, wxPython, Pygame), the application crashes or freezes when running them with "file->run". Is it possible to avoid this? Do you know other IDEs, which can be used with [Qt, wxPython, Pygame]? Ingo From akineko at pacbell.net Wed Jul 3 04:07:18 2002 From: akineko at pacbell.net (Aki Niimura) Date: 3 Jul 2002 01:07:18 -0700 Subject: A problem with urllib References: <3D1FD7A1.F265FC8E@engcorp.com> <3D2163E3.3050605@nowhere.org> <3D224BFF.9090409@nowhere.org> Message-ID: Bryan Olson wrote in message > Ah, the base64.encodestring() includes a "\n" at the end of the output. > In the version below, I strip it off. Bingo! It worked. (I added .strip() to my previous test script) Thank you for taking time to solve this mystery which I have tried to solve for more than a half year. This turned out to be an interesting investigation. Best regards, Aki Niimura From rgc at swissonline.ch Thu Jul 4 22:09:31 2002 From: rgc at swissonline.ch (Roy Culley) Date: Fri, 5 Jul 2002 04:09:31 +0200 Subject: Sorting a dictionary by value Message-ID: I'm sorry if this is a novice question but I have searched google and the python FAQ and haven't found an answer. I have a large dictionary where I want to sort and print based on the largest values in a dictionary and not the keys. Now in perl you can do: @Keys = sort { $Hash{$b} <=> $Hash{$a} } keys %Hash; Is there any such magic for python? From max at alcyone.com Thu Jul 18 18:39:29 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 Jul 2002 15:39:29 -0700 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <3D374109.1040202@mxm.dk> Message-ID: <3D3743A1.911F9687@alcyone.com> Max M wrote: > I don't especially like "self" myself. But wouldn't it be easy enough > to > just: An obvious issue is what happens with respect to bound and unbound methods. The self argument is often implicit in normal work, but it _is_ there, and needs to be set up properly. In your scheme, what happens when you write: def f(x, y): ... # not a method, no self, implicit or explicit class C: def m(x, y): ... # method, implicit self g = f # what does this mean? c = C() um = C.m um(c, ...) # how do I call this? bm = c.m bm(...) # or this? Trying to hide the self argument is destined to only lead to massive confusion. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From jonathan at onegoodidea.com Tue Jul 16 07:06:29 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 16 Jul 2002 12:06:29 +0100 Subject: namespaces in python References: Message-ID: On 16/7/2002 8:32, in article w_PY8.102605$xy.35029121 at twister.socal.rr.com, "Jeff Davis" wrote: > Is there a way to put functions and variables in a different namespace > without putting it in a seperate file or instantiating a new object? Is > there a way to have static methods that don't require instantiating the > object first? If you're using Python 2.2 with metaclasses, you can do this: >>> class namespace( object ): ... def __init__( self, name, bases, dict ): ... self.__name = name ... self.__dict__.update( dict ) ... def __repr__( self ): ... return '' % self.__name ... >>> >>> class foo: ... __metaclass__ = namespace ... def hello( name='World' ): ... print 'Hello', name ... CONSTANT = 5 ... >>> foo >>> foo.hello() Hello World >>> foo.hello( 'Jonathan' ) Hello Jonathan >>> foo.CONSTANT 5 >>> Note that foo is not actually a "class" as such. It's an instance of 'namespace', which isn't a proper type. This could also be extended to do something useful with the bases so that you can inherit from other namespaces. Metaclasses allow you to pull all manner of tricks with 'class' ;-) [As an aside, while I know this is a horrible idea, it would be ultra-cool to be able to use syntax like: ( [ ...] ): ... to mean: class ( [ ...] ): __metaclass__ = ... so that you could just have written for the above: >>> namespace foo: ... def hello( name='World' ): ... print 'Hello', name ... I can think of nummerous other examples like this one.] I'll-make-Guido-timothy-the-day-he-introduced-metaclasses--ly y'rs, Jonathan From aleax at aleax.it Fri Jul 26 10:39:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 14:39:27 GMT Subject: Solaris 9, python 2.1.3, find References: Message-ID: Marc Petitmermet wrote: ... > find /usr/local -follow -name libtk8.3.so -print > > the library is found. The man page for "find" states that follow is > "Always true. Causes symbolic links to be followed". I think that > this is not true because in may case /usr/local is a link to /p1/local > on a second disk. By "always true", find's manpage does NOT mean that it's indifferent whether you specify -follow or not. It means that, if you DO specify it, it evaluates to 'true' -- remmember that the find command is performing a boolean and, left to right and short-circuiting, on its arguments (there are even explicit -o etc...). Alex From mertz at gnosis.cx Mon Jul 8 14:59:36 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Mon, 08 Jul 2002 14:59:36 -0400 Subject: Is there a re guru out there? References: Message-ID: |Krzysiek Czarnowski wrote: |: I try to convert some LaTeX constructs to "plain" equivalents like \(,\) --> |: $, \[,\] --> $$ |: and \frac{...}{...} --> {...\over ...}. The \frac bit appeared not to be |: trivial since ... should be balanced with respect to { }. Daniel Yoo wrote previously: |Parsing is a large topic, so someone more competent than me should |handle it. *grin*. But here's an article that talks about parsing |with Python: | http://www-106.ibm.com/developerworks/linux/library/l-simple.html?dwzone=linux Although I'm not sure I can sell myself as a parsing expert, I do agree that a parsing solution is the right way do this nested matching. Moreover, I have expanded somewhat on my earlier SimpleParse article that Yoo references. Take a look at Chapter 4 of my _Text Processng in Python_ book draft, which looks a bit at parsing theory (not profoundly, just as a practical review) and state machines, then at mx.TextTools, SimpleParse, and PLY. The whole book (as much as I've written) is at: http://gnosis.cx/TPiP/ And the appropriate chapter, a click past that. -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From nospam at any.time Thu Jul 4 20:10:05 2002 From: nospam at any.time (Some One Else) Date: Fri, 05 Jul 2002 00:10:05 GMT Subject: Math irregularity ... is this normal? Message-ID: Hello! I just compiled and installed Python 2.2.1 on Linux-Mandrake 8.0. When I do the following: >>> 2/5.0 0.40000000000000002 In 'Learning Python', a similar example says I should get the more logical answer of 0.4. Did I install something wrong? I can see where this could result in creeping math errors. Thanks! (respond to group -- not despammed email) From gerhard.haering at gmx.de Mon Jul 29 10:22:25 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 29 Jul 2002 14:22:25 GMT Subject: Newbie question about dictionaries References: Message-ID: In article , Vladimir Cherepanov wrote: > I've read that dictionaries are implemented as hash tables. Is there any way > to specify a hash function? Sure there is. You need to implement a __hash__ method. It's described here: http://www.python.org/doc/current/ref/customization.html Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From ivan at xpeNOSPAMnguin.com Fri Jul 12 15:48:19 2002 From: ivan at xpeNOSPAMnguin.com (Ivan Kozik) Date: Fri, 12 Jul 2002 12:48:19 -0700 Subject: PyOpenGL (OpenGL.Tk) conflicts with Tkinter (main program) Message-ID: <3d2f327f$1_2@nopics.sjc> Hello, I'm having problems using a PyOpenGL canvas inside an existing program. The OpenGL canvas is not supposed to be run at startup, but is supposed to be executed by a button. Here is the GL portion of the code: from OpenGL.GL import * from OpenGL.Tk import * from OpenGL.GLUT import * class 3D_Plot: def __init__(self, rc, list_of_objects, dict_of_objects, \ annot_D, annot_R, annot_G, annot_B): print "Message from class 3D Plot" print dict_of_objects It doesn't matter that it doesn't do anything yet, because when I start the program, the main program window AND a second canvas shows up. The second canvas has the title of "tk" and freezes the rest of the program. How would I make it completely independent? None of the examples show how to put it in an exisiting program. Any help would be greatly appreciated. Thanks, Ivan From aleax at aleax.it Thu Jul 11 03:00:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 07:00:05 GMT Subject: Python in the enterprise: Pros and cons References: <7xbs9fta42.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: ... > Yes, those are documentation gaps. You have to actually go out buy > chunks of dead tree pulp in order to use this documentation, and then > let it encroach heavily into your working/living space if you want to > keep it around for future reference. To me, these problems greatly Untrue: safari.oreilly.com can give you access to many books without any tree slaying and without requiring you to set a foot out of the door -- and your working/living space remains uncluttered, too. You do have to pay O'Reilly some money to use the service, though:-). Alex From percy at thunderbolt.ee.itb.ac.id Tue Jul 23 02:13:38 2002 From: percy at thunderbolt.ee.itb.ac.id (Percy Tambunan) Date: Tue, 23 Jul 2002 13:13:38 +0700 (JAVT) Subject: good books Message-ID: what is a good book in python, If i can only afford to buy just one book? From ld at nospam.com Mon Jul 1 20:11:17 2002 From: ld at nospam.com (news) Date: Tue, 02 Jul 2002 00:11:17 GMT Subject: File read problem in Windows Message-ID: f = open('myfile,'r') a = f.read(3072) When I do a len(a) I only get 634 bytes. It doesn't seem to want to grab the full 3072. This ONLY happens in windows...when I run my program in Linux I get the full 3072 and everything works fine! Any ideas? Thnx...Larry From charles_mantha at hotmail.com Sat Jul 6 14:57:29 2002 From: charles_mantha at hotmail.com (Charles Mantha) Date: Sat, 6 Jul 2002 14:57:29 -0400 Subject: problems with a for loop (noobie) References: <1IsV8.42194$Fc1.850199@wagner.videotron.net> Message-ID: > > ps : and for some reason, the output is not the same as in the tutorial >> when > > I try this. > > This is kind of hard to explain if we don't see the output that you saw. > Are you certain you typed it exactly as it appeared in the tutorial > (including indentation)? This is what I get : for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' 3 is a prime number 4 equals 2 * 2 5 is a prime number 5 is a prime number 5 is a prime number 6 equals 2 * 3 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 8 equals 2 * 4 9 is a prime number 9 equals 3 * 3 While the tutorial says : >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 From prema at prema.co.nz Sun Jul 21 04:22:23 2002 From: prema at prema.co.nz (Prema) Date: 21 Jul 2002 01:22:23 -0700 Subject: Pmw Inconsistencies -- Any ideas ?? References: Message-ID: Jeff ! Just public acknowledgement! Since your email my Pmw blues are over. I love it.! Thanks heaps Greg too ! Much appreciated Kind regards Mike jepler at unpythonic.net wrote in message news:... > On Thu, Jul 18, 2002 at 08:06:35AM +0000, Mike MacDonald wrote: > > ##Error message: > > ## Traceback (most recent call last): > > ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 1, in ? > > ## import Pmw > > ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 11, in ? > > ## root=Pmw.initialise() > > You're bound to have problems when you have two modules with the same name. > Here, it looks like you're running the file "Pmw.py" which tried to import > the module "Pmw". > > Jeff From b.maryniuk at forbis.lt Tue Jul 9 06:16:48 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 12:16:48 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: References: Message-ID: <200207091216.48782.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 11:56, Boudewijn Rempt wrote: > It's part of the kdebindings module: > http://developer.kde.org/language-bindings/java/index.html AFAIK, QT isn't KDE, right? It actually, *is*, but You can not run KDE so far simply on Winblows or MacOS or somewhere else as You can do this with wxWindows or Tk. And you can not use Java for very small and fast programs (console use) -- it'll start a half of hour... And also not for very-very-very large projects with GUI and other stuff. I've seen no one success project, written on Java. Even all the tools from the Oracle 8i-9i -- they always mostly fails or crashes in the middle of the work (JDeveloper, Oracle Installer, OAS etc). :( -- Sincerely yours, Bogdan M. Maryniuck "...Deep Hack Mode--that mysterious and frightening state of consciousness where Mortal Users fear to tread." (By Matt Welsh) From fredrik at pythonware.com Sat Jul 27 16:17:55 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Jul 2002 20:17:55 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: Carl Banks wrote: > I'm sorry if it seemed like I was trolling. Oh, sorry, I didn't mean you. I meant the "lambda lovers have childhood traumas" guy. If he cannot defend his position with- out stuff like that, it must be a pretty worthless position. If you like lambdas, use them. All the best pythoneers do, so why shouldn't you? And as you noted, they're great when you need something simple, and don't want to break the flow. And when you find that you have to refactor, it's not that hard to turn that comment into a def line, add a newline and type "return". (Premature refactoring is the root of all evil, etc. ;-) Oops, my typometer just rolled over. time to stop worki From robert_kuzelj at yahoo.com Wed Jul 3 02:41:53 2002 From: robert_kuzelj at yahoo.com (Robert Kuzelj) Date: 2 Jul 2002 23:41:53 -0700 Subject: "my brain hurts" or is isinstance broken? References: Message-ID: hallo walter, thanks for the reply. >> class metatype(type): pass >> >> class A1: pass >> class B1(object): pass >> class C1: __metaclass__ = metatype >> >This is not a bug, it's one of the main features of new style >classes. what is a feature of 2.2? that you cant distinguish between a class and an instance? hardly! >> of what type are B1() and C1()? > B1 and C1. i am very well aware of this. but it doesnt solve my problem. because C1.__class__ =~ metatype C1().__class__ =~ C1 there is no _direct_ possebility to find out if a given object is an instance or a class (new style one that is). well there is a workaround: if not isinstance(obj, types.ClassType) and \ not isinstance(obj, types.TypeType): print "its an instance!" but isn't explicit better than implicit? i think i have read this somewhere on the python pages? didnt i? ;-) imo it should be very clear that there is a difference between the following two statements: class A(object): #defines a class which is an object of type type. A() # creates an instance and the information on how the object was created should be explictly accessibly. ciao robertj From max at alcyone.com Sat Jul 27 19:31:09 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 27 Jul 2002 16:31:09 -0700 Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <2259b0e2.0207271526.1214228@posting.google.com> Message-ID: <3D432D3D.9E265A18@alcyone.com> Michele Simionato wrote: > I know a print statement cannot stay in a lambda function, however as > a > newbie I ask : why ? Because a lambda is an expression, not a statement. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From kp at kyborg.dk Fri Jul 12 05:22:51 2002 From: kp at kyborg.dk (Kim Petersen) Date: Fri, 12 Jul 2002 11:22:51 +0200 Subject: Python in the enterprise: Pros and cons References: <3D2D4008.7050207@kyborg.dk> Message-ID: <3D2E9FEB.2070607@kyborg.dk> Laura Creighton wrote: > Kim Petersen: > > >>Learning Python is straight forward, and doesn't scare of a COBOL >>programmer in the way that C++ or Java would. >> > > > Is getting a float when they wanted a fixed-decimal a problem? It seems that Cameron already answered this one ;-) But i should say that this hasn't become a problem here yet, as the programmers know that there will be sacrifices on both ends of this conversion (Cobol -> Python). I have a feeling that i will be forced to write a some kind of framework for the programmers, to encompass some of the output formatting types in Cobol and possibly also a transparent class to do fixed decimal... But we haven't reached that stage yet, first things first ;-) And in this case it was extending the Cobol runtime with the ability to call python programs and functions dynamically (we're using RM-Cobol-85 7.1) - this is firmly established at this point - and i'm considering releasing this to the wider community as open-source (i'm for it - but i'm not sure about my Boss ;-)) - Unfortunatly the extension cannot do the reverse (eg. performing cobol paragraphs (functions)) because of the way the language is setup. But type conversion between Cobol and Python is (almost) transparent (unfortunatly it cannot be 100% transparent, as Cobol calls subprograms with arguments by reference). > > Laura Creighton > > From skip at pobox.com Wed Jul 3 08:10:33 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Jul 2002 07:10:33 -0500 Subject: Syntax Error at end of file In-Reply-To: <3D22E6FE.9070705@thomas-guettler.de> References: <3D22E6FE.9070705@thomas-guettler.de> Message-ID: <15650.59833.457366.303859@12-248-8-148.client.attbi.com> Thomas> But it would be very nice if the python parser would tell what Thomas> input token it was searching for, and where the start token is. In a similar thread which occurred just a few days ago it was observed (by Tim Peters, I think) that the set of acceptable characters at any particular point in the parse is big, so enumerating them in the error message would be counterproductive and would just serve to confuse the issue in most cases. Most people don't add huge gobs of text to developing source code between debug runs, so if you get a SyntaxError, it's almost always in the code entered most recently. This helps narrow down the possible sources of the error dramatically, and with the exception of things that come in pairs and which can extend parsing of a construct across multiple lines (triple quoted strings and various paren-list things) the cause of most SyntaxErrors is generally within a line or two of the point of detection. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From rs at onsitetech.com Tue Jul 16 15:03:48 2002 From: rs at onsitetech.com (Robb Shecter) Date: 16 Jul 2002 19:03:48 GMT Subject: Getting SOAP working w/ Activestate Python? Message-ID: <3D346DB4.5070401@onsitetech.com> Hi, I've got Activestate Python installed (Python 2.2.1), and used the Python Package Manager to install the two packages: ZSI 1.1 PyXML 0.7 However, I haven't gotten any demos to work yet. These two packages are the two available from Activestate. Are they compatible? Why should I have to install PyXML explicitly? Isn't XML support built in to the latest version of Python? Thanks, Robb From otijim at yahoo.com Mon Jul 15 15:22:33 2002 From: otijim at yahoo.com (Jake R) Date: Mon, 15 Jul 2002 19:22:33 GMT Subject: Common list in distinct objects' Message-ID: <3d331fa9.361390031@news.byu.edu> I ran into this today. I created a class that contains a list attribute. I then add an element to the lists of each object. So each object should have a list with one element. However, the result I get is that, appearantly, both objects are sharing the same list. So, instead of two lists with one element I get one list with two elements. --In Addition------------------------------------------ This only seems to occur when I use a default null list in my __init__ method. If I change the object declaration lines to: a = testList([]) b = testList([]) Then two separate lists are created as expected. Or, if I remove the default value in the 'def __init__' and replace the line with: self.theList = [] I also get the expected two lists behavior. Can anyone help clarify this for me. --EXAMPLE----------------------------------------- class TestList: def __init__(self, mylist=[]): self.theList = mylist def printList(self): for x in self.theList: print x def addItemToList(self, item): self.theList.append(item) ## Program a = TestList() b = TestList() a.addItemToList("This is list of A") b.addItemToList("This is list of B") print "Print a" a.printList() print print "Printing b" b.printList() From duncan at NOSPAMrcp.co.uk Tue Jul 9 12:31:54 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 16:31:54 +0000 (UTC) Subject: sorting many arrays from one... References: Message-ID: "Shagshag13" wrote in news:ager5l$ldguf$1 at ID-146704.news.dfncis.de: > driven, *others = map(list, zip(*aux)) > > but this last line don't work and i don't know how to fix it... unless > i replace it by : > > return map(list, zip(*aux)) You can get back driven and others by: others = map(list, zip(*aux)) driven = others.pop() but it all depends on what you want to do with the results. You might find it just as easy to do the return statement as (presumably) most of the time you call your generic function you know how many parameters you passed and therefore how many results to expect. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From mgilfix at eecs.tufts.edu Tue Jul 30 13:14:14 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Tue, 30 Jul 2002 13:14:14 -0400 Subject: Cookbook: Associating multiple values with each key in a dictionary In-Reply-To: <20020730171536.A992@bork.demon.nl>; from egbert@bork.demon.nl on Tue, Jul 30, 2002 at 05:15:37PM +0200 References: <20020730171536.A992@bork.demon.nl> Message-ID: <20020730131414.C7503@eecs.tufts.edu> On Tue, Jul 30 @ 17:15, Egbert Bouwman wrote: > On page 9 of the free chapter 01 of their cookbook > alex and associates present a way to associate multiple values > without duplications to a dictionary: > d2 = {} > d2.setdefault(key, {})[value] = 1 > This produces nested dictionaries with unique keys, > however with values that I don't need. > > I prefer a solution with lists, as in the one with duplications allowed: > d1 = {} > d1.setdefault(key, []).append(value) > > This function creates a multivalued list without duplications: > > def keyplus(dic,key,value): > dic.setdefault(key, []) > if value not in dic[key]: > dic[key].append(value) > > but now I have a feeling that some one-liner is possible. If not, > don't we need then a list method 'append_if_not already-there' ? The beauty of using dictionaries is that you can always just do the 'setting' operation, regardless of whether or not the item is in the dict and still have the result be unique (because it always hashes to the same value). The problem with the list method is that in order to keep your list unique, you have to check that the item is not already in the list, which can be expensive. I'm not really sure why you prefer the list method. Is there something that you can't accomplish with the nested dictionaries? Are you looking perhaps for some ordering? If so, then you're right, the dict solution might not be best. However I would suggest using a dict as a look up mechanism to determine whether the item is in the list already before the append. The result should be considerably faster. -- Mike From glingl at aon.at Sat Jul 20 10:46:52 2002 From: glingl at aon.at (Gregor Lingl) Date: Sat, 20 Jul 2002 16:46:52 +0200 Subject: Lists & two dimensions References: Message-ID: <3D3977DC.1040609@aon.at> Pichai Asokan schrieb: > I am a trainer and in a training session a participant came up with a > problem that stumped me: > > Here is the code snippet that isolates what I want: > -------------------- > board = [[-1] * 3 ]*3 > print board > board[1][2] = 'x' > print board > -------------------- > Output > ----------------------- > [ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ] > [ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ] > ----------------------- > > I thought > board = [[-1] * 3 ]*3 > should give me a list of 9 elements; > but ... if you got a list of 9 elements the expression board[1][2] = 'x' wouldn't make sense. > > What is going on? > Where can we read more to understand what is goingg on? What you get is a list of three identical elements (i. e. three pointers to the same three element list) like: >>> l = ['a','b','c'] >>> v = [l]*3 >>> v[1][2]='x' >>> v [['a', 'b', 'x'], ['a', 'b', 'x'], ['a', 'b', 'x']] >>> a possible workaround: >>> v = ['a','b','c'] >>> v2 = [] >>> for i in range(3): v2.append(v[:]) # copy of v >>> v2 [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']] >>> v2[2][0]='z' >>> v2 [['a', 'b', 'c'], ['a', 'b', 'c'], ['z', 'b', 'c']] >>> I'm sure there ar more elegant ways ... Gregor > > P Asokan From fredrik at pythonware.com Mon Jul 15 15:06:57 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Jul 2002 19:06:57 GMT Subject: 8 Queens Problem References: Message-ID: Grant Edwards wrote: > Or, if you like obvious silliness, here's one with a Tkinter > user-interface that shows the chess-board as it solves the > problem... > > ftp://ftp.visi.com/users/grante/python/queens.py if slightly silly is silly enough, there's a console version in my windows console package: http://effbot.org/efflib/console/index.htm this is based on Guido's sample implementation in Python's demo directory (look under Demo/scripts). From StRanGy at dijana.vest.hr Sat Jul 6 09:16:18 2002 From: StRanGy at dijana.vest.hr (Ivica Munitic) Date: 6 Jul 2002 13:16:18 GMT Subject: Tkinter Text Widget Tag Problem References: Message-ID: In article , Ivica Munitic wrote: > def onEnter(event): > start, end = self.text.tag_prevrange("hlink", > self.text.index("@%s,%s" % (event.x, event.y))) > self.text.tag_add("alink", start, end) self.text.tag_raise("alink") This i forgot to add in the original post :))) Sorry > self.start, self.end = start, end -- --------------------------------- # RealName: Ivica Munitic # E-Mail: imunitic at vest.hr # ICQ: 36877532 --------------------------------- From kristian.ovaska at helsinki.fi Sat Jul 27 05:10:00 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Sat, 27 Jul 2002 12:10:00 +0300 Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: <5ro4kuse28hla4hvg1i3lg0aljh64pe3ue@4ax.com> "David LeBlanc" : >> It's strange that while regular languages are a small subset of real, >> Turing-complete languages, >I may be wrong about this, but I don't think regular expressions qualify as >turing complete. No branching for one thing... You're right and that's what I ment, too. "Language A is a subset of B" means that everything you can express in A you can also express in B, but the reverse is not necessarily true. Regular languages are rather limited: they can't even recognize balanced parenthesis: (), (()), ((())), etc. -- Kristian Ovaska From eric.brunel at pragmadev.com Mon Jul 8 05:37:14 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 8 Jul 2002 09:37:14 +0000 Subject: Getting Process List On *nix References: Message-ID: Donn Cave wrote: > For sure. The traditional UNIX "ps" needs kernel structures that can > move or change even between minor releases of the same platform, it's > the farthest thing from portable. Unfortunately, the ps command isn't > much fun either - command line and output vary substantially between > platforms and aren't designed for computer analysis. Missing columns, > columns that run together, etc. You'll end up having to locate the > columns in the header line, and use that as a reference for each line. Apparently, the use of the -o option on ps seems a bit more portable. I tried: ps -A -o pid -o user -o args on Linux and Solaris, and it works on both. Since Solaris has a long history of messing up with ps options, it may be the most portable solution you can get. And you can choose the fields you want to see too... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From wadebk at nswc.navy.mil Wed Jul 17 11:32:12 2002 From: wadebk at nswc.navy.mil (Brian) Date: 17 Jul 2002 08:32:12 -0700 Subject: netCDF in 2.2 References: <57fe7929.0207120253.37865e70@posting.google.com> Message-ID: <57fe7929.0207170732.1a2deeba@posting.google.com> wadebk at nswc.navy.mil (Brian) wrote in message news:<57fe7929.0207120253.37865e70 at posting.google.com>... > I'm a relative newbie in Python and I can't get netCDF to work under > 2.2 on Windows. I found a .pyd file that makes it work under 2.1 > (scientific_netcdf.pyd), but it doesn't work under 2.2. Does anyone > have the equivalent version of this file or another easy solution? I can't believe that nobody else has run into this before. Please, if someone knows how to do this tell me. From SBrunning at trisystems.co.uk Wed Jul 3 10:03:10 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 3 Jul 2002 15:03:10 +0100 Subject: Useful RE patterns (was: Variable Interpolation - status of P EP 215) Message-ID: <31575A892FF6D1118F5800600846864DCBD4A7@intrepid> > From: Fredrik Lundh [SMTP:fredrik at pythonware.com] > Simon Brunning wrote: > > > > From: Mike C. Fletcher [SMTP:mcfletch at rogers.com] > > > I'm actually doing something very similar for SimpleParse > > > > Interesting project. But you might want to call it something > > else - there is already a SimpleParse. See > > > ml > > umm. one might think that mcfletch at rogers.com might know > about something available from members.rogers.com/mcfletch... Ah. Yes. Hmmm. Didn't spot that. It certainly *sounded* like a different project, though - using REs rather than mxTextTools. Ah well, never mind, Simon makes a plonker out of himself again... Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From davegaramond at icqmail.com Tue Jul 23 10:23:11 2002 From: davegaramond at icqmail.com (David Garamond) Date: Tue, 23 Jul 2002 21:23:11 +0700 Subject: Queue.Queue examples? Message-ID: <3D3D66CF.9060603@icqmail.com> despite having read the manual, i'm still totally ignorant on the basic concept of Queue and how can it be used to safely pass objects between two (or more) threads. could someone enlighten me? -- dave From suresh at mspl.net Wed Jul 24 04:42:40 2002 From: suresh at mspl.net (Suresh Ananthan) Date: 24 Jul 2002 01:42:40 -0700 Subject: convert from utf-7 encoded text to normal text? Message-ID: Hello List, I'm working on C/C++ platform. I have recieved mail in the following format. There's utf-7(or utf-8) encoded text. ------=_NextPart_000_0057_01C2323C.D9CAFA60 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset="utf-7" test+AEA-qa21.com+ADs- dig+AEA-qa21.com test+AEA-qa21.com+ADs- dig+AEA-qa21.com I hope that this is a unicode format. I need to convert (or) decode this string. What algorithm i should use? (or) any other sample program available for convert this unicode string to normal text?????How to decode this text to get normal chars? I'm newbie and tried some API / C RTL functions, but did not get correct result, so detailed answer will be very helpfull. Please... Advance Thanks Regards Suresh ************************************************************************ Suresh Ananthan, MicroWorld Technologies Inc., Mumbai. India Email: suresh at mwti.net (or) suresh at mspl.net Phone: 022 8265701/05 Ext:206 *********************************************************************** From sholden at holdenweb.com Tue Jul 2 08:55:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 2 Jul 2002 08:55:02 -0400 Subject: cpickle and classes References: Message-ID: "Guy" wrote in message news:c07d0edc.0207020330.5f0d9ec5 at posting.google.com... > Been reading alot of the messages posted to the python groups about > cpickle, (old and new). Below I've got an exsample bit of code.(Please > don't comment on this code its just AN EXAMPLE.) > > -------------------------------------------------------------------------- -- > > import cPickle > > class mill: > time = "" > date = "" > name = "" > flourUsage = flour() > add =[""] > > class flour: > ammount = "" > date = "" > > data = mill() > > data.time = "1" > data.date = "2" > data.name = "3" > data.flourUsage.ammount = "4" > data.flourUsage.data = "5" > data.add=["adsfads","dsgdsfgdf"] > > Data001 = cPickle.dumps(data, 1) > Data002 = cPickle.loads(Data001) > > print Data002.time > print Data002.date > print Data002.name > print Data002.flourUsage.ammount > print Data002.flourUsage.date > > file = open(os.getcwd()+"\\test.dump", "w") > cPickle.dump(Data002, file) > file.close() > > -------------------------------------------------------------------------- - > > When this is run it puts some stuff to screen and file : No it doesn't. Sorry, I have to comment on the code, because it just doesn't run as presented. When the interpreter processes the definition of class mill it calls class flour, which is undefined, so you get a NameError exception. Given this failure it casts some doubt on the veracity of the other problems you compain about... However, let's rearrange the code so the definition of flour comes first, then see what happens. interesting. Now we see that "os" isn't defined due to a missing import. Sorry, try again. See further notes below.. > > Screen display : > > >>> 1 > >>> 2 > >>> 3 > >>> 4 > >>> 5 Now, this last line of output just doesn't appear. Please note that you are setting data.flourUsage.date in the class definition, but setting data.flourUsage.data in the main code. > > File display : > > (i__main__ > mill > p1 > (dp2 > S'date' > S'2' > sS'add' > (lp3 > S'adsfads' > aS'dsgdsfgdf' > asS'name' > S'3' > sS'time' > S'1' > sb. > > If you look at the file there is NO sign of the > Data002.flourUsage.ammount > and Data002.flourUsage.date values or var names. > > Why ? > Can cpickle not handle this ? > Is there anything I can do to improve the code to make cpickle work ? > Are there any work arounds for this ? > Maybe suggestions of how to do this in a different way. Perhaps if you were to present a correct example we could set you stright. Suffice it, at this stage, to say that the class definitions are extracted from the defining module by executing the class definition. Let's see what happens when you show us the code you actually ran. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 10:04:39 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 09:04:39 -0500 Subject: Help On file IO References: Message-ID: >>>>> "jayant" == jayant kawadkar writes: jayant> I want a help on File IO ,as I 'm new to Python jayant> langauge. As I want to use the API : jayant> char* PyModule_GetFilename(PyObject *module) jayant> in my python programm jayant> What should I import for that I can use this . jayant> Now it is giving the error that: jayant> PyModule_GetFilename is not defined. Did you include /some/dir/lib/your-python/config/config.c (eg. /usr/local/lib/python2.1/config/config.c)? This file includes Python.h, which includes moduleobject.h which defines PyModule_GetFilename. You'll also need to link with the python system, eg /usr/local/lib/python2.1/config/libpython2.1.a Take a look at http://www.python.org/doc/current/ext for more info. The chapter "Extending and Embedding Python" in the *Python Essential Reference* by David Beazley is also helpful. John Hunter From aleax at aleax.it Wed Jul 24 11:46:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 15:46:44 GMT Subject: error code References: <3d3ebee7$0$4203$afc38c87@news.easynet.fr> Message-ID: ferreira jorge wrote: > Hi > > I want to get the code of an error . > > how can I do that ? > > With "sys.exc_value" and "sys.exc_type" I have a String . > But I want a Integer > > Thanks Most exceptions have no 'integer' associated with them, but if you have for example an instance of IOError, it has an errno attribute that's probably what you want. Alex From marklists at mceahern.com Fri Jul 12 10:59:52 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 09:59:52 -0500 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: Message-ID: > Just adding my tuppence worth. Remember that whitespace can be added > horizontally too eg. > > for line in xreadlines.xreadlines(sys.stdin): > if line[0] == '#' : continue > elif line[:5] == 'DATE:' : yield ('DATE', scan_date (line)) > elif line[:5] == 'INTF:' : yield ('INTF', scan_intf (line)) > elif line[:4] == 'ETH:' : continue # for now > elif line[:4] == ' ' : continue > else : yield ('DATA', scan_data (line)) For what it's worth, PEP 8 recommends using startswith()/endswith() instead of slicing for prefix/suffix checking. Btw, would something like this better express the structure or is it just obfuscation? for line in xreadlines.xreadlines(sys.stdin): handler = get_handler(line) handler.handle(line) // m - From nickone at 263.net Mon Jul 1 08:12:04 2002 From: nickone at 263.net (nicholas wang) Date: Mon, 1 Jul 2002 20:12:04 +0800 Subject: How to triger a timer/signal to a running program Message-ID: Hi,all My task is to kill a program when it runs more than a limited time. My plat is Linux7.1; I've tried Csh to make it using ps ... ; then kill this program. But it will get extra messages to stdout. Of course, use "limit" command also works. But both are not perfect. I know Perl get a command "alarm" will do such a job I'm searching a Python counterpart. Does anyone know what it is? My idea about this job is: ( in a python shell ) 1. mark a signal to a specific program. 2. run this program 3. if time exceeds limit(set before run), the shell will kill it. 2. continue to run the remained commands. Thanks to you!! From glingl at aon.at Sat Jul 13 20:02:49 2002 From: glingl at aon.at (Gregor Lingl) Date: Sun, 14 Jul 2002 02:02:49 +0200 Subject: structs in python References: Message-ID: <3d30bfba$0$33064$91cee783@newsreader02.highway.telekom.at> "Paul Magwene" wrote in message news:pan.2002.07.13.21.27.21.238063.7266 at snet.net... > On Sun, 07 Jul 2002 00:12:00 -0400, Kevin O'Connor wrote: > > > > > It would be useful if there were a simple way of declaring a class with > > only member variables (and no methods); an object more akin to a C > > struct. > > > > What if a syntax like the following were permitted: > >>>> p = ( .x = 10, .y = 11, .color = 'blue') > How do you like this one: >>> class Struct: def __init__(self, **args): self.__dict__=args >>> p = Struct(x=10,y=11,color='blue') >>> p.x 10 >>> p.y 11 >>> p.color 'blue' >>> p.__dict__ {'color': 'blue', 'y': 11, 'x': 10} >>> p.color='red' >>> p.__dict__ {'color': 'red', 'y': 11, 'x': 10} >>> p.color 'red' >>> From dcinege at psychosis.com Sun Jul 28 23:57:21 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Sun, 28 Jul 2002 23:57:21 -0400 Subject: lexing nested parenthesis Message-ID: <200207282357.21550.dcinege@psychosis.com> It's nice when you open up your reference book, and immediately find a section on what you want to do. It sucks large donkey rocks when that section is titled: "Difficulties and Impossiblies" (Mastering Regular Expressions) I've been playing with shlex, and think in my application I'm better off minimizing or avoiding it. Primarily I want to do search, evaluate, modify, and replace on a line by line basis. The diffculty comes with matching arbitrary nested constructs, IE nested parenthesis. IE if 1 and (var1 or ?(-d /etc/)): I want to find ?(.*), but not runneth under or over. Evaluating a token at a time will become disgusting. It also seems redundant as you can see it's the same parsing rules as Python has. (And in fact that is what the line will be converted to.) Can anyone recommend a 'Better Way'? I'm thinking maybe subclassing generate_tokens. Dave -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From huaiyu at gauss.almadan.ibm.com Mon Jul 8 17:25:22 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 8 Jul 2002 21:25:22 +0000 (UTC) Subject: Why isn't this a bug? References: Message-ID: Russell Blau wrote: >>>> c = 2/5. >>>> str(c) >'0.4' >>>> str((c,)) >'(0.40000000000000002,)' >If this is not a bug, however, it does raise a question about the design of >the language. Granted, I suppose one *could* define the operation of the >built-in function str() so that exactly the same value can result in >different string representations depending on the context in which the value >is found (i.e., a long that is inside a list "looks" different than one that >is not inside a list); then, the output shown above is not a "bug" but is >the way the feature was designed to operate. But why define your language >in such a way as to produce inconsistent output? I don't see any value in >doing so, and it seems vaguely un-Pythonic (although I admit my >Pythonic-ness expertise is very limited). Python has two levels of object-to-string conversions. The 'str' is often too vague - it cannot distinguish between 2.4 and '2.4'. This is not a bug - it has to make every string a fixed point (str(s)==s). The 'repr' is often too precise - it shows 2.4 as 2.3999999999999999. This is not a bug - it needs to have 'eval' as an inverse on simple objects. What is called for in most situations, and expected by most newbies, is a level of display that is somewhat in between - it shows 2.4 as 2.4 and '2.4' as '2.4'. >>> 2.4, '2.4', [2.4, '2.4'] (2.4, '2.4', [2.4, '2.4']) >>> print 2.4, '2.4', [2.4, '2.4'] 2.4 '2.4' [2.4, '2.4'] This is not hard to do (see below), but there is a view that the need is not great enough to warrant one more level of object-to-string conversion. >Anyway, if anyone is interested in *changing* this "feature" in a future >version, I will point out that it can be done fairly easily by adding >methods called "list_str" "tuplestr" and "dict_str" to the files >listobject.c, tupleobject.c, and dictobject.c, respectively. Each method >would be identical to the currently-defined methods "list_repr" "tuplerepr" >and "dict_repr" except that all calls to PyObject_Repr would be replaced by >calls to PyObject_Str. Simply changing 'list_repr' to 'list_str' alone is not good enough - it will not preserve the distinction between strings and numbers. Sometime ago I made a patch that adds a function 'disp' and magic method '__disp__' to handle this functionality. Altogether 48 files need to be changed, most only adding one item in a struct. If there is a concensus that this is worth it, I'll try to sell it to Python-dev. Huaiyu From b.maryniuk at forbis.lt Tue Jul 9 05:57:18 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 11:57:18 +0200 Subject: [OT] Corrections about Java In-Reply-To: <20020709094938.GA1489@lilith.my-fqdn.de> References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091137.11467.b.maryniuk@forbis.lt> <20020709094938.GA1489@lilith.my-fqdn.de> Message-ID: <200207091157.18646.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 11:49, Gerhard H?ring wrote: > Works for me. I meant: some_loop_forewer { try { break; } finally { continue; } } Perhaps 1.3.1 just fixed here... > Btw. Python had a similar problem in 2.0, IIRC. At least Python 1.5 no. -- Sincerely yours, Bogdan M. Maryniuck DOS: n., A small annoying boot virus that causes random spontaneous system crashes, usually just before saving a massive project. Easily cured by UNIX. See also MS-DOS, IBM-DOS, DR-DOS. (from David Vicker's .plan) From baas at ira.uka.de Sun Jul 21 03:49:01 2002 From: baas at ira.uka.de (Matthias Baas) Date: Sun, 21 Jul 2002 09:49:01 +0200 Subject: ANN: Pyrex 0.3.4 References: Message-ID: On Fri, 19 Jul 2002 08:21:30 GMT, "Fredrik Lundh" wrote: >Matthias Baas wrote: >> I thought you only need that if you import the dll through an >> import library which Python doesn't do. > >nope. without dllexport (or a DEF file or an exports directive to >the linker), Ah, now I see! I've checked for a def file, but I forgot about the linker options. I was always using the distutils and indeed, there's a "/EXPORT:initxtest" given to the linker. Thanks for clearing that one up. >the module's init function won't be exported. if it's >not exported, Python's PYD loader refuses to load the module. > >the correct solution (in 2.2 and earlier) is to use the DL_EXPORT >macro, which is set to the right thing for whatever platform you're >using. For the sake of understanding, I tried to use this macro, but it takes an argument. What's that argument supposed to be? I had a look in the Python source and also read about the macro USE_DL_EXPORT. Do I have to define that myself before including Python.h (but DL_EXPORT was defined even without defining USE_DL_EXPORT myself)? Well, whatever I tried, I didn't really manage to compile the module that way.... - Matthias - From menion at asylumwear.com Wed Jul 3 00:36:58 2002 From: menion at asylumwear.com (Joshua Schmidlkofer) Date: Tue, 02 Jul 2002 21:36:58 -0700 Subject: creating a file from python References: Message-ID: <3D227F6A.2000105@asylumwear.com> gollem wrote: >I want to create a file from inside a running python script. >I can do that using commands and touch but it won't work if the intended >name of the file is the value of a python variable. The file is created as >the variable name instead of the variable value. >I think I need to use a shell (bash) variable to do it but then the question >becomes how do I create that? thnx > > > > I think you mean: import os os.environ['MYFILE'] = 'myfilename' os.system('bash -c "myscript_that_needs_a_variable_named_MYFILE") js From dyoo at hkn.eecs.berkeley.edu Tue Jul 9 20:01:26 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 10 Jul 2002 00:01:26 +0000 (UTC) Subject: fonts too small References: Message-ID: VanPopering wrote: : I have slackware 8.1 installed and WindowMaker. : When I start idle.py the fonts are very small. : using rxvt, Xterm, or Nedit the fonts are fine. : How can I change the fonts in idle? Hi David, We can change IDLE's fonts by editing the 'config-unix.txt' file that's in IDLE's source directory. Likewise, if we're running on a Windows platform, we can modify 'config-win.txt'. If you're interested, you can read 'config.txt' for some more details about how IDLE reads sets up things like fonts, colors, and other options. Hope this helps! From charleshixsn at earthlink.net Mon Jul 1 13:13:10 2002 From: charleshixsn at earthlink.net (Charles Hixson) Date: Mon, 01 Jul 2002 10:13:10 -0700 Subject: Has Red Hat helped or hurt? References: <20020511151638.B24475@tummy.com> Message-ID: Sean Reifschneider wrote: > ... > > Yeah, in a perfect world people would write code that anticipated any > problems that future releases of the language might cause... When you > figure out how to do this, go ahead an submit a patch to Red Hat... > > Sean It's easy. Just install the python you want in /usr/local, and change your *USER* path so that /usr/local is searched before /usr/bin. Then as root, you can use the old version, and as the developer you can use the one you compiled from CVS (or whichever other version you want). And it you don't specify, you still reach the default install. If you're tight on disk space, you can either put a link to python2 in /usr/local, and have it be named python, or just use the old version. (Sorry, limited disk space is a limit.) -- -- Charles Hixson Gnu software that is free, The best is yet to be. From brian at sweetapp.com Tue Jul 9 18:06:14 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 9 Jul 2002 15:06:14 -0700 Subject: Why self? In-Reply-To: <3D2B5C2E.6050001@onsitetech.com> Message-ID: <000901c22794$d7c01cd0$bd5d4540@Dell2> Robb Schecter wrote: > 2. I'm down w/ polymorphism, man! I'm all over over it. There's a big > difference between type and class, for starters, and 'type' as in > 'implements an interface' is what I'm talking about. There is no interface concept in Python. Some attributes/methods exist and work as expected, others don't. And the difference between type and class depends on the language. In Smalltalk there is no difference. In Python the difference is disappearing. Cheers, Brian From opengeometry at NOSPAM.yahoo.ca Sat Jul 27 13:30:22 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 27 Jul 2002 17:30:22 GMT Subject: Two dimensional regexp matching? References: <3D4285A3.80407@tiscali.co.uk> Message-ID: In comp.lang.python Paddy wrote: > We already have the re module for regular expression matching on a string. > > I am looking for pointers to references/algorithms for regular expression matching for > files of tabular data, i.e. > > Table definition > ================ > 1) Samples from one point in the system appears in a column of the table. > 2) Samples encoded as characters > 3) All points in the system are sampled at the same time to produce successive > rows of the table > > So a system sampled at two points in successively may produce the following file: > > GH > DF > AS > QW > FF > SD > > I want to be able to do regular expression type searches within the file. Things like > Where can I find point1 == (D or G) then point2 == W within three samples and where the > next sample of point2 != the earlier sample of point1? > > That was a small example, in reality there is usually hundreds of points and tens of > thousands of samples in multi-megabyte files but I'd first like to see if anyone else has > considered this kind of 'two dimensional regexp matching' > > Note: I DO NOT have queries in the date on sample points. The queries will always be "Find > the range of sample times in which 'this' occurs". > > U have tried Google but without success - I don't know enough to think of a suitable > search phrase, or, (much less likely), Google doesn't have it ;-) > > > Thanks in advance, Paddy. You can extract the sample number (ie. row number) when match occurs, ie. point1 = (D or G) -> i = 1, 2 point2 = W -> i = 4 Then, do your math, i2 - i1 < 3 -> 4 - 2 matches. On Unix, I would do something like grep -n '^[DG]' -> will give you i = 1, 2 grep -n '^.W' -> will give you i = 4 I leave it up to you to code this in Python. It should be simple enough, depending on your data structure. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From fredrik at pythonware.com Mon Jul 22 11:26:18 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Jul 2002 15:26:18 GMT Subject: Scope of instantiated class References: <3D3ACCA6.7030002@lmco.com> <3D3B580F.20508@usa.net> Message-ID: Jim Jinkins wrote: > If the function returns the class to a name, that name holds the class > definition. You can instantiate objects of the class using the 'class > name' returned by the function. > > Or so says _my_ interpretation of the tutorial. how am I supposed to interpret "return the class to a name"? From gerhard at bigfoot.de Sun Jul 14 14:33:12 2002 From: gerhard at bigfoot.de (Gerhard Haering) Date: Sun, 14 Jul 2002 20:33:12 +0200 Subject: Pros/cons of various PostGres modules In-Reply-To: <200207141808.g6EI87r30238@localhost.localdomain> References: <545cb8c2.0207130852.74d88a5@posting.google.com> <20020714005307.GA4849@gargamel.hqd-internal> <200207141808.g6EI87r30238@localhost.localdomain> Message-ID: <20020714183312.GA2487@gargamel.hqd-internal> * Dave Reed [2002-07-14 14:08 -0400]: > > Gerhard wrote: > > PyGreSQL is IMO very badly maintained: there was a serious bug with > > cursor.fetchone() always returning the first row of the resultset, which > > made cursors basically unusable. It was known for over a year until > > somebody (me) got annoyed enough to take the half-an hour to look into > > the Python and C code, write a patch and submit it to the PostgreSQL > > developers. > > Thank you! I've been bit by this bug. PyGreSQL is the one that comes > with postgresql - correct? Yes, and patches and bug reports should go to the PostgreSQL project. > I found it worked fine on my Red Hat 7.3 system with their python 1.5.2 > rpm, but as soon as I tried to get it working with my installation of > python2.2 I had this problem. You were also using a different PostgreSQL version, then: the bugfix ended up as a last-minute fix in PostgreSQL 7.1.3. > Can you tell me where the source for this patch is so I can make certain > it's included in any postgresql installations I make? Just ensure you're using the PyGreSQL (in src/interfaces/python) from at least PostgreSQL 7.1.3. > As I understand it - please correct me if I'm wrong - I could install > pyPgSQL and it would work w/o any changes to my code (other than > importing that module) if I've stayed with the DB-API. Is this correct? In theory, you should only need to adjust the module and the parameters to the connection method. There are, however, certain differences, mostly wrt to different ways to access PostgreSQL-specific features like notifications or exotic SQL features like ARRAYs. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mwh at python.net Mon Jul 8 07:43:18 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 8 Jul 2002 11:43:18 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: Thomas Jensen writes: > Hello group (and list :-), They don't seem to be online yet, but Tim Couper's slides on "Selling Python to a Fortune 500 Company" from EuroPython might be interesting to read. They'll appear here: http://europython.zope.nl/sessions/presentations/all soonish (I hope). Cheers, M. -- Any form of evilness that can be detected without *too* much effort is worth it... I have no idea what kind of evil we're looking for here or how to detect is, so I can't answer yes or no. -- Guido Van Rossum, python-dev From logiplexsoftware at earthlink.net Thu Jul 11 11:25:44 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 11 Jul 2002 08:25:44 -0700 Subject: Python in the enterprise: Pros and cons In-Reply-To: References: <200207110952.21663.b.maryniuk@forbis.lt> Message-ID: <20020711082544.59a18ff9.logiplexsoftware@earthlink.net> On Thu, 11 Jul 2002 05:47:22 -0400 Tim Peters wrote: > [builder] > > Python has many fans in the open source community, but is it ready for > > the enterprise? > > [Bo M. Maryniuck] > > What the buzzword "the enterprise" is (as other buzzwords, aka > > XML, Java etc)? > > It's an especially annoying American buzzword for "business use, as opposed > to consumer, research, or educational use". Your enterprise-ready software > is primed to take on the challenge of synergizing mission-critical business > logic in empowering ways. IOW, it computes the sales tax right more often > than not . > > to-the-next-level-going-forward-ly y'rs - tim I always took "enterprise" to mean "runs on an AS/400 with a text interface", or possibly as a synonym for "token-ring". -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From graham at effectif.com Sat Jul 6 12:54:36 2002 From: graham at effectif.com (Graham Ashton) Date: Sat, 06 Jul 2002 17:54:36 +0100 Subject: Understanding properties References: Message-ID: On Sat, 06 Jul 2002 17:49:48 +0100, Emile van Sebille wrote: > try: > > class MyObject(object): Thanks. All has become clear... :) -- Graham From phr-n2002b at NOSPAMnightsong.com Thu Jul 25 04:50:28 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 25 Jul 2002 01:50:28 -0700 Subject: random 64-bit int References: <5nM%8.30598$4T2.8891354@twister.socal.rr.com> Message-ID: <7xu1mo5gyz.fsf@ruckus.brouhaha.com> Jeff Davis writes: > It seems like the above works, but I'd like to know whether I am losing > randomness, or whether there is a more efficient or faster way to > accomplish that. Would it be a good idea to include a call to > random.seed()? > > Also, it would be *really* nice if there was a good way to do that in > python2.1, which does not seem to allow the "q" type for unpack(). If you need really good randomness, for example for a security application, don't use the random module at all. Instead, if you're using Linux or *BSD, read from the /dev/urandom device: randfile = open("/dev/urandom") and then to get 8 bytes of randomness: bytes = randfile.read(8) If you want to convert the bytes to a long int, the simplest way I know is to convert to hex first: import binascii n = long(binascii.hexlify(bytes), 16) If you're using Windows, the Cygwin package emulates /dev/urandom using a Windows CAPI call (CryptGenRandom). At the moment there's no direct way to call that function in the standard Python distribution, but I suppose you could write an extension. Docs are at msdn.microsoft.com. From ngps at vista.netmemetic.com Tue Jul 16 23:51:27 2002 From: ngps at vista.netmemetic.com (Ng Pheng Siong) Date: 17 Jul 2002 03:51:27 GMT Subject: Session ID & Security References: Message-ID: According to Jan Felix Reuter : > Now I'm concerned about security, because with this sheme an attacker could > easily get access to a user's session by just guessing its ID. After some > research I found out about Message Authentication Codes and the hmac python > module. How does one use it? Do I apply the algorithm to every message (cgi > output?) and place the hash in another cookie or appended to the session ID > string? So, if the client sends back a hash that differs from the last hash > the server has send, the session is discarded, is that how you do it? Take a look at AuthCookie, bundled with M2Crypto. http://www.post1.com/home/ngps/m2 Cheers. -- Ng Pheng Siong * http://www.netmemetic.com From tim.one at comcast.net Sat Jul 27 01:04:35 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 27 Jul 2002 01:04:35 -0400 Subject: how to count lines in a file ? In-Reply-To: Message-ID: [Jonathan Hogg] > Not quite. Any cycle containing an object with a __del__ method will be > skipped and left to languish in memory-limbo forever. [Steve Holden] > You mean the garbage collector doesn't *collect* data that appears in > cycles? That's not my understanding (which doesn't nevessarily mean it's > dissonant with reality). The key here is "a __del__ method", meaning an object of a user-defined class that explicitly defines a method named "__del__". If a cycle contains at least one such object, gc will not collect that object, or the cycle it's in. Instead the object is placed in a list of unreachable yet uncollectable trash, which you can access as gc.garbage. Here's an example: >>> class A: ... def __del__(self): ... self.x.remove() ... def remove(self): ... print "oops!" ... >>> i = A() >>> j = A() >>> i.x = j >>> j.x = i >>> import gc >>> gc.garbage [] >>> del i, j >>> gc.collect() 4 >>> gc.garbage [<__main__.A instance at 0x0065B558>, <__main__.A instance at 0x0065B5A8>] >>> The difficulty is that when objects with __del__ methods are in a cycle, it's impossible to guess a safe order to tear them down: any object in a cycle is-- by definition --reachable from every other object in the cycle, so no matter which Python decided to tear down first, some other object Y in the cycle may try to use it from Y's own __del__ method. Random errors are the best you can hope to get from that, and system crashes the worst (the latter can be prevented, but only with a silly level of difficulty). So Python punts in this case -- if you create such beasts, it's your problem to tear them down in a safe order (which only you can know). At least you can scan gc.garbage for such unreachable beasts, and break the cycles in an order that you know (or hope) is safe. Better never to create such things to begin with, of course. > ... > >>> a = [1,2,3,4] > >>> a.append(a) > >>> a > [1, 2, 3, 4, [...]] > >>> > > Notice how the interpreter cleverly avoids an infinite recursion in the > repr() of that list. The fact that it contains references to itelf need > not stop its collection, and that is precisely why [I understand] the > new GC scheme was introduced to supplement reference counting. Right on all counts. That isn't an instance of an object with a __del__ method, and it's only __del__ methods that inhibit cyclic gc. > ... > So, what you *seem* to be saying is that it would be perfectly > possible to collect objects that don't have __del__() methods, but > once they acquire such they are no longer collectible even when only > cyclic references exist? That seems an odd asserion. Nevertheless, a true one . Objects with finalizers in cycles are a problem for all automatic memory recycling schemes. Python's approach here is an instance of refusing to guess in the face of ambiguity. Other approaches that have been implemented in other languages/systems include running finalizers in an arbitrary order (and hoping things don't blow up); running finalizers in order of object creation, or the reverse of that order (and hoping the user has a good enough handle on that so they don't write code that blows up); simply letting the objects leak; reclaiming the memory but not running the finalizers at all; defining incomprehensible schemes where an object's finalizer is run at most once no matter how often the object may resurrect itself, or be resurrected by other objects from the cycle(s) it's in (that's a technical hack Java uses to ensure that Java itself doesn't die with NULL-pointer errors (etc) after running a finalizer in an unreachable cycle: note that if there are two objects A and B in a cycle with __del__ methods, and if A is torn down first, B's __del__ method may resurrect A (e.g., make A reachable from a global again), and that's a recipe for system disasters; Java is careful to avoid that, via a mass of technical rules that only make sense to implementers); assorted registration schemes for explicitly informing the system of the order you want cycles torn down; and severely limiting what kind of code *can* appear in user-defined finalizers so as to prevent any possiblity of a finalizer doing harm to the system. They all suck. Python's sucks the least . From mcfletch at rogers.com Tue Jul 2 15:29:54 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 02 Jul 2002 15:29:54 -0400 Subject: Useful RE patterns (was: Variable Interpolation - status of PEP 215) References: <4PfQ8.44245$n4.10307683@newsc.telia.net> <3D1203A2.B2A3AD9@email.sps.mot.com> Message-ID: <3D21FF32.6090902@rogers.com> Fredrik, it would be nice to see the list you collect (not just the selected final entries). I'm actually doing something very similar for SimpleParse (pre-built parsers for common constructs that can automatically be included in your grammars). The library feature will appear in SimpleParse 2.0 (now under development). Watch for more details in the weeks ahead or join in in the development effort... So far I have: int hex float number := hex/float/int double quoted string single quoted string string := (dqs/sqs) semi_colon_comment (ini-files and the like) hash_comment (python-style) slashslash_comment (C++ // comments) slashbang_comment (C /* */ non-nesting comments) slashbang_nest_comment (as previous, but allows nesting) (and common character classes as well, but RE has those already) Common ones I'm thinking of adding: Identifiers (e.g. Python, XML, HTML, C, filenames, URIs) Dates (with a decent selection of formats, suitable for human data entry processing) Times (again, a number of formats) Display-formatted numbers (e.g. 200,000.00 or 200 000,00 or (200,00) ; locale specific by default, possibly offering a few common international formats) Common units of measurement (SI units only? or maybe Imperial as well. Anyway, type would be something like: unit_weight or unit_distance or unit_energy (parsers would then define expression,unit to require a unit or expression,unit? to provide a default unit)) Irrational numbers (under numbers, i or j forms) Monetary values (locale-specific base, possible with a "world" version to allow for parsing Pounds, Francs, Euros, Yen, Dollars etceteras without needing to switch locales, support for surrounding brackets meaning negative, those kinds of things :) ). IP Addresses Dotted identifiers Higher-level constructs under consideration: Mathematical expressions Lists, tuples, dicts (not sure how to make this generic without requiring a specific name for key/value expressions) Possible Python-specific additions (seen in tokeniser.py for your purposes): Calling/parameter-lists (definition and use) Triple quoted strings (under strings) SGML/XML/HTML-specific, thinking of including them as simpleparse/common/sgml.py: Identifier Tag Attribute Comment Entity References Processing instruction Various DTD elements (not sure if worth the trouble) For most of those you could probably find RE versions in various libs of the standard library (after all, they're common :) ). Enjoy, Mike Michael Hudson wrote: > Norman Shelley writes: > > >>Fredrik Lundh wrote: >> >> >>>... >>>If I were to add a dozen (or so) patterns to the (S)RE module, >>>what should I pick? What patterns do you find yourself using >>>over and over again? >> >>All kinds of numerics, e.g. scientific (1e-6, 2e6, ...) and engineering (1u, >>2M and/or 2MEG, ...) notation. >> >>Python identifiers as previously mentioned. > > > Well, *they're* already in the tokenize module. > > Cheers, > M. > -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From spam at ob_scure.dk Tue Jul 9 04:03:32 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Tue, 09 Jul 2002 10:03:32 +0200 Subject: Using Python for processing of large datasets (convincing man agment) References: Message-ID: <3D2A98D4.4040002@ob_scure.dk> Delaney, Timothy wrote: [snip - multiple results] > or you can actually do it in your sql call - IIRC correctly as a "batch" > call, or just simply as: > > "select a from T_A;select b from T_B;select c from T_C;" > > Doing this should reduce your network latency massively. I've used this method before, but never to reduce latency, thanks for the advice! -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From chris_mk at hotmail.com Tue Jul 30 18:14:35 2002 From: chris_mk at hotmail.com (Christopher) Date: 30 Jul 2002 15:14:35 -0700 Subject: decoding XML-ified special chars such as " References: Message-ID: Well, I seem to remember seeing something else, but here is what I got... Look in the HTMLParser.HTMLParser class for the function unescape... def unescape(self, s): if '&' not in s: return s s = s.replace("<", "<") s = s.replace(">", ">") s = s.replace("'", "'") s = s.replace(""", '"') s = s.replace("&", "&") # Must be last return s That's it. Looks like it was just a string substitution like I mentioned earlier to Gabe in an email. I'm actually pretty sure there is another way somewhere, I just can't remember where. Sorry. Chris PS you can use it as follows: >>> import HTMLParser >>> test = HTMLParser.HTMLParser() >>> test.unescape('abc < def') 'abc < def' "Gabe Newcomb" wrote in message news:... > Is there a module to take strings such as ", & and turn them > into the characters they normally represent (', &)? > > Gabe Newcomb > Software Test Automation Engineer > 425.372.2732 > Noetix Corporation > www.noetix.com > > after years of waiting, nothing came From claird at starbase.neosoft.com Mon Jul 8 07:58:40 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 8 Jul 2002 06:58:40 -0500 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7xwus7n5q4.fsf@ruckus.brouhaha.com> <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> <7xznx2j1qp.fsf@ruckus.brouhaha.com> Message-ID: <0B37FDD557B1530C.5DC635F49B964DBB.A17AB33A96993C53@lp.airnews.net> In article <7xznx2j1qp.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >Actually, SQL tends to be awful slow too. Recent Oracle versions let >you write stored procedures in Java, which are orders of magnitude >faster than PL/SQL procedures. MySQL also has some alternate language >interfaces for stored procedures now but I'm not up on them. I'm *not* ready to ratify these propositions. SQL's a special-purpose language--there's no question about that. To call it slow ... well, I just don't find it suf- ficiently comparable to general-purpose languages for that to be meaningful to me. What I do know is that it's very typical for beginners in SQL to do simple-minded accesses, then sort-and-calculate in a host (client-side) language, without realizing that they might get ORDERS of magnitude better performance by having SQL do the calculations on the server side. It's also possible to push calculations to the server side and degrade performance. I'm simply urging Mr. Jensen to follow through on his inclination to look to SQL improvements as an early step in performance improvement. We don't know yet, do we, what RDBMS he uses? Yes, the vendors certainly do attempt product differentiation by the extension languages they offer for stored procedures, server-side functions, and other goodies. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From gerhard at bigfoot.de Sun Jul 21 18:24:27 2002 From: gerhard at bigfoot.de (Gerhard Haering) Date: Mon, 22 Jul 2002 00:24:27 +0200 Subject: XML with Python - supposed to be simple? ;) In-Reply-To: References: Message-ID: <20020721222427.GA12508@gargamel.hqd-internal> * Vladimir Cherepanov [2002-07-22 01:17 +0400]: > "Martin v. Loewis" wrote in message > news:m3it38lsxm.fsf at mira.informatik.hu-berlin.de... > > "Vladimir Cherepanov" writes: > > > > > As a complete newbie to both XML and Python, I've been trying to > > > create (any!) XML document using DOM API in PyXML package. Very > > > simple task isn't it? > > You'll then learn that you can create > > Document instances by invoking createDocument on the > > DOMImplementation. For minidom, you get the DOM implementation by > > calling xml.dom.minidom.getDOMImplementation(). > > Thanks, I'll try this. Btw, I didn't find this method in DOMImplementation > Interface - the only method I found was "hasFeature()". > And what about serializing? Here's a working example: #!/usr/bin/env python from xml.dom.minidom import getDOMImplementation # requires PyXML: from xml.dom.ext import PrettyPrint impl = getDOMImplementation() doc = impl.createDocument(None, "document", None) root = doc.documentElement foo = doc.createElement("foo") root.appendChild(foo) PrettyPrint(doc) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From peter at engcorp.com Mon Jul 8 23:25:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 23:25:45 -0400 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> Message-ID: <3D2A57B9.8EDD2BF0@engcorp.com> Lowel Stern wrote: > > >Do you know about the % operator? > > > Yes I do. But not how to use it properly... > You will find that if you use the %s with the popen command you get an > error: > TypeError: unsupported operand type(s) for %: 'file' and 'str' Please post the code that generates this message. The code _can_ be fixed. -Peter From ls2311 at netcom.com Tue Jul 9 01:57:42 2002 From: ls2311 at netcom.com (Lowel Stern) Date: Mon, 08 Jul 2002 22:57:42 -0700 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> <3D2A57B9.8EDD2BF0@engcorp.com> <14rkiu8fnp8chiua156k2qm9r1s2vf5trs@4ax.com> Message-ID: On Tue, 9 Jul 2002 00:16:02 -0500, "Chris Gonnerman" wrote: >----- Original Message ----- >From: "Lowel Stern" > > >> On Mon, 08 Jul 2002 23:25:45 -0400, Peter Hansen >> wrote: >> >> >Please post the code that generates this message. The code >> >_can_ be fixed. >> > >> >-Peter >> >> >> -------------------------------------- >> import os >> key = "%s %s" % ('"stern:STWA"',"1234") >> print key >> fp = os.popen('C:\python_scripts\prog %s') % (key) >> --------------------------------------- > >Thar she blows. The line most likely should be: > > fp = os.popen('C:\python_scripts\prog %s' % key) > >Note that the parens after the function or method name >bind "tighter" than the % operator. The call is made >FIRST, then the % operation. It needs to be the other way. > > >> fp = os.popen('C:\python_scripts\prog %s') % (key) >> Traceback (most recent call last): >> File "", line 1, in ? >> fp = os.popen('C:\python_scripts\prog %s') % (key) >> TypeError: unsupported operand type(s) for %: 'file' and 'str' >> > >Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net >http://newcenturycomputers.net > > Thank you all for your input and for fixing this problem for me. Lowel From wilk-spamout at flibuste.net Mon Jul 15 05:14:08 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Mon, 15 Jul 2002 11:14:08 +0200 Subject: any web application available in python? References: Message-ID: <20020715111408.50a92994.wilk-spamout@flibuste.net> Le Mon, 15 Jul 2002 04:19:24 -0400 "a64bs4$1oo$1 at newsreader.mailgate.org" ?crivait: > hi.. > i want to make a community-oriented website for programmers > well, i don't know what features i would need yet though. > > however, it seems that message-board is pretty basic feature to any > website.. > is there any module(?) or open source code that i can use for > message-board with apache? not really for message-board, but really for community, you can use moinmoin, a python clone of wikiwiki http://moin.sourceforge.net/ bye -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From niessink at serc.nl Fri Jul 26 04:14:27 2002 From: niessink at serc.nl (Frank Niessink) Date: 26 Jul 2002 08:14:27 GMT Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> <918bc22f.0207200441.7a5a130d@posting.google.com> <918bc22f.0207210552.56806903@posting.google.com> Message-ID: Syver Enstad wrote: > > donnal at donnal.net (Donnal Walter) writes: > > >> >> Yes, from the responses here that does appear to be the conventional >> way of doing things, so I guess I will continue using unittest this >> way too. I had thought I might replace my batch files with a >> TestSuite, but I'm really not complaining about the way it works now. >> Thanks. > > Btw, here's some code I put in my __init__.py files to run unittest > for all modules in a package. Just another solution: I usually have my tescases in a tests/ subdirectory, and use this testall.py script to run them: ---------------------------------------------- #!/usr/bin/env python import glob for filename in glob.glob('*Test.py'): exec 'from %s import *'%filename[:-3] if __name__ == '__main__': import unittest unittest.main() ---------------------------------------------- This also works from unittestgui.py by entering "testall" in the textbox. Cheers, Frank -- [...] just as lunch was at the centre of a man's temporal day, and man's temporal day could be seen as an analogy for his spiritual life, so Lunch should (a) be seen as the centre of a man's spiritual life, and (b) be held in jolly nice restaurants. -- Douglas Adams, 'Life, the Universe, and Everything' From jim at dsdd.org Fri Jul 26 19:47:46 2002 From: jim at dsdd.org (Jim Meier) Date: Fri, 26 Jul 2002 23:47:46 GMT Subject: Python Internals Doc References: Message-ID: On Fri, 26 Jul 2002 12:20:10 -0600, David LeBlanc wrote: > There was, at one time, a website describing Python's internals - anyone > know if it's still available and, if so, where it can be found? > > David LeBlanc > Seattle, WA USA I'm afraid I can't answer your question (google probably can), but I can tell you that python's internals have always been easy enough to read even for my poor brain. Just grab the source and hop right in :) -Jim From maxm at mxm.dk Thu Jul 25 06:29:44 2002 From: maxm at mxm.dk (Max M) Date: Thu, 25 Jul 2002 12:29:44 +0200 Subject: Bug? cgi.escape(int) References: <3D3FBC36.2050708@thomas-guettler.de> Message-ID: <3D3FD318.7020406@mxm.dk> Thomas Guettler wrote: > It would be nice if cgi.escape(int) would not > throw an exception. > > What do you think? Why? Isn't escape supposed to get a string as an input? Passing it an int is meaningless. regards Max M From umopi at psyon.org Fri Jul 19 03:00:24 2002 From: umopi at psyon.org (Eric Arnold) Date: Fri, 19 Jul 2002 00:00:24 -0700 Subject: regex substitution question Message-ID: I have a question about a regex substitution. Lets say that with the following string: x11111x22222x33333x44444x I wanted to find anything that looked like this: 'x([^x]*)x[^x]*x' and replace only the first group with something (say "-") so the first match would be: "x(11111)x22222x" which would change the line to: x-x22222x33333x44444x and so on ... then the last match would be: "x(33333)x44444x" which would change the line to: x-x-x-x44444x but the last "44444" would never get substituted. What would be the easiest way to accomplish this? Thanks! Eric From theller at python.net Wed Jul 10 07:38:19 2002 From: theller at python.net (Thomas Heller) Date: Wed, 10 Jul 2002 13:38:19 +0200 Subject: Pyrex and Distuils: an enhanced build_ext command References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> <3d799735.0207100216.4eb8a9cd@posting.google.com> Message-ID: "Graham Fawcett" wrote in message news:3d799735.0207100216.4eb8a9cd at posting.google.com... > > Okay, I wrote the distutils command. Actually I just added a > subpackage to Pyrex that you can import into your setup script: > > from distutils.core import setup > from distutils.extension import Extension > import Pyrex.Distutils > > setup(name='foo', ext_modules=[Extension("foo", ["foo.pyx"])]) > > Note that the Extension() specifies a .pyx file, not a .c file. You > can specify .c files as well, but of course Pyrex will ignore them. > > Pyrex.Distuils (my subpackage) is a build_ext replacement -- it > import-hacks itself into the distutils.command package, so that it > gets a first shot at any build_ext calls. Once it's finished, it > returns control to the "real" build_ext. Some notes, just to spread some distutils knowledge: 1. The 'official' way to replace a standard distutils command class is done in the following way: Derive your class, say 'my_build_ext', from the standard distutils command: class my_build_ext(build_ext): .... and then pass a cmdclass parameter to the setup command: setup(... cmdclass = {'build_ext': my_build_ext}, ...) 2. Looking at distutils command.build_ext source, there is already a method which 'precompiles' source files into .c files, it's the swig_sources() method. Sound a little hackish, but probably we could get away with just overriding this method in the my_build_ext class. Maybe something like the swig_sources() command should be promoted into an 'official' hook for precompilation? Thomas From ianb at colorstudy.com Mon Jul 15 12:00:46 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 15 Jul 2002 11:00:46 -0500 Subject: Python CGI - Session Management In-Reply-To: References: Message-ID: <1026748846.582.25.camel@lothlorien.colorstudy.net> On Mon, 2002-07-15 at 10:48, Jan Felix Reuter wrote: > Hi, > I'm trying to implement some session management in my website, to keep track > of logged-in users. The site is entirely made of CGI's written in python. I > just don't know where to start, I've looked at the Cookies module, I > understand that allright, but where do I place the code in my CGI's? > > How does one do session managment in Python, anyway? Aren't there any > modules that I have overlooked? Also, I'd like to know if there's a good > website with resources about programming for the web with python. I google > search didn't give me any meaningful results. For more complex things, people often use frameworks (which usually include some sort of sessions). Some of them are listed here: http://www.python.org/cgi-bin/moinmoin/WebProgramming For sessions, you'll want associate a session-ID with the user (i.e., set a SID cookie for the user), and then use something like shelve to store the session information associated with that cookie. I don't know of anything to do this for you, but then I'd also be surprised if something for CGI didn't exist somewhere. Ian From pixie888 at hotmail.com Mon Jul 22 08:46:09 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Mon, 22 Jul 2002 12:46:09 GMT Subject: Python to Excell References: Message-ID: <3d3bfe07.268926031@news.skynet.be> Thank you, Do you have any suggestion/clues on how to use that module, there is quite some functionality in it. Some sample code to get started would be great. I am not a very experienced programmer... Henk On Mon, 22 Jul 2002 11:57:52 +0100, Stefan Schukat wrote: >Sorry missing gencache > >-> > >from win32com.client import gencache >gencache.EnsureDispatch('Excel.Application', 0) > > > Stefan > >-----Original Message----- >From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] >Sent: Monday, July 22, 2002 10:48 AM >To: python-list at python.org >Subject: Re: Python to Excell > > >On Mon, 22 Jul 2002 09:49:33 +0100, Stefan Schukat > wrote: > >>Search for excel8/9/10.olb an run makepy on it. There you'll have >>all the classes available from Excel. >> >>or run "win32com.client.EnsureDispatch('Excel.Application', 0)" >>and search the [PYTHON_ROOT]\Lib\site-packages\win32com\gen_py >>directory for the generated module. > >When I try the code above I get: >>>> import win32com >>>> win32com.client.EnsureDispatch('Excel.Application', 0) >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'win32com' module has no attribute 'client' >>>> from win32com import client >>>> win32com.client.EnsureDispatch('Excel.Application', 0) >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'win32com.client' module has no attribute >'EnsureDispatch' > >Any idea? > >> >>or use the macro recorder of excel and translate it to python code >> >>or use the excel online help >> >>or buy a book "Python Programming on Win32" >> >>or ... >> >> >> Stefan >> >> >>-----Original Message----- >>From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] >>Sent: Monday, July 22, 2002 8:33 AM >>To: python-list at python.org >>Subject: Python to Excell >> >> >>Hi all, >> >>I want to use Python to automate Excell. What I want to do is writing >>a script which updates an Excell sheet and which prints it out then. I >>know the stuff about DispatchEx but I do not know the interface which >>is exposed by Excell. Can anybody help me further on this one? >> >>Thanks, >> >>Henk >>-- >>http://mail.python.org/mailman/listinfo/python-list >> >> > >-- >http://mail.python.org/mailman/listinfo/python-list > > From mlai at intrinsyc.com Mon Jul 15 13:39:48 2002 From: mlai at intrinsyc.com (max) Date: 15 Jul 2002 10:39:48 -0700 Subject: Serial Port Returning Garbage. Why? Message-ID: Hi. I need some help. I've been trying to establish a bi-directional serial communications link between two microprocessors with a python script. The link is used by a 'master' processor to transmit commands to a 'slave' processor, while also allowing the 'slave' to return any output back to the 'master' for analysis. The information garnered from the 'slave' is used to determine subsequent actions. Here's some background on the 'master' and 'slave': 'Master': Processor: sa1110 Serial Connector: 3-wire OS: linux 4.0 Python Version: 2.0 'Slave': Processor: irrelevant Serial Connector: 3-wire OS: irrelevant Python Version: not applicable Now, when individually connected to HyperTerminal, both the 'master' and the 'slave' work perfectly. I can see that the master correctly sends the command with a carriage return at the end. Likewise, inputting a command to the 'slave' through HyperTerminal results in expected behaviour, with output that should be detectable by the 'master' if the two processors are connected together. However, this isn't the case. Whenever I display the output sent by the 'slave' in an SSH terminal connected to the 'master', I'm supposed to get a prompt that looks like "IBoot>", at which I write my commands. Instead, I get garbage that looks like the following: IBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: Invalid command.^M^JIBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: Invalid command.^M^JIBoot> 68.0.B^M^J^M^JError: Invalid commandexec tftp192.^M^J^M^JError: I Anyway, I'm using the os module's functions to read and write to the serial port, and i'm using os.system to invoke the stty program to set the properties of the serial port connection. The reason for using stty is because the termios and fcntl modules aren't available for use. I've also tried using the global open function to generate a file descriptor, but that shows the same results as with the os module. The serial port properties appear to be properly set through stty, while timing doesn't appear to be an issue. Knowing all of this, does anyone know what could be causing the output to become garbled? Thanks Maximilian Lai Embedded Software Developer Intrinsyc Software, Inc. 10th Floor, 700 West Pender Vancouver, BC V6C 1G8 p: 604-646-7970 f: 604-801-6417 e: mlai at intrinsyc.com w: www.intrinsyc.com Intrinsyc, the 'Connected Intelligent Device Company' From nospam at nonesuch.com Wed Jul 31 18:15:56 2002 From: nospam at nonesuch.com (David Smith) Date: Wed, 31 Jul 2002 15:15:56 -0700 Subject: C++/Python version problems? References: <3D484ACD.7030503@nonesuch.com> <3D485962.4060506@nonesuch.com> Message-ID: <3D48619C.9030506@nonesuch.com> David Smith wrote: > I'm just using STL - in particular, vector, fill, max, min. Actually, this module doesn't use vector. It #includes and uses min, max, and fill. The undefined name __gxx_personality_v0 shows up in /usr/lib/libstdc++.so.3 So, following the clues in "Distributing Python Modules", I added to the extension specification in setup.py: Extension("cfuncs", ["cfuncs.cpp"], libraries=['stdc++'], library_dirs=['/usr/lib']) and rebuilt. But when I tried to import it into Python, I still got the error: ImportError: ./cfuncs.so: undefined symbol: __gxx_personality_v0 -- David Smith drs at labs dot agilent dot com <- hopefully doesn't trigger spambots From cb9001 at hotmail.com Fri Jul 12 20:10:01 2002 From: cb9001 at hotmail.com (C Booth) Date: 12 Jul 2002 17:10:01 -0700 Subject: exporting boost::tuples::tuple to python Message-ID: <7c37d98e.0207121610.4e4f20e8@posting.google.com> Hi, I am trying to export a C++ class to python using the boost package (www.boost.org). I want my C++ functions to return a tuple: #include "boost/tuple/tuple.hpp" class TestClass { public: TestClass(); ~TestClass(); void setXYZ(float x,float y, float z); boost::tuples::tuple getXYZ(); }; And i wrap the class up as follows... #include BOOST_PYTHON_MODULE_INIT(Test) { boost::python::module_builder TestClass_Module("Test"); boost::python::class_builder pyTestClass(TestClass_Module, "TestClass"); pyTestClass.def(boost::python::constructor<>()); pyTestClass.def(TestClass::getXYZ, "getXYZ"); // <-- Line #1 pyTestClass.def(TestClass::setXYZ,"setXYZ"); } The class works just fine if i use it from C++ and if i comment out Line #1 again it works just fine in both C++ and python. I am using MSVC 6.0, boost 1.27.0. When I don't comment out Line #1 I get the appended error message, is this something i can fix, or should i give up on MSVC and try another compiler? thanks for any help, chris --------------------------- j:\chrisb\boost_1_27_0\boost\python\detail\extension_class.hpp(393) : error C2664: 'py_extension_class_converters' : cannot convert parameter 1 from 'struct boost::python::type >' to 'struct boost::python::type' No constructor could take the source type, or constructor overload resolution was ambiguous j:\chrisb\boost_1_27_0\boost\python\caller.hpp(33) : see reference to function template instantiation 'struct _object *__cdecl boost::python::to_python(const class boost::tuples::tuple &)' being compiled j:\chrisb\boost_1_27_0\boost\python\detail\extension_class.hpp(393) : error C2228: left of '.to_python' must have class/struct/union type j:\chrisb\boost_1_27_0\boost\python\caller.hpp(33) : see reference to function template instantiation 'struct _object *__cdecl boost::python::to_python(const class boost::tuples::tuple &)' being compiled Error executing cl.exe. -------------------- From aleax at aleax.it Wed Jul 24 06:54:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 10:54:33 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: Jeremy Bowers wrote: > Python session you can copy & paste to follow along: > > ----- > > class M1: > "M1's docstring." > def __init__(cls, name, bases, dict): > pass > > class A: > "A's docstring." > pass > > A.__doc__ There's nothing connecting A and M here, so I can just assume you forgot something, as well as making __init__ into a noop (as noticed in a following message). Anyway... > (Oh, and this stuff rocks. A three line metaclass, and two lines > activating it on a couple of base classes, is saving me oodles of typing > and goodness only knows how many bugs based on forgetting those lines in > some obscure subclass. I had a hard time understanding the metaclasses > until I found a need for them, but now it's crystal clear. Thanks, Python > team, this f'in ROCKS!) ...would you please share your uses for metaclasses? I can use all the good examples I learn about -- it's hard to teach people how to use metaclasses without actual motivation, and the more real-life examples I can collect and quote, the more likely I can help people achieve that motivation! Thanks, Alex From peter at engcorp.com Mon Jul 1 00:23:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Jul 2002 00:23:36 -0400 Subject: newbie Q: delete list few lines in file References: <7fe97cc4.0206291519.1c95ce31@posting.google.com> <3D1E5123.FDEFADDF@engcorp.com> <3D1E83C0.8060700@earthlink.net> <3D1E8A08.53DD2272@engcorp.com> Message-ID: <3D1FD948.25806D00@engcorp.com> Jonathan Hogg wrote: > > I think that it is unclear from Xah's original post whether the files or the > lines are to be deleted. Certainly, asking how to write to files in place > suggests that the lines are to be deleted. I didn't catch that part. Apparently neither did anyone else who was interested in helping, rather than criticizing... I just ask things that come to mind to try to clarify the vague questions we get. If I slip up sometimes in my reply, well, that's to be expected. At least I'm trying to ferret out a useful answer. > > -trying-not-to-complicate-things-ly yr's, > > If you want to say "that's complicated, are you sure you want to do that?", > go ahead. But it's not helpful to tell someone that something cannot be done > when it can. That's just misdirection. This time I was wrong. Nevertheless, the answer I should have got was "no, you misunderstood, I want to delete the lines, not the files", in which case I or someone else would have said, "oh, for *that* you can just truncate the file". -all-the-world's-a-critic-ly yr's, Peter From cqx at cube2.nefud.org Tue Jul 9 13:06:23 2002 From: cqx at cube2.nefud.org (cqx) Date: 09 Jul 2002 10:06:23 -0700 Subject: expect module and/or functionality? Or SSH wrapper module? Message-ID: Is there a more up-to-date expect-like module than the ExpectPy-1.9b1 package available on SourceForge? I'm actually more interested in a pure python expect module if possible. I mostly need it as an interface to 'ssh'. thanks, -allan From b.maryniuk at forbis.lt Tue Jul 9 07:17:38 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 13:17:38 +0200 Subject: HTML to PDF converter? In-Reply-To: References: Message-ID: <200207091317.38684.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 12:28, Alberto Berti wrote: > mmmm.... a basic one > http://www.zope.org/Members/gaaros/ZpdfDocument > it's not so zope centered... Date: 1999/11/28 Version: 0.0.1 (Development) :-( -- Sincerely yours, Bogdan M. Maryniuck The only "intuitive" interface is the nipple. After that, it's all learned. (Bruce Ediger, bediger at teal.csn.org, in comp.os.linux.misc, on X interfaces.) From cliechti at gmx.net Tue Jul 16 18:23:55 2002 From: cliechti at gmx.net (Chris Liechti) Date: 17 Jul 2002 00:23:55 +0200 Subject: saving modules References: <1d95285a.0207161412.5e101629@posting.google.com> Message-ID: abelo at earthlink.net (Carl) wrote in news:1d95285a.0207161412.5e101629 at posting.google.com: > -The file name reads out as fibopy~1 and the full name reads out > as fibo.py.txt your editor/browser saved the file with the wrong ending. just rename it to fibo.py (without .txt) and it should work. chris -- Chris From fredrik at pythonware.com Sat Jul 13 10:22:12 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 14:22:12 GMT Subject: What went wrong in Python1.6 ? References: Message-ID: Roy Smith wrote: > As far as I know, nothing was really "wrong" with 1.6, other than > timing. in practice, what was released as 1.6 final was pretty much an early 1.6 alpha (plus some backported stuff); what was supposed to be 1.6 final was renamed 2.0... so in a parallel universe, most of us are using using 1.7.3 and 1.8.1, and the python-dev team is warming up for 1.9... From cliechti at gmx.net Mon Jul 1 18:07:53 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Jul 2002 00:07:53 +0200 Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: "Fredrik Lundh" wrote in news:sb%T8.14091$p56.4590186 at newsb.telia.net: > Steve Holden wrote: > >> There did used to be a MoinMoin-based Wiki somewhere >> under www.python.org > > http://www.python.org/cgi-bin/moinmoin > > resurrecting it (and moving it's focus to Python in general, > rather than Python 2.0 ;-) sounds like a good idea. > > maybe we should start here: > > http://www.python.org/cgi-bin/moinmoin/Python > > and see what happens... ... File "/usr/local/apache/MoinMoin/parser/wiki.py", line 335, in replace return apply(getattr(self, '_' + type + '_repl'), (hit,)) AttributeError: Parser instance has no attribute '_hmarker_repl' well not exactly on that page, but on many pages including the frontpage... who can solve that? chris -- Chris From rotundo52 at hotmail.com Sun Jul 21 00:28:12 2002 From: rotundo52 at hotmail.com (Jon J. Morin) Date: Sun, 21 Jul 2002 04:28:12 GMT Subject: getting date into rfc822 format Message-ID: Hi all. I'm writing a program that sends email in an environment that does not have sendmail or similar MTA. I am trying to prepend the date to the headers of the email, but many mail clients that I have tested it with show the date as unknown when the message comes in. Here is how I come up with the date: import time date = time.ctime(time.time()) Which gives me a date like this: Sat Jul 20 00:02:03 2002 When what I want is something like this: Fri, 01 Mar 2002 00:18:17 -0500 (EST) Incidentally, I have read the rfc822 and I can't figure out what the -0500 is in the date/time. Can anyone explain this to me? Jon J. Morin University of Maine at Augusta From mhammond at skippinet.com.au Thu Jul 25 01:34:16 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 25 Jul 2002 05:34:16 GMT Subject: Python + Win32ALL + ASP = Problems accessing Request/Response/Session/Application objects References: <_ko%8.247434$iB1.13124073@bin4.nnrp.aus1.giganews.com> <3D3E6BCD.4010809@mxm.dk> Message-ID: <3D3F8DF3.9060807@skippinet.com.au> Joe Salmeri wrote: > Hopefully Mark Hammond will see this, I'm sure he will be able to provide > the answer (he always does!) OK :) It is all a bit nasty I'm afraid. In a nutshell, these objects are just COM objects that exist in some global namespace. (They are actually pyscript.ScriptItem objects, added as globals in pyscript.PyScript.RegisterNamedItem()) Each "engine" has a global namespace. The "engine" is defined by the application (ie, ASP), and "named items" along with the user specified "script code" are added to this engine. ASP obviously could have many Python engines open at once - one for every different connection to a page with Python content. Your external module may be used by any number of other ASP connection/scripts, so you really can't consider these script objects as "global" in any sense of the word. So while you may be able to devise a scheme for yourself, there really isn't much the ActiveScripting framework can do to help - nothing here is "global", so nothing is exposed as such. You could just pass the "ax" object around - it should have all the globals as attributes - eg, "ax.session" may work. Mark. From ods at fep.ru Mon Jul 1 09:52:07 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Mon, 1 Jul 2002 17:52:07 +0400 (MSD) Subject: New style classes as exceptions (Was: exception handing) Message-ID: On 29 Jun 2002, Chris Liechti wrote: CL> Rhymes wrote in CL> news:pan.2002.06.29.17.41.28.926443.440 at myself.com: CL> ... CL> >>>> ex1 = "spam" CL> >>>> try: CL> > ... raise ex1 CL> > ... except ex1: CL> > ... print 'got it' CL> > ... CL> > got it CL> ... CL> CL> exceptions are instances of classes nowdays... don't use CL> strings. and avoid CL> troubles... New style classes don't work when used as exceptions. I guess it should be considered as a bug. >>> class o(object): pass ... >>> try: ... raise o('spam') ... except o: ... print 'OK' ... Traceback (most recent call last): File "", line 2, in ? TypeError: exceptions must be strings, classes, or instances, not o From see_reply_address at something.invalid Tue Jul 16 22:01:59 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 17 Jul 2002 14:01:59 +1200 Subject: Why self? References: <3D2E11B5.4070502@removethisandallhyphens-o-n-e.net> Message-ID: <3D34D017.5030800@something.invalid> Fernando P?rez wrote: > > wrong. The interpreter mangles the __names automagically by adding the class > name. You can work around it, but at least it helps to prevent accidents. I think it's worth pointing out that the __ mangling is not intended to make the attribute inaccessible in some sort of bondage-and-discipline way, but to prevent name clashes between instance variables in superclasses and subclasses. In that respect, it's a considerable improvement over C++'s "private", which does exactly the opposite -- it renders things inaccessible *without* doing anything to prevent clashes! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jonathan at onegoodidea.com Fri Jul 26 14:21:52 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 26 Jul 2002 19:21:52 +0100 Subject: how to count lines in a file ? References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> Message-ID: On 26/7/2002 14:45, in article Znc09.12549$724.4531 at atlpnn01.usenetserver.com, "Steve Holden" wrote: > So what you appear to dislike is that there is now a *chance* that __del__() > will be called on cyclic garbage, when there wasn't before. Not quite. Any cycle containing an object with a __del__ method will be skipped and left to languish in memory-limbo forever. If the objects exist in a cycle then "logically" they must exist for ever. Luckily, for most simple containers, throwing them away is semantically no different from keeping them around - a dictionary or a list on it's own doesn't do anything. However, if something has a __del__ method then throwing it away requires executing some code which may have unknown side-effects - so you can't do it. At the very simplest level, the object's dictionary/slots may be meaningless at the time that you would execute __del__ (because you're in the middle of breaking all the cyclic references), so executing __del__ might cause horrible things to happen. It's a sort of philosophical thing. If you can be sure that having closed the door, no-one will open it again then the room on the other side is allowed to simply disappear ;-) __del__ only has sensible semantics in the presence of reference counting. Either have reference counting or throw away __del__. When it comes down to it you gotta pick one or the other. Jonathan From mwh at python.net Tue Jul 30 05:23:51 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Jul 2002 09:23:51 GMT Subject: Python design failures (was Re: Let's Talk About Lambda Func References: Message-ID: Michael Gilfix writes: > On Mon, Jul 29 @ 17:44, Sean 'Shaleh' Perry wrote: > > is there a place which documents modules needing a steward? Don't think so. The distutils are always looking for some love... > I second that. Or even more interestingly, is there a place which > lists who has ownership of each module? Don't think there's one of them either. Most modules aren't really "owned", there's just someone who does most of the looking after. cvs logs are the best way of finding this out. Cheers, M. -- This is an off-the-top-of-the-head-and-not-quite-sober suggestion, so is probably technically laughable. I'll see how embarassed I feel tomorrow morning. -- Patrick Gosling, ucam.comp.misc From mdehoon at ims.u-tokyo.ac.jp Tue Jul 23 03:44:46 2002 From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon) Date: Tue, 23 Jul 2002 16:44:46 +0900 Subject: Got it! (Re: Almost got it) References: <3D3D037C.6080301@ims.u-tokyo.ac.jp> Message-ID: <3D3D096E.1080703@ims.u-tokyo.ac.jp> I found the special trick needed to make this work. What I needed to do was to add c:\winnt\system32\python22.dll explicitly to the list of object files. I guess the -lpython22 is supposed to find python22.dll instead of python22.lib, but the latter gets used because of the -L c:\python22\libs. My Windows installer works now. Thanks again --Michiel. C:\cygwin\home\mdehoon\Software\Cluster>c:\cygwin\usr\local\bin\gcc.exe -mno-cygwin -mdll -static --entry _DllMain at 12 -s build\temp.win32-2.2\Release\cluster.o build\temp.win32-2.2\Release\clustermodule.o build\temp.win32-2.2\Release\ranlib.o build\temp.win32-2.2\Release\com.o build\temp.win32-2.2\Release\linpack.o build\temp.win32-2.2\Release\cluster.def -Lc:\python22\libs -lpython22 -o build\lib.win32-2.2\Pycluster\cluster.pyd -s c:\winnt\system32\python22.dll C:\cygwin\home\mdehoon\Software\Cluster> From duncan at NOSPAMrcp.co.uk Tue Jul 9 10:01:54 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 14:01:54 +0000 (UTC) Subject: win32: Leaving Dos Box open References: <3D2AE438.9030205@thomas-guettler.de> Message-ID: Thomas Guettler wrote in news:3D2AE438.9030205 at thomas-guettler.de: > Hi! > > How can the dos box be left open when I run foo.py from > the windows explorer and there is a syntax error? > > thomas > > Try something like this: ---- error.py --- import sys def excepthook(t,v,tr, old=sys.excepthook): old(t,v,tr) raw_input("Press return to exit") sys.excepthook = excepthook x = 3/0 print "Done" ---- end of error.py --- Copy the top 5 lines somewhere near the top of your own script. Alternatively wrap a try:except: handler around the main loop of your script. I sometimes use code like this: if __name__ == '__main__': try: # main program code goes here... main() except: # In case of emergency, lets debug! import pdb, sys, traceback sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info() traceback.print_last() pdb.pm() Which not only keeps the window open, but throws you into a debugger for good measure. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From amuys at shortech.com.au Tue Jul 9 21:39:32 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 9 Jul 2002 18:39:32 -0700 Subject: Why self? References: <090720021439257166%pecora@anvil.nrl.navy.mil> Message-ID: <7934d084.0207091739.4720aafc@posting.google.com> "Louis M. Pecora" wrote in message news:<090720021439257166%pecora at anvil.nrl.navy.mil>... > [[ This message was both posted and mailed: see > the "To," "Cc," and "Newsgroups" headers for details. ]] > > In article , Mark > McEahern wrote: > > > What you don't see, of course, is all the people who are silent because > > they're quite happy with self. prefixes and consider this a pointless > > discussion usually kept alive by people who refuse to learn the idioms of > > Python to their best advantage. > > Yeah, I may be one of those complainers. I have tried to learn the > language well and really like it, but for some reason this self. thing > really bugs me. (I _am_ seeing a therapist :-) ). I write a lot of > scientifc code and I just think > > > self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) > > is a LOT uglier than > > y= x**2 * t/z + a * FFT(tseries) In fact the only reason I have followed this thread is because I found myself writing some similar code just the other day and came to the same conclusion. Python loves namespaces right? Now I haven't given much thought to it, but it occurs to me to ask why Python dosn't provide support for using namespaces, not just defining them? Compare the following: self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) to: y= x**2 * t/z + a * FFT(tseries) to: with self: y= x**2 * t/z + a * FFT(tseries) Issues that immediately occur to me are: 1) Another keyword 2) How do you reference variables that aren't in the specified namespace without a second keyword! 3) Issue 2 becomes critical when you what to deal with temporary results that you definately want discarded along with the current local scope. So maybe only rvalues are affected ie. with self: self.y = x**2 * t/z + a * FFT(tseries) might be better, but then the inconsistency bites. Maybe this is a good idea? More likely I'm about to learn which critical basic flaw I've missed. at-least-I-will-get-to-learn-something-ly yours Andrae Muys From maxm at mxm.dk Mon Jul 15 02:41:17 2002 From: maxm at mxm.dk (Max M) Date: Mon, 15 Jul 2002 08:41:17 +0200 Subject: php function "addslashes" / "removeslashes" in python References: Message-ID: <3D326E8D.2070703@mxm.dk> Sean 'Shaleh' Perry wrote: > On 09-Jul-2002 Lowel Stern wrote: > >>Does anyone know if this exists already? perhaps in re.escape ?? Or if you are looking to use the function to put data to a database there are better ways in Python. Try and explain the problem, then the answer might be something else than it would be in Php regards Max M From emile at fenx.com Thu Jul 4 11:05:38 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 04 Jul 2002 15:05:38 GMT Subject: win32com and internet explorer References: <3d235b64$1@post.usenet.com> Message-ID: <6vZU8.409778$cQ3.28013@sccrnsc01> chandan mathur > I am new to python/programming.. I was trying to read and save a page > from the internet using win32com and internet explorer..., easy rite? Yep... but in python without win32com and ie: >>> import urllib >>> fp, info = urllib.urlretrieve("http://www.google.com") >>> content = open(fp).readlines() >>> content -- Emile van Sebille emile at fenx.com --------- From bokr at oz.net Wed Jul 31 14:27:26 2002 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2002 18:27:26 GMT Subject: how to count lines in a file ? References: <7aU%8.139472$vm5.4528856@news2.tin.it> <1027656130.63094@yasure> Message-ID: On 29 Jul 2002 00:25:59 -0400, list-python at ccraig.org (Christopher A. Craig) wrote: >bokr at oz.net (Bengt Richter) writes: > >> I like this, but I think I would rather see timely finalization >> subsumed under a general event-handling mechanism for objects. Thus >> ref count going to zero would be a standard event that you could >> write a handler for. > >You're still assuming that the standard deals with such a thing as a >reference count. One of the points of this whole thread (to my mind) Yes and no. You have a point. I was assuming there is/was/will be a platform with reference counting, and that such a platform (whose platform-specific events would be referenced in sys.events or such) would have a standard event ID for reference count of an object going to zero. So yes, reference count going to zero is too platform specific to be in the same league as an abstract finalization event which might be something to add to the language (I assume this is the gist of your point), and no, that doesn't mean I expect all systems to have reference counts for all objects and for that to be part of "the [language] standard". For a platform without (or with specialized limited) reference counting, we would have to find or create another event which could underlie the abstract finalization event. Alex's local(...) construct could provide a leaving-scope event that could serve as the equivalent for object references created within its scope. >has been that, though it is well known that CPython uses reference >counts for garbage collection (and people mistakenly depend on this), >the actual language standard does not require it. This means that any >code that depends on reference counts, in any way, is not only not I think "any way" is a bit broad, but I take it you mean source code that specifically refers to reference counting one way or another. I think you would agree that a low level dependency on platform specifics is necessarily part of constructing a platform-independent level of abstractions. If there were a general purpose mechanism for event handling (and triggering), I would expect it to handle both platform-specific and platform-independent events. Timely finalization is the abstract concept, and reference counting going to zero is a platform-specific event that could be used to implement it. My example wan't the best, since it appeared to suggest general user-level use of a ref count event per se (which I assume was what mainly you reacted to). Of course, events encompass more than synchronous events within a single thread, so there is more to think about (and we are already 'way OT for this NG thread ;-) >portable to Jython (or any other non-CPython compiler), it's not >necessarily compatible with all future versions of CPython. > I think you are right that the language definition should not depend on reference counting, but I think general purpose event mechanisms may and should be able to name and deal with platform specific events, so that they can be used to build a platform independent layer of events and features. >So if Guido decides today that reference counts were a dumb idea and >he would be better off with a simple mark-and-sweep GC, he can >implement one and not lose too much sleep over the weeping and >gnashing of teeth from those that depended on the behavior of the >current compiler. <.8 wink> > I'm sure he would give due consideration to all factors ;-) Regards, Bengt Richter From news-and-lists at the-me.de Thu Jul 25 13:30:45 2002 From: news-and-lists at the-me.de (Axel Bock) Date: Thu, 25 Jul 2002 19:30:45 +0200 Subject: python class question Message-ID: Hi folks, I need an explanation of a piece of code *urgently*, to understand an error message generated by Zope Python (a pure Python error, I think ...). Well: I have a class xrml, which wants to access a ZMySQLDA database connection (all this happens under Zope, but I think my question is pure Python nonetheless). For this I stole code from another module (ZSQLMethods :-), and the result looks like this: class xrml(SimpleItem.SimpleItem): def init_db(self): try: dbc = getattr(self, connection) except: return 'error' DB = dbc() Now I tried to modify the last line as follows: self.DB = dbc() and getting a very strange error (Error Type: UnpickleableError Error Value: Cannot pickle objects). Now my question is: what the hell am I doing here? Especially what is DB?? connection seems to be equally important, how can I find out what type of thing this is? A "return self.connection" delivers a "MySQL_database_connection". Is this a string, or an object? The code works well (queries and all else) if I use DB instead of self.DB, but this makes me unable to use DB from other member functions, doesn't it? (I'm quite a Python newbie i fear ... :-)) Any help would be much appreciated! Thanks in advance and greetings from Germany, Axel. From donn at drizzle.com Sat Jul 13 03:26:28 2002 From: donn at drizzle.com (Donn Cave) Date: Sat, 13 Jul 2002 07:26:28 -0000 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <3CgX8.68516$vm5.2504519@news2.tin.it> <0UlX8.69924$vm5.2553930@news2.tin.it> Message-ID: <1026545186.810050@yasure> Quoth "James J. Besemer" : ... "...to the letter." This strikes me as a "foolish consistency." | I think the standard is good overall but what makes it best is it | acknowledges up front that there's some room for personal judgment | and common sense. Among adults I expect we all can accommodate a | little flexibility in following these rules. So to some extent, I | regard interpreting it "to the letter" to be inconsistent with how | the PEP is written. I don't propose to take any action against people who deviate from it, and in fact I probably do so myself. But the problem with that is that everyone has an opinion, and it's always good judgement and common sense, to the one who holds it. We can say "follow the standard", or we can say "follow the standard unless you have some other idea." If you have a good way for people to tell the difference between their own personal idiosyncrasies and a really good idea that really deserves to be an exception, that would be interesting. | My particular problem is that some of the express rules about horizontal | white space actually hinder readability. As Mr. Corns points out, ... | But from a readability standpoint, it is a superior (and harmless) deviation | from the standard. This is really my point. There are two ways of looking at it. If you evaluate the standard from first principles, you can certainly argue that there may be superior alternatives. But a standard style actually creates its own advantage, assuming that it's widely used. Once a coding style has really become standard, deviations from it will tend to be less readable for most of the people who are used to that standard, and it makes no difference if the deviations are in principle superior. Looking at it that way, there really is no such thing as a superior deviation from the standard, it's a contradiction in terms. I'm accommodating a little flexibility, just don't try to tell me the the result will be more readable. It won't be. Donn Cave, donn at drizzle.com By the way, speaking of style - you may not have noticed that you formatted your post to 84 columns. 75 or less would be nice. I reformatted for you. From knight at baldmt.com Mon Jul 15 18:00:06 2002 From: knight at baldmt.com (Steven Knight) Date: Mon, 15 Jul 2002 17:00:06 -0500 (CDT) Subject: ANNOUNCE: SCons.0.8 (Python build tool) is now available Message-ID: SCons is a software construction tool (build tool, or make tool) written in Python. It is based on the design which won the Software Carpentry build tool competition in August 2000. Version 0.08 of SCons has been released and is available for download from the SCons web site: http://www.scons.org/ Or through the download link at the SCons project page at SourceForge: http://sourceforge.net/projects/scons/ RPM and Debian packages and a Win32 installer are all available, in addition to the traditional .tar.gz and .zip files. WHAT'S NEW IN THIS RELEASE? IMPORTANT: Release 0.08 contains the following interface changes: - The old feature of automatically splitting strings of file names on white space has been REMOVED. - The prefix, suffix and src_suffix arguments to the Builder() function may no longer be callable functions. - The BUILDERS construction variable should now be a dictionary that maps builder names to actions. Existing uses of lists, and the Builder() name= keyword argument, generate warnings about use of deprecated features. - The "shared" keyword argument has been removed from the Object and Library builders. Shared and static objects and libraries should now be created via the separate StaticObject, SharedObject, StaticLibrary and SharedLibrary builders. Object and Library are now synonyms for StaticObject and StaticLibrary, respectively. This release adds the following features: - New construction environment Append() and Replace() methods allow clearer manipulation of construction variables. - New functions: FindFile(), GetLaunchDir(), SetBuildSignatureType(), SideEffect(). - New command-line options: --debug=time, --implicit-deps-changed, --implicit-deps-unchanged, --warn. - New Builders: Tar. - Added a new Platform() method with support for the cygwin, os2, posix, and win32 platforms. - New "platform" and "tools" keyword arguments to Environment(). - Added a new Tool() method with support for the ar, dvipdf, dvips, g++, g77, gas, gcc, gnulink, icc, ilink, latex, lex, lib, masm, mslink, msvc, nasm, pdflatex, pdftex, tar, tex and yacc tools. - A dependency Scanner for native Fortran "include" statements, using a new "F77PATH" construction variable. - The -v option prints more specific version / build information. changes in the case of drive letters don't cause a rebuild. - The "target" argument to a Builder call may now be omitted, in which case the target(s) are deduced from the source file(s) and the Builder's specified suffix. - A new "multi" keyword argument to Builder() specifies that it's okay to call the builder multiple times for a target. - SCons now automatically falls back to using timestamps for out-of-date checks if the Python MD5 module can't be imported. - Multiple calls for a single Alias() will now append values. The following fixes have been added: - File names with multiple dots are now handled correctly. - The --implicit-cache option has been fixed if the scanner returns an empty list; no longer causes redundant rebuilds when the header file list changed; has been fixed when a file has no implicit dependencies and its source is generated. - C dependency scanning now detects #include file names with characters like '-'. - Shared libraries now use LIBS and LIBPATH for dependencies. - A build directory may now be outside of the SConstruct tree. - Shared object builds using g++ and gcc now use $CPPFLAGS, too. - A single interrupt is now guaranteed to halt SCons both when using -j and not. - Relative CPPPATH directories now work correctly when using BuildDir(). - SCons now prints an error message if a file can't be unlinked before being built, instead of just silently terminating the build. - Emitter functions' use of path names work properly using BuildDir or in subdirectories. - Fix .sconsign signature storage so that output files of one build can be safely used as input files to another build. Performance has been improved as follows: - Use our own version of the inefficient stock os.path.splitext() method. - Cache source suffix computation. - Code cleanup in MultiStepBuilder.__call__(). - Replicate some logic in scons_subst(). The following changes have been made to the SCons packaging: - Updated README instructions and setup.py code to catch an installation failure from not having distutils installed. The documentation has been updated to reflect the above changes. ABOUT SCONS Distinctive features of SCons include: - a global view of all dependencies; no multiple passes to get everything built properly - configuration files are Python scripts, allowing the full use of a real scripting language to solve difficult build problems - a modular architecture allows the SCons Build Engine to be embedded in other Python software - the ability to scan files for implicit dependencies (#include files); - improved parallel build (-j) support that provides consistent build speedup regardless of source tree layout - use of MD5 signatures to decide if a file has really changed; no need to "touch" files to fool make that something is up-to-date - easily extensible through user-defined Builder and Scanner objects - build actions can be Python code, as well as external commands An scons-users mailing list is available for those interested in getting started using SCons. You can subscribe at: http://lists.sourceforge.net/lists/listinfo/scons-users Alternatively, we invite you to subscribe to the low-volume scons-announce mailing list to receive notification when new versions of SCons become available: http://lists.sourceforge.net/lists/listinfo/scons-announce ACKNOWLEDGEMENTS Special thanks to Charles Crain, Jeff Petkau, Anthony Roach, Zed Shaw and Terrel Shumway for their contributions to this release. On behalf of the SCons team, --SK From sachs at panix.com Tue Jul 30 14:06:45 2002 From: sachs at panix.com (Josef Sachs) Date: 30 Jul 2002 14:06:45 -0400 Subject: Need help with win32com Message-ID: I have been using Python since 1994 on Unix, and I'm now trying to do some glue programming under Windows NT. (1) Could anyone suggest telnetd or sshd servers for NT, so that I can do some programming remotely? (2) I'm trying to use some COM objects that are defined in type libraries (.dll files). I can't figure out the proper arguments to win32.client.Dispatch(). I get: comm_error: (-2147221005, 'Invalid class string', None, None) Can anyone help me figure this out? Thanks in advance. From just at xs4all.nl Sun Jul 7 17:23:15 2002 From: just at xs4all.nl (Just) Date: Sun, 07 Jul 2002 23:23:15 +0200 Subject: is this a bug? References: <1026076470.877638@master.nyc.kbcfp.com> Message-ID: In article <1026076470.877638 at master.nyc.kbcfp.com>, "news" wrote: > Python 2.0 (#1, Feb 7 2001, 22:41:16) > [GCC 2.95.2 19991024 (release)] on sunos5 > Type "copyright", "credits" or "license" for more information. > >>> "aa" in ["aa", "ab"] > 1 > >>> "aa" in ["aa"] > 1 > >>> "aa" in ("aa") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'in ' requires character as left operand > > Is this a bug, or should this be consistent between lists and tuples? > > Puzzled. ("aa") is not a tuple but a string: >>> ("aa") 'aa' >>> ("aa",) ('aa',) >>> Just From claird at starbase.neosoft.com Mon Jul 15 08:46:04 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 15 Jul 2002 07:46:04 -0500 Subject: Open document formats References: <96c7f32.0207090659.b5b9a27@posting.google.com> <3D327322.5000006@mxm.dk> Message-ID: <790D2BA894F0EDCA.DABF15A0CD758D3A.EBDE18787B963495@lp.airnews.net> In article <3D327322.5000006 at mxm.dk>, Max M wrote: >.doc is the most common file format there is outside of html/txt so >naturally anybody who has customers that lives in an MS world must be >able to read it. Which means most of us. > >Publishing/reading in ps/pdf is rather easy for *nix types and >Publishing/reading in .doc is easy for Windows types, so it is very much >a matter of taste which format you use. . [more detail] . . While I'm generally among the world leaders in ascribing differences to "a matter of taste", I must demur on this point. Yes, I agree conventional desktop users frequently pass around .doc-s. It's NEVER acceptable to me, though, in the context of this thread, simply because .doc-s are such agents of contagion. They're infectious. It's un- safe computing. If you substitute .rtf for .doc in what you wrote, I can accept it. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From huaiyu at gauss.almadan.ibm.com Wed Jul 31 14:21:04 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 31 Jul 2002 18:21:04 +0000 (UTC) Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <7Rc19.92310$724.23106@atlpnn01.usenetserver.com> <3d46964b$1_2@hpb10302.boi.hp.com> <3d46c6a2$1_1@hpb10302.boi.hp.com> Message-ID: John Roth wrote: > >> For vertical scoping, it is not necessary to separate items with >commas. > >Is this valid Python in general, or is this another change to the >syntax? It's just what I think is necessary. I'm not sure if it fits the current python parser, although it appears to be so for existing structures like def, class, if, while. Huaiyu From brian at sweetapp.com Mon Jul 8 15:35:17 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 8 Jul 2002 12:35:17 -0700 Subject: Why self? In-Reply-To: <3D29DC83.4020205@onsitetech.com> Message-ID: <000e01c226b6$96de4e50$bd5d4540@Dell2> If the explicit self argument were removed, what would you add to the language to differentiate between local and instance variables? Cheers, Brian From mhammond at skippinet.com.au Wed Jul 31 18:58:26 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 31 Jul 2002 22:58:26 GMT Subject: Error including win32net in a Python COM server References: <3D4726D5.7050001@skippinet.com.au> Message-ID: <3D486BC3.9010607@skippinet.com.au> Emanuel Borges wrote: >>win32net uses functions only available on Win NT/2k/XP - you should use >>win32wnet for Win9x. > > > Thanks Mark but I am using these functions on a Windows 2000 system. > The functions themselves work fine. It's when I include them into my > COM server that gives me errors. If you register this code in your > registry, do you have the same problems? I'm using VBA in Excel to > access these methods, if that helps... That is strange. Can you send me a trivial COM object that demonstrates the problem? Thanks, Mark. From peter at engcorp.com Fri Jul 19 18:45:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Jul 2002 18:45:18 -0400 Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <190720021018041866%pecora@anvil.nrl.navy.mil> <190720021507121883%pecora@anvil.nrl.navy.mil> Message-ID: <3D38967E.4341FD67@engcorp.com> "Louis M. Pecora" wrote: > > In article , > Terry Reedy wrote: > > > Certainly, copying a global or builtin method to a local for > > repeated use is a standard Python speedup trick. > > I learn something every day. We should have a collection of speedup > tricks listed somewhere. This text by Guido sort of already does, in the conclusion section: http://www.python.org/doc/essays/list2str.html -Peter From shagshag13 at yahoo.fr Tue Jul 23 08:09:11 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 23 Jul 2002 14:09:11 +0200 Subject: good books References: Message-ID: is it still worth to buy it if you browse through this ? http://systems.cs.uchicago.edu/~beazley/tutorial/beazley_advanced_python/advpy.pdf http://diveintopython.org/ http://www.ibiblio.org/obp/thinkCSpy/dist/ http://www.greenteapress.com/thinkpython.html http://www.mindview.net/Books/TIPython because i'm also looking for "The" python's book but i'm tired to buy this expensive books that i use only a few times and less that some internet links... s13. From pinard at iro.umontreal.ca Mon Jul 8 22:34:07 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 22:34:07 -0400 Subject: `~/.pythonrc' `from __future__ import' In-Reply-To: References: Message-ID: [Thomas Bellman] > Well... At least under Unix there is a way... Put this code in > your ~/.pythonrc: [...] Wow! It even works!! Thanks a lot for the tip! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From whisper at oz.net Sun Jul 7 02:54:20 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 6 Jul 2002 23:54:20 -0700 Subject: Crash boom, why? In-Reply-To: <3d27d736@dnews.tpgi.com.au> Message-ID: You might be running into an execution context problem. See what /pythondoc/lib/built-in-funcs.html#built-in-funcs has to say. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of tALSit > Sent: Saturday, July 06, 2002 23:31 > To: python-list at python.org > Subject: Crash boom, why? > > > Hi, I'm doing some python/c++ integration, and i've come across a problem > that has nothing to do with c++. > > I've got a couple of scripts, and I want python to execute them. I execute > them with the builtin command "execfile" with just the name of > the script as > a parameter. I have two scripts, one of them executes perfectly fine, and > the other one only has 2 lines (calls to c++ objects). But the > thing is that > if I exec the script, python crashes, but if i copy and paste the contents > of the script inside the python interpreter, it works fine! > > Is execfile () the way to go around when I want to exec a script? > Are there > limitation to be taken into account with that function? > > Thanks for all! > > // talsit > > > -- > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Thu Jul 18 23:52:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Jul 2002 23:52:06 -0400 Subject: HTML DOM parser? References: Message-ID: <3D378CE6.E670EDAD@engcorp.com> David LeBlanc wrote: > > adding time.sleep(2) made it work - gave the browser time to _have_ a > document :-) Ah, sorry to post code that isn't very robust. I was just trying to give you an example so you could judge whether it might be suitable. I actually expected your answer to be that it was very far from being useful to you... In this case, you should probably look at "ie.busy", which you should monitor after things like ie.navigate() to make sure the documented has been fully loaded. My choice of www.nightsong.com was of course because that's the domain the OP posted from. I didn't stop to think someone might have a "www" subdomain which actually refused a connect request... strange if you ask me. -Peter From Hobbes2176 at yahoo.com Tue Jul 23 22:23:01 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Wed, 24 Jul 2002 02:23:01 GMT Subject: Make me beautiful (code needs help) References: Message-ID: <9co%8.2838$ub.168@nwrddc02.gnilink.net> Fernando Perez wrote: > For this kind of thing, look at Numeric. It has a ton of functions > ready-made for numerical processing, very convenient slicing syntax > (better than python lists) and as a bonus it's fast. Explicit loops in > python over large lists for numerical processing take an eternity and a > half. That's what Numeric is for. Fernando, Thanks for the tip. Is there a "HOWTO" doc on installing Numeric? I seem to recall looking at it awhile ago and seeing NumPy NumericPy NumPython NP (ok, I'm making them up now) ... point is, I got sorely confused as to what the current "numerics in python" package was. Regards, Mark From gerhard at bigfoot.de Fri Jul 19 23:46:30 2002 From: gerhard at bigfoot.de (Gerhard Haering) Date: Sat, 20 Jul 2002 05:46:30 +0200 Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) In-Reply-To: References: Message-ID: <20020720034630.GA28338@gargamel.hqd-internal> * eugene kim [2002-07-19 22:44 -0500]: > thank you for helping me.. > i'm sure that i encoded all strings to unicode > (title,url) > but it still gives me error.. > =) What about self.firsttime? As your code looks like: > cursor.execute("insert into history (col1, col1, col3) values (%s, %s, %s)", > (self.url, self.title, self.firsttime)) what about a print map(type, (self.url, self.title, self.firsttime)) to test if you're really not using any Unicode strings there? :-) > this is so cool.. what module do i need to use? pypgsql? Of course I'd be all for pyPgSQL :) But in this particular case, all other PostgreSQL modules work exactly the same. > yet another question, how do i check which module i have in my current > system? There's no good answer, as there is no databas of installed Python packages (yet). You can try to import and look if you get an ImportError: from pyPgSQL import PgSQL # pyPgSQL import psycopg # psycopg import pgdb # PyGreSQL to look which PostgreSQL modules you have installed. > (one more irrelevant question: is this also possible in java?) Java has Unicode strings only. And there's also a JDBC driver for PostgreSQL, which at some point will encode the Unicode strings to a bytestring for you. I'm not sure I understand your question, though. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From merkosh at hadiko.de Sun Jul 14 21:06:57 2002 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 14 Jul 2002 18:06:57 -0700 Subject: function parameter: question about scope Message-ID: hi, I've got a object method which works similar to the __deepcopy__() function of the copy/deepcopy protocol. this function takes an optional argument "memo={}": def getElements(self, types, memo={}): '''Returns a list of sub-elements.''' if memo.has_key(id(self)): return memo[id(self)] elements = super(Compound, self).getElements(types, memo) if (types == ()) or (self.__class__ in types): elements.extend ([self]) return elements This function checks wether self.__class__ is contained in 'types' and if so, it adds itself to the list 'elements' and returns it. The problem is, that 'memo' seems to live beyond method invocation - and I don't know why: If I call 'getElements( types=() )', the method works fine. The first call to 'getElements( types=() )' works fine, too. The parameter 'memo' seems to have remembered , because when I call 'getElements( types=() )' again I get the same result as in the previous call which is different to the first call. Calling 'getElements( types=(), memo={} )' works fine. Why does 'memo' keep exising? Thanks in advance Uwe From fredrik at pythonware.com Sun Jul 14 07:26:41 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Jul 2002 11:26:41 GMT Subject: Print a traceback from an extension? References: Message-ID: wrote: > Can I print a traceback from within a extension written in C? > > I know we're supposed to just keep returning NULL until we make it > back to the main loop. That normally works fine. > > But I'm calling Python code from a callback that is called by C > code. The Python code fails so PyEval_CallObject returns NULL. I want > to provide a helpful message at that point. > > Can this be done? If so, can someone suggest where to look for an > example? I usually use a small helper like this one: static void report_error(const char* message) { PyObject* sys_stderr; sys_stderr = PySys_GetObject("stderr"); if (sys_stderr) { PyFile_WriteString("*** error in my library: ", sys_stderr); PyFile_WriteString((char*) message, sys_stderr); PyFile_WriteString(" (see traceback for details):\n", sys_stderr); } PyErr_Print(); PyErr_Clear(); } ... function = PyEval_CallObject(...) if (!function) report_error("sorry, cannot call your object") From gerhard.haering at gmx.de Sat Jul 20 09:16:18 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Jul 2002 13:16:18 GMT Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: Alex Martelli wrote in comp.lang.python: > eugene kim wrote: > >> thx again.. >> >> i got PyGreSQL(pyPgSQL gave me error ImportError: No module named libpq) >> i looked at Well, for nearly all database modules you must actually compile them (they have parts written in C). How to do this for pyPgSQL is described in the README, and in the setup.py. For Debian and FreeBSD, it is available as packages from your distribution (look into the FAQ at http://pypgsql.sf.net for details). >>>>>help(pgdb) >> that was about all docs i could get including from web Check out the docs for the Python interface to the "Redhat database", which is just Redhat's fancy term for their supported version of PostgreSQL. It describes using pgdb, the DB-API2 layer of PyGreSQL in great detail. Link below. > Can't help you much here -- I use psycopg for the same task (interfacing > to PostgreSQL). You'll find that most DB interface modules more or less > follow the Python DB API, > > http://www.python.org/topics/database/DatabaseAPI-2.0.html > > http://www.amk.ca/python/writing/DB-API.html > (excellent, though it explains the previous DBAPI 1.0 so some > detailed differences are inevitable) > > http://initd.org/pub/software/psycopg/dbapi20programming.tar.gz > (you need TeX to format this one) Here's a very good one for PyGreSQL: http://www.redhat.com/support/resources/howto/database/database_python/ I've already got permission from its author to adapt this for my planned pyPgSQL handbook, which will also allow me to learn some more Docbook/XML :) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mwh at python.net Tue Jul 9 09:53:16 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 9 Jul 2002 13:53:16 GMT Subject: `~/.pythonrc' `from __future__ import' References: Message-ID: bellman at lysator.liu.se (Thomas Bellman) writes: > Tim Peters wrote: > > > [Fran?ois Pinard] > > >> I would rather have all future features available all the time when I > >> write interactively, yet I guess why some people would prefer not. > > > There's no way to do that, short of fiddling Python's source code. > > Well... At least under Unix there is a way... Put this code in > your ~/.pythonrc: You're a bad man! Cool hack, though. Cheers, M. -- Presumably pronging in the wrong place zogs it. -- Aldabra Stoddart, ucam.chat From gerhard.haering at gmx.de Mon Jul 29 01:06:52 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Mon, 29 Jul 2002 07:06:52 +0200 Subject: How to install Jython? In-Reply-To: <3D44C9CC.A0DBC792@bellatlantic.net> References: <3D44C9CC.A0DBC792@bellatlantic.net> Message-ID: <20020729050652.GA60500@gargamel.hqd-internal> * David Lees [2002-07-29 04:50 +0000]: > I need very basic configuration advice to install jython-21 on my > win98SE box. I am doing something wrong. I downloaded > jython-21.class.exe but am unable get it do self-extraction. I gather > that this is not an windows .exe, Yes, it's a class file. Your broser is pulling your leg. > but some sort of machine independent self extracting file that you run java > to extact. Indeed, a Java class file :-) Just rename it to jython-21.class, then follow the instructions from http://www.jython.org/install.html Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From aleax at aleax.it Thu Jul 11 10:28:15 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 14:28:15 GMT Subject: What does "Sparse is better than dense" mean? (Python Zen) References: Message-ID: <3CgX8.68516$vm5.2504519@news2.tin.it> Mark McEahern wrote: >> Although it's in the Humor section I take the Python Zen >> (http://www.python.org/doc/Humor.html#zen) quite seriously. >> However I can understand what does “Sparse is better than >> dense” means. > > Here's one of my pet peeves: > > if x: do_one_thing() > > or: > > try: foo() > except: pass > > The problem with collapsing these single statement blocks into one line is > that it complicates visual scans of a block of code. It certainly doesn't > make a hill of beans difference to the compiler. It definitely doesn't make any difference to the compiler, but it makes a huge difference to ME, as a human reader of the code, to avoid wasting a line and thus fitting more lines onto a screen. This is particularly important with small screens, such as the Sharp Zaurus' 300x200 screen or thereabous, but even on large screens it lets me use a larger and thus more readable font for any given amount of lines that I need to see at once on-screen. Personally, I have no difficulty whatsoever "visually scanning" these constructs -- the lack of any indented line under the keyword stands out and quite effortlessly makes my eyes glide rightwards. I MUCH prefer to use entirely blank lines for separation of _semantically *meaningful* blocks_ of code, rather than breaking every compound statement into more lines than needed, most particularly when such a compound statement corresponds to a single "compound thought". MY pet peeve is to spell "terminate the loop when X > Y" and similarl obviously-single concepts as TWO lines...: if X > Y: break Consider a typical "Loop-and-a-half" (Knuth) construct with a few statements before and after the conditional-brak: style A: while True: prelim_one() X = prelim_two() Y = another_thing(X) if X > Y: break yet_another(X, Y) prepare_next(X+Y) style B: while True: prelim_one() X = prelim_two() Y = another_thing(X) if X > Y: break yet_another(X, Y) prepare_next(X+Y) Style B forgoes the wanton linebreak at the 'if' and invests that line (plus another presumably saved elsewhere by using no wanton breaks:-) to make the loop's exit condition stand out much better. I suspect we'll have (at best) to agree to disagree on the specifics of this. The general theme of the Subject, on which I suspect we CAN agree (even while fighting on the specifics:-), is: whitespace is a precious resource. That doesn't mean "hog it avidly", i.e., "make your code as dense as possible". It means "invest it wisely": use spacing in a consistent way that enhances readability and clarity of your code (preferably respecting the Python Style Guide PEP, http://www.python.org/peps/pep-0008.html). Alex From pinard at iro.umontreal.ca Fri Jul 12 10:37:30 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 12 Jul 2002 10:37:30 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: [Jonathan Hogg] > Consider if resolv.conf used XML - perhaps something looking like: > > > python.org > > > 123.45.67.89 > 87.65.43.21 > > > You might say that this is verbose and monstrous, Your wish is my command. This is verbose and monstrous! :-) > but it's readable and fairly obvious in meaning. The original non-XML format is also pretty readable and obvious in meaning. Surely, there are advantages to XML, but at first glance here, it seems we gain nothing but verbosity and monstrosity. In my opinion, the advantages have to be pretty real to justify such a change. We should not go XML for the only sake of going XML. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From cliechti at gmx.net Sat Jul 20 10:26:24 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Jul 2002 16:26:24 +0200 Subject: Using pointers References: <4210d7a2.0207200538.44a91c0f@posting.google.com> Message-ID: jkrahn at nc.rr.com (Joe Krahn) wrote in news:4210d7a2.0207200538.44a91c0f at posting.google.com: > Can I make a pointer to an object in Python? I know that all > objects/variables are references, but not in the same sense as in C. see the other post from Gon?alo. > How do I get multiple pointers to reference and modify one variable? you can store the variable in an other object. a class is such a thing or you can use a list: a = [0] b = a now b and a reference the same list adn you can get the first object of that list with a[0] or b[0] if you want to change it just say a[0] = 3 etc. a class is much nicer for such things. you maybe want to look at object oriented programming in general. class Storage: def __init__(self, value): self.value = value a = b = Storage(7) print a.value print b.value a.value = 5 print b.value chris -- Chris From sarmstrong13 at mac.com Tue Jul 9 12:21:36 2002 From: sarmstrong13 at mac.com (SA) Date: Tue, 09 Jul 2002 11:21:36 -0500 Subject: CGI Help Please. Message-ID: I've been working on a little test script so I can understand the functionality of the cgi module when writing a python cgi script. The goal is to redirect a page from a link o the stored value in a query string. (ex.TestFile). I've now managed to get my script to work part way. I got rid of the server error I was getting by changing: #!/usr/bin/env python To #!/sw/bin/python sw/bin is the directory where my default python is located. For some reason my Apache setup chokes on the /usr/bin/env executable. So this fixes the server error. I then set the program to display the value for the key "pageID", but what I get is: The test file is: ['testtxt'] Finished! What I would like to do now is take that dictionary value(testtxt), which is the name of the text file I would like to use, read the text in the text file and re-display this in a new web page. Basically what I have is a html template file and a lot of text files. My final script will take the query string from the href as a text file name and send that to the python cgi script. That value will then be used to look up the textfile, read it's data, and print the file in the body section between
 tags on a
new web page. With this script, I will have only a template file that needs
it's links updated when I add new textfiles instead off 100+ html files
needing to be constantly maintained.

So since I'm new to python and CGI, I've been 'hacking' around on my machine
with different codes trying to understand how the script would function. Can
anyone help me please?

Below is the test script I wrote:
#!/sw/bin/python

import cgi
import re

QueryString = cgi.parse_qs('pageID=testtxt')

for pageID in QueryString.keys():
    QValue = QueryString[ pageID]
#    passvalue = [Qvalue]
#    body = open("QValue", "r")
#    for line in body.readlines():
    print "Content-Type: text/plain\n\n"
#        print line
    
    print "The test file is:\n"
    print QValue
#    body.close()
    
print "Finished!"

Any ideas on what I'm doing wrong?

Thanks.
SA


-- 
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me



From ross at karchner.com  Thu Jul 25 19:48:55 2002
From: ross at karchner.com (Ross M Karchner)
Date: 25 Jul 2002 23:48:55 GMT
Subject: setup.py OS X issue
Message-ID: <20020725194854985-0400@news.mindspring.com>

Hey,

I am trying to install MySQLdb ( http://sourceforge.net/projects/mysql-
python )

and I am unable to install this


From jdavis at empires.org  Fri Jul 26 20:40:34 2002
From: jdavis at empires.org (Jeff Davis)
Date: Sat, 27 Jul 2002 00:40:34 GMT
Subject: performance problem in python 2.2
References:   <7xd6tayqt6.fsf@ruckus.brouhaha.com>  <7xptxaj9kq.fsf@ruckus.brouhaha.com>
Message-ID: <6_l09.28101$_M2.10183516@twister.socal.rr.com>

> 
> No, on most computers a C integer can't represent numbers like 2**64.
> It only has 32 bits.  If you multiply numbers together that overflow
> 32 bits, you'll get the wrong answer unless the language mysteriously
> converted them to floats for you (the rules for that are slightly
> obscure).
> 

If you read my C code, you'll see that I used the 'unsigned long long type' 
which is a 64-bit int. And I only stored 2^32 in it. When I needed to 
crunch the numbers, I treated 2^64 as p*p (because 2^64 == 
sqrt(2^64)*sqrt(2^64) == 2^32*2^32), and then I commuted the 
multiplication so it would happen in a way that wouldn't overflow. Maybe 
it isn't a solid algorithm, but it appears to have mostly worked, and as 
you can see I was thinking about something while I designed it. Granted, 
it was more a "sounded good at the time" kind of thing, but I at least 
don't think I'm overflowing my ints.

Regards,
        Jeff


From fperez528 at yahoo.com  Wed Jul 10 16:48:57 2002
From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=)
Date: Wed, 10 Jul 2002 14:48:57 -0600
Subject: Why self?
References: 
Message-ID: 

David LeBlanc wrote:

> Louis;
> 
> I think he was proposing an idea. I don't believe you can import from self,
> and i'm almost positive that "to ... export" isn't part of Python.
> 
>> In article , Huaiyu Zhu
>>  wrote:
>>
>> > The Pythonic way to use namespace is :-)
>> >
>> > from self import x, y, z, a, tseries
>> > y= x**2 * t/z + a * FFT(tseries)
>> > to self export y

True, but it would actually be pretty simple to write a pair of helper 
functions to do just that. In fact I have one for the second part which I use 
a fair bit:

def setattr_list(obj,alist,nspace = None):
    """Set a list of attributes for an object taken from a namespace.

    setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
    alist with their values taken from nspace, which must be a dict (something
    like locals() will often do) If nspace isn't given, locals() of the
    *caller* is used, so in most cases you can omit it.

    Note that alist can be given as a string, which will be automatically
    split into a list on whitespace. If given as a list, it must be a list of
    *strings* (the variable names themselves), not of variables."""

    # this grabs the local variables from the *previous* call frame -- that is
    # the locals from the function that called setattr_list().
    # - snipped from weave.inline()
    if nspace is None:
        call_frame = sys._getframe().f_back
        nspace = call_frame.f_locals

    if type(alist) in StringTypes:
        alist = alist.split()
    for attr in alist:
        val = nspace[attr]
        setattr(obj,attr,val)

I can then do:
...
seattr_list(self,'x y z a b c')
or 
seattr_list(self,['x','y','z','a','b','c'])

at the end of a method to replenish my self namespace. 

cheers,

f.

ps. I also have a little companion getattr_list(). I'm not sure if it's 
possible to inject back variables into the frame of a caller though, as I 
seem to recall that locals() is to be considered read-only.



From tim.one at comcast.net  Wed Jul 17 15:45:46 2002
From: tim.one at comcast.net (Tim Peters)
Date: Wed, 17 Jul 2002 15:45:46 -0400
Subject: map del efficiency python2.2 and 2.1
In-Reply-To: 
Message-ID: 

[John Hunter]
> pymalloc to the rescue.  I rebuilt 2.2 --with-pymalloc and the
> interminable delay was vanquished.

Cool!  It will be even better in 2.3 (see other posts in this thread).

> Now where do I go to get a deep understanding of my platform's (glibc
> 2.2.2) implementation of free and why it behaves so badly?

Study the source code, watch it in a debugger until your eyes bleed, and/or
try to engage its current maintainer(s) in discussion.  Python grew its own
pymalloc because platform mallocs are a diverse, finicky, and ever-moving
target -- it would truly be a full-time job to keep up-to-date on the subtle
quirks and disaster-modes of all of them, but now we only have to understand
ours.  And that's only a half-time job .





From spam at ob_scure.dk  Sat Jul  6 12:34:38 2002
From: spam at ob_scure.dk (Thomas Jensen)
Date: Sat, 06 Jul 2002 18:34:38 +0200
Subject: Using Python for processing of large datasets (convincing managment)
References: <3D27152C.8020108@obscure.dk.X> <3D271A91.3D571053@engcorp.com>
Message-ID: <3D271C1E.6000000@ob_scure.dk>

Peter Hansen wrote:



> If you email me offline I'd be happy to give you details from my
> current employer's extensive use of Python as a highly reliable
> and effective tool, and how it has never been an issue that 
> developers who know Python before they start working with it are
> not as common as weeds.

Thank you, I will!

> (Thomas, I assume null at obscure.dk.X is not a valid email address. ;-)
Ahem, sorry! It should be valid now, except the underscore.
(Perhaps I'm a bit paranoid about spam, but on the other side I get less 
than one spam mail pr. week, which I belive is rather low ;-)

-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)



From fredrik at pythonware.com  Wed Jul 10 05:28:31 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Wed, 10 Jul 2002 09:28:31 GMT
Subject: Converting a hex string to a number
References: <0017278C.C22236@smiths-aerospace.com>  <3d2b3c2f.3993392@news.dsl.pipex.com>  <3d2b69b6.15643974@news.dsl.pipex.com>  <3d2be255.329033@news.dsl.pipex.com>
Message-ID: <37TW8.47022$n4.11329907@newsc.telia.net>

Simon Foster wrote:

> Oh Fredrik, I bought your book too!

good.

page 12-14 should explain why eval is unsafe, I think.

page 38 mentions ways to convert strings to numbers, and
the quote on page 39 should tell you why matt's "re + eval"
approach can be dangerous...

the next time someone points this out, you could answer
"I know, I have the book" instead of "are you a troll"...






From marklists at mceahern.com  Thu Jul 11 15:01:03 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Thu, 11 Jul 2002 14:01:03 -0500
Subject: try..catch..finally?
In-Reply-To: <3D2DD2A0.6040500@NOSPAMREMOVETHISxs4all.nl>
Message-ID: 

not that i knew this from first hand experience--that's what google's for
--but python did have a try-except-finally before the 1.0 release.
you can read all about it here:

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=3967d908.363887342%4
0news.online.no

// m

-





From tim.one at comcast.net  Wed Jul  3 00:40:08 2002
From: tim.one at comcast.net (Tim Peters)
Date: Wed, 03 Jul 2002 00:40:08 -0400
Subject: python threads and the linuxthread pthread library
In-Reply-To: <20020702103730.L10625@prim.han.de>
Message-ID: 

[holger krekel]
> I have been told (at EuroPython and anywhere else) that removing the GIL
> is just too hard.

Greg Stein did it once, long ago.  Search for "free threading" in old
archives, perhaps particularly in the defunct Thread-SIG.  A single-threaded
Python program ran about 2x slower as a result; the need for mutual
exclusion doesn't go away, and in effect one honking giant hammer of a lock
(the GIL) got replaced with many teensy short-lived locks.  That's got
substantial overhead of its own, although I'm sure it could have been
significantly reduced if anyone had mountains of time to throw at it.

Removing the GIL would be substantially harder today.  There are both gross
and exceedingly subtle reliances on that the GIL is held, all over Python's
C code, and the extent of that reliance has only grown since Greg did his
experiment.

multiple-processes-remain-your-best-friends-ly y'rs  - tim





From ld at nospam.com  Fri Jul 26 21:44:38 2002
From: ld at nospam.com (Larry)
Date: Sat, 27 Jul 2002 01:44:38 GMT
Subject: UDP Multicast HELP!
References:    <3d3f969f$0$11269$afc38c87@news.optusnet.com.au>
Message-ID: 

"Steven"  wrote in message
news:3d3f969f$0$11269$afc38c87 at news.optusnet.com.au...
> > I truly appreciate you taking time to respond, but I really don't
> understand
> > what you are trying to explain to me.  Everything else in python seems
so
> > easy, and creating a tcp socket and udp socket is so easy, just a few
> lines
> > of code.  I am really surprised that there is no EASY way to join a
group.
>
> if you do a search at Google in the groups archive you should find plenty
of
> examples on using IP multicast in Python
>
> Some example code I found has been uploaded here:
>
> http://www.tetrica.com/quickdry/python/
>
> Steven

Thanks Steven (Gee, I sound like that Dell commercial)...that link did the
trick for me!

Larry




From sholden at holdenweb.com  Sat Jul 27 00:16:07 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Sat, 27 Jul 2002 00:16:07 -0400
Subject: Let's Talk About Lambda Functions!
References: <20020726024901.2725.176.Mailman@mail.python.org>  <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> <7x3cu6f8sv.fsf@ruckus.brouhaha.com>
Message-ID: <%7p09.24972$724.6065@atlpnn01.usenetserver.com>

"Paul Rubin"  wrote in message
news:7x3cu6f8sv.fsf at ruckus.brouhaha.com...
> Alex Martelli  writes:
> > It's not an issue of syntax sugar as superficial as what keyword to
> > use.  A REAL lambda, by any other name -- the ability to package up
> > ANY chunk of code, not just an expression -- might add power enough
> > to justify its existence.  Today's lambda's just deadweight.
>
> I agree that the current incarnation of lambda is deficient.  I
> think it should be strengthened so you can lambdafy arbitrary code,
> not eliminated.  The current version is better than nothing, though.
>
> I don't see why the anti-lambda contingent doesn't want to also
> get rid of anonymous scalar expressions.  I mean,
>
>    a = b + (c * d)
>
> the horror!  Why not insist on naming the subexpressions, e.g.
>
>    temp = c * d
>    a = b + temp

k00l! Then we *could* use

    (a)

to represent a single-element tuple.

that's-enough-ly y'rs  - steve
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------







From warkid at storm.ru  Tue Jul 23 14:36:09 2002
From: warkid at storm.ru (Kerim Borchaev)
Date: Tue, 23 Jul 2002 22:36:09 +0400
Subject: Overhead for local assignments (was: A better self)
In-Reply-To: <230720021211008411%pecora@anvil.nrl.navy.mil>
References: <230720021211008411%pecora@anvil.nrl.navy.mil>
Message-ID: <4941.020723@storm.ru>

Hello Louis,

  sorry if this message sounds offensive - it isn't supposed to ;-)

Tuesday, July 23, 2002, 8:11:00 PM, you wrote:

...

LMP> xRange time= 0.15076
LMP> tuple assign time= 0.958203999999
LMP> line time= 0.799539
LMP> fcn1 (class call) time= 1.508272
LMP> fcn2 (local call) time= 1.256834

...

LMP> Method (2) is fastest as some people suggested.  (1) does seem to
LMP> involve some time creating and destroying a tuple as suggested.  (3) is
LMP> the worst, by a factor of 2!  So if you have lots of class function
LMP> calls, assign the function to a local variable, but even better, avoid
LMP> using the function calls to just calculate a formula, if possible.

It feels like a general advice.
"lots of class function" - it lets everyone decide the meaning of
"lots" for himself; or how should I treat "to just calculate a
formula" - is it for any code that involves "the math"?

So I'd give another general advice:

- Make the code as clean as possible(using functions, methods - all
  the best of the language ) BEFORE you discover that it works too slow.
   
- And only whan you're absolutely sure(the tests show) that
  it's slow for your needs - think about optimization.
  
- Then profile test cases of interest to find out which pieces of code are
  worth optimizing to get a valuable speedup.

- Then optimize. ...or not yet?

Best regards,
 Kerim                            mailto:warkid at storm.ru





From chandan_mathur at hotmail.com  Thu Jul  4 21:00:41 2002
From: chandan_mathur at hotmail.com (chandan)
Date: 4 Jul 2002 18:00:41 -0700
Subject: win32com and internet explorer
References: <3d235b64$1@post.usenet.com> <6vZU8.409778$cQ3.28013@sccrnsc01>
Message-ID: 

"Emile van Sebille"  wrote in message news:<6vZU8.409778$cQ3.28013 at sccrnsc01>...
> chandan mathur
> >     I am new to python/programming.. I was trying to read and save a
>  page
> > from the internet using win32com and internet explorer..., easy rite?
> 
> Yep... but in python without win32com and ie:
> 
> >>> import urllib
> >>> fp, info = urllib.urlretrieve("http://www.google.com")
> >>> content = open(fp).readlines()
> >>> content

Hi.. thanx for the reply..., i have used urllib before, but i need to
retrieve a https ssl secured page..., so i thought of lettin internet
explorer do all the dirty work of handling https.. since i had no luck
with the httpshandler from urllib2 (some socket problem.. i can't
figure out). Is there an alternate way of handling this problem?

help appreciated
Chandan


From mcfletch at rogers.com  Wed Jul 10 01:26:52 2002
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Wed, 10 Jul 2002 01:26:52 -0400
Subject: [Ann] SimpleParse 2.0.0a2 available
Message-ID: <3D2BC59C.7070703@rogers.com>

URL:
	http://simpleparse.sf.net/

Release Notes:
	The alpha-2 release is basically to let people play with the new version, 
it's not production quality code by a long shot.

What is SimpleParse (from the website):

SimpleParse is a BSD-licensed Python package providing a simple parser 
generator for use with the mxTextTools  text-tagging engine. SimpleParse 
allows you to generate tagging tables for use with the text-tagging 
engine directly from your EBNF grammar.

Unlike most parser generators, SimpleParse generates single-pass parsers 
(there is no distinct tokenization stage), an approach taken from the 
predecessor project (mcf.pars) which attempted to create "autonomously 
parsing regex objects". The resulting parsers are not as generalized as 
those created by, for instance, the Earley algorithm, but they do tend 
to be useful for the parsing of computer file formats and the like (as 
distinct from natural language and similar "hard" parsing problems).

In addition to the parser generator, the SimpleParse project includes a 
sub-project to create a modified version of the mxTextTools engine which 
reorganizes the code to allow for certain common EBNF constructs to be 
readily implemented.


Enjoy yourselves,
Mike
_______________________________________
   Mike C. Fletcher
   http://members.rogers.com/mcfletch/






From stephen at xemacs.org  Fri Jul  5 10:14:57 2002
From: stephen at xemacs.org (Stephen J. Turnbull)
Date: Fri, 05 Jul 2002 23:14:57 +0900
Subject: [OT] What is Open Source? (was Re: ANN: Twisted 0.16.0...)
References: 
	
	
	
	
	
	
	<87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp>
	<20020417135054.A88552@doublegemini.com>
	<87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp>
	<20020703214452.A28696@doublegemini.com>
Message-ID: <87adp69s7y.fsf@tleepslib.sk.tsukuba.ac.jp>

>>>>> "Clark" == "Clark C. Evans"  writes:

    Clark> Not that you have to believe in RMS's vision

    sjt> But I do believe in RMS's vision of a free-software-only world.

    Clark> I don't.  I firmly believe that copyright and patent are
    Clark> fundamentally good ideas (trademark is the best of the
    Clark> three).

Believing in a free-software-only world doesn't mean I think
intellectual property is wrong.  It means that I would like to strive
for a world in which the instruments are not used much, if at all.  At
least for software.  See below.

    Clark> Unfortunately, over the last century, our government has
    Clark> taken a good thing and turned the dial all the way up.
    Clark> Just like Food is good... too much food and you get FAT.
    Clark> Everything in moderation.

Well, IMO (not carefully researched), GNU shows that even permanent
_copyright_ in software would be no big deal.  Something I've
considered somewhat more carefully is the issue of patent; as far as I
can tell _in software_ patent is just a big gun that capital can hold
at the heads of authors.  But even for large software projects it is
rarely necessary to assemble a lot of capital all at once.  Therefore
I oppose patenting software in principle.

I don't mind rewarding very smart people such as RSA or Karmarkar, who
find ways to implement specifications that others cannot, even with a
blackbox demonstration that it can be done.  However they are extremely
rare.  Mostly patent is used to protect monopolies and oligopolies,
and serves the interest of Corporate Legal, not Corporate R&D, let
alone those who work on the software directly.

    Clark> what I do find fault is that the laws are currently so out
    Clark> of ballence that they have lost all legitimacy.

I agree that it's a question of balance.

But I think that (_in software_), compared to the cost of reinventing
most patents, the transaction cost of negotiating a license and paying
the royalty is absurdly high, enough so that setting the "novelty and
inventiveness" bar at infinity is a reasonable approximation.  (I used
to think otherwise, but I've changed my mind over time---I might
change it again. :-)

    Clark> GNU software has yet to be seriously challenged and when it
    Clark> is only the copyright holder can enforce challenges.
    Clark> Currently there is much GPL software out there that is not
    Clark> owned by anyone (just try and find the owner for some

I have.  It hasn't been hard---but I have had no luck with getting
assignments.  Evidently authors often aren't interested in enforcing;
they're just stuck with the license because the work is derivative.

    Clark> peices) and as such, enforcing it will be damn near
    Clark> impossible.

For those who believe in free software and wish to use their works to
encourage more free software to be written, the GPL is the odds-on
candidate for the best tool.  Such people should, as you point out,
either carefully consider the consequences of having to defend their
rights themselves or assign to the FSF.

But many of us don't really care to enforce copyleft.


-- 
Institute of Policy and Planning Sciences     http://turnbull.sk.tsukuba.ac.jp
University of Tsukuba                    Tennodai 1-1-1 Tsukuba 305-8573 JAPAN
 My nostalgia for Icon makes me forget about any of the bad things.  I don't
have much nostalgia for Perl, so its faults I remember.  Scott Gilbert c.l.py




From d2002xx at yahoo.co.uk  Fri Jul 19 00:08:34 2002
From: d2002xx at yahoo.co.uk (d2002xx)
Date: 18 Jul 2002 21:08:34 -0700
Subject: Tkinter vs. wxPython
References: 
Message-ID: 

> My question is this: is there any compelling reason I shouldn't just go
> with Tkinter instead? I work (for now) exclusively on Win32 boxes, by
> the way.

Just compare the number of widgets in wxPython and Tkinter, you will
find out tkinter is almost useless. I'm wondering why python doesn't
use wxPython (or PyQT) as default GUI.


From LogiplexSoftware at earthlink.net  Wed Jul 31 14:21:27 2002
From: LogiplexSoftware at earthlink.net (Cliff Wells)
Date: 31 Jul 2002 11:21:27 -0700
Subject: Use python without install it.
In-Reply-To: 
References: 
Message-ID: <1028139687.2415.47.camel@software1.logiplex.internal>

On Wed, 2002-07-31 at 08:58, Bertrand Geston wrote:
> Hi,
> 
> Does somebody know if it is possible to use python on a computer under Linux
> on that it's not allowed to install it for security reasons (server in
> production) ?

Why would installing Python be a security risk?  If someone were able to
get enough access to the server that they could run an installed copy of
Python, I'm guessing they'd be able to install their own if it weren't
already there. 

Or are you simply hoping the added inconvenience of the installation
(after hours/days of hacking a Linux box) will dissuade them? ;)

> The purpose is to have some shell scripts written in Python to make some
> maintenance tasks. Those scripts are launched manually.
> 
> Run it from a CD rom ? How ?
> Special user ? is it really secure ?
> Other idea ?
> 
> TIA.
> 
> B.
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




From guidance_shanghai at yahoo.com.cn  Sun Jul  7 01:54:30 2002
From: guidance_shanghai at yahoo.com.cn (Leon Wang)
Date: 6 Jul 2002 22:54:30 -0700
Subject: Chinese language support of Python?
References:  <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl> 
Message-ID: 

Hi, I got the Chinese displayed correctly in window title without
change the default encoding in site.py by:

root.title(u'\u4e2d\u6587')

But still can not put Chinese directly as string in source, I can not
live with so much \u... for a whole Chinese sensence/paragraph, it's
impossible to read and edit them :(
However, I can print Chinese string (normal string, without u prefix
and \u codes) in console with command line python.exe. How can I let
Tkinter accept that?

martin at v.loewis.de (Martin v. Loewis) wrote in message news:...
> Boudewijn Rempt  writes:
> 
> > > root.title('中文') # this is Chinese
>  [...]
> > If you use _real_ unicode -- for instance 
> >  root.title(u'\u028A\u0288') # no chinese, because of lacking fonts, but IPA
> > then everything works fine -- at least, with my window manager, on my OS.
> 
> It's more likely that the OP meant
> 
> root.title(u'\u4e2d\u6587')
> 
> Regards,
> Martin


From whisper at oz.net  Wed Jul 10 13:49:02 2002
From: whisper at oz.net (David LeBlanc)
Date: Wed, 10 Jul 2002 10:49:02 -0700
Subject: Pyrhon language dedicated Wiki
In-Reply-To: 
Message-ID: 

Danial;

>From all I've read on the subject by Ward Cunningham (Wiki inventor) and the
advocacy pages on TWiki.org, it takes time, pages and a willingness to
promote in order to get people to start using a Wiki. Even then, use starts
off gradually and then starts to build.

One example of promoting is adding (what you hope will be interesting) pages
and then announcing them on c.l.py: "Today I added the start of a great
article on threading - come, take a look and add your comments!" (that one
ought to at least get a comment out of Aahz ;)).

It's not a matter of "If we build it, they will come" - you're going to have
to make it desirable to come...

HTH,

David LeBlanc
Seattle, WA USA

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Daniel Dittmar
> Sent: Wednesday, July 10, 2002 6:06
> To: python-list at python.org
> Subject: Re: Pyrhon language dedicated Wiki
>
>
> Fredrik Lundh wrote:
> >> maybe we should start here:
> >>
> >>     http://www.python.org/cgi-bin/moinmoin/Python
> >>
> >> and see what happens...
> >
> > from what I can tell, nothing happened.
> >
> > I'll restore the wiki to it's original "historical" state, when
> > I find the time.
>
> Could you wait a few days more? I didn't follow that link when I searched
> for it, but used the search function on python.org. And that led
> me only to
> the old version.
>
> I promise to sketch a topic guide for web development in the next
> two days.
> Maybe that gets something started.
>
> Daniel
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list





From dwelch91 at nospam.attbi.com  Fri Jul 19 10:50:11 2002
From: dwelch91 at nospam.attbi.com (djw)
Date: Fri, 19 Jul 2002 14:50:11 GMT
Subject: Python v.s. huge files PROBLEM!!
References: <11e94203.0207181433.1c32f5bc@posting.google.com>
Message-ID: <3D382723.2020201@nospam.attbi.com>

Jose Rivera wrote:
> Hi..
> Scenario:
> OS      : WinNT 4.0
> FileName: RESPALDO_MENSUAL_Data.MDF
> Size    : 243,386,941,440 bytes
> 
> Problem:
> I want to copy this file to another disk. Both disks have 500 GB of
> free space.
> 
> Microsoft problem:
>    You May Not Be Able to Copy Large Files on Computers That Are
> Running Windows NT 4.0 or Windows 2000 (Q259837)
> 
> Workaround suggested by Microsoft:
>    Use Backup / Restore utilities
>   Result: They didn't work either... using HP OmniBack
> 
> Workaround made by us:
> Make a python program that read and writes to the other file in
> theother disk.
> 
> Python Code:
> 
> import sys
> 
> if len(sys.argv) != 3:
> 	print 'Format:'
> 	print '\t pyCopy.exe SourceFile EndFile'
> else:
> 	fn1=sys.argv[1]
> 	fn2=sys.argv[2]
> 	f1=open(fn1,'rb')
> 	f2=open(fn2,'wb')
> 	data=f1.read(1024*1000)
> 	while data:
> 		f2.write(data)
> 		data=f1.read(1024*1000)
> 	f1.close()
> 	f2.close()
> 
> Result:
> IOError: [Errno 22] Invalid argument
> 
> Question:
> Is there anything wrong?



If buffered I/O doesn't work, how about non-buffered I/O?

According to MSDN:

Use CreateFile for Non-Buffered File I/O
If your application performs file input or output without using the 
intermediate buffering or caching provided by the system, the 
application must call CreateFile with the FILE_FLAG_NO_BUFFERING flag 
set when opening the file. In this case, your application must pass a 
buffer to ReadFile or WriteFile that is correctly aligned for the 
device. Note that the alignments changed for some devices with Window 
2000. For more information, see the FILE_FLAG_NO_BUFFERING description 
in the CreateFile section and the VirtualAlloc section.
One way to align buffers on integer multiples of the volume sector size 
is to use VirtualAlloc to allocate the buffers. This function allocates 
memory that is aligned on addresses that are integer multiples of the 
operating system's memory page size. Because both memory page and volume 
sector sizes are powers of 2, this memory is also aligned on addresses 
that are integer multiples of a volume's sector size. Your application 
must make sure that it reads and writes in multiples of the actual 
sector size of the input or output device. An application can determine 
a volume's sector size by calling the GetDiskFreeSpaceEx function.


So how about some code that looks vaguely like this (only tested a 
little bit, no error checking and no guarantees!)
(Note the use of win32con.FILE_FLAG_NO_BUFFERING):


import win32file, win32con, win32api

fn1=sys.argv[1]
fn2=sys.argv[2]

f1 = win32file.CreateFile( fn1,
                            win32con.GENERIC_READ,
                            win32con.FILE_SHARE_READ,
                            None,
                            win32con.OPEN_EXISTING,
                            win32con.FILE_FLAG_NO_BUFFERING,
                            0)

f2 = win32file.CreateFile( fn2,
                            win32con.GENERIC_WRITE,
                            win32con.FILE_SHARE_WRITE,
                            None,
                            win32con.CREATE_ALWAYS,
                            win32con.FILE_FLAG_NO_BUFFERING,
                            0)

# bad assumption of using C: in next line! Need to change...
spc, bps, fc, tc  = win32file.GetDiskFreeSpace( "c:\\" )
bpc = spc * bps # = 4096 on my XP box

while 1:

     hr, r1 = win32file.ReadFile( f1,
                                  bpc )

     e, bw  = win32file.WriteFile( f2,
                                   r1 )

     if bw == 0: break

win32api.CloseHandle( f1 )
win32api.CloseHandle( f2 )


Worked on my system for a 19Mb file...  way smaller than yours, but
I don't have many 243Gb files laying around... in fact this was the
largest file on my harddrive!

I could not figure out how to tell when ReadFile() was complete. The 
param that is usually passed back from the Win32API - 
lpNumberOfBytesRead  - is not returned by the Python wrapping of the 
function (don't know why not). However, the check for bytes written 
(returned by win32file.WriteFile() seems to do the trick.

Also, note that I used GetDiskFreeSpace(), not the Ex version. I think
there is an error in MS's docs - the Ex version doesn't return the
cluster sizes and such like the non-Ex version.

Regards,

Don



From aleax at aleax.it  Fri Jul  5 11:07:19 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 05 Jul 2002 15:07:19 GMT
Subject: metaclass & __slots__
References:  
Message-ID: 

Jonathan Hogg wrote:
        ...
> Unfortunately, you can't set or modify __slots__ in the __init__ method of
> a metaclass. The damage has already been done by the time you get to the
> __init__ method:
        ...
> You need to make the change in the __new__ method before the class is

Perfectly right!  I should have checked whether __slots__ was taken into
consideration in type's __new__ or __init__, but I was lazy or hurried and
just focused on the obvious issue that the original poster's code called
type.__init__ at the start of the custom metaclass's own __init__, so it
wouldn't have worked "even if" it was type.__init__'s job, rather than
type.__new__'s, to implement __slots__.  Thanks for the correction!


Alex



From erict at millfilm.co.uk  Mon Jul 22 13:58:18 2002
From: erict at millfilm.co.uk (Eric Texier)
Date: Mon, 22 Jul 2002 18:58:18 +0100
Subject: xmlrpclib question
References: <3D3BFA10.92E38B5B@millfilm.co.uk> 
Message-ID: <3D3C47BA.3339925A@millfilm.co.uk>

Yes, thank you I understand now.
This is a nasty habit to have to believe that:
if server is not None:   ==   if server:


Fredrik Lundh wrote:

> Eric Texier wrote:
> > I posted this question earlier but I am still confuse about what
> > I am doing wrong. Why, in the class 'clientRootTask' just taking
> > out the 'if' statement will make it work:
>
> what did you expect that if statement to do?
>
> as written, you're asking the server if it's "true".  to figure that
> out, Python calls the proxy object's __nonzero__ method, which
> the proxy happily forwards to the server.
>
> maybe you meant "if server is not None"?
>
> 



From claird at starbase.neosoft.com  Wed Jul 24 16:52:25 2002
From: claird at starbase.neosoft.com (Cameron Laird)
Date: 24 Jul 2002 15:52:25 -0500
Subject: GUI toolkits
References:  
Message-ID: 

In article ,
Steve Menard  wrote:
			.
			.
			.
>I personally settle on wxWindows. I will not say I like it. I am used to
>SWING and wxWindows is painful to use. But it works as well on all supported
>platforms.
>
>    Steve
>
>

You *like* Swing?

Do you want to recommend Jython to the originator of the thread?
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://starbase.neosoft.com/~claird/home.html


From philippe.gendreau at savoirfairelinux.com  Wed Jul 24 17:01:14 2002
From: philippe.gendreau at savoirfairelinux.com (Philippe Gendreau)
Date: Wed, 24 Jul 2002 17:01:14 -0400
Subject: syntax questions
In-Reply-To: <3D3EEF16.5040404@destiny.com>; from mcherm@destiny.com on Wed, Jul 24, 2002 at 02:16:54PM -0400
References: <3D3EEF16.5040404@destiny.com>
Message-ID: <20020724170114.A29182@xmailer.ods.org>

* Michael Chermside  [2002-07-24 14:16]:
> > I know about the dir() function,  but I'm surprised that my list object
> > hides a function object (even if they have the same name). 
> > Is that how python treats names all the time? Does it mean you can't
> > have a class, def and variable of the same name?
> 
> Yes, that's how it works all the time.
> 
> Actually, the ADVANTAGE of this is that you aren't required to memorize 
> the entire list of all built-in functions and things. For instance, if 
> you NEVER, EVER use the "input" function (as well you shouldn't), then 
> it's not going to hurt you if you use a line like:
> 
>      for input in sys.stdin:
>          process(input)
> 
> Of course, it's still not a good idea, but you aren't forced to memorize 
> the list of built-in stuff, nor does old code break when a new built-in 
> function is added (which happens rarely, but does happen).
> 
> As for having a class, a "def" (ie, function), and a variable all with 
> the same name, no... not in the same namespace. And this is good. 
> Because in Python (unlike some languages), a function, a class, and a 
> "variable", are all objects, and can be used interchangably.
> 
> Consider the map() function. It is normally passed a function as its 
> first argument and applies it to the items in a list:
> 
>      >>> def add5(x):
> 	    return x + 5
>      >>> map( add5, range(4) )
>      [5, 6, 7, 8]
> 
> But classes are instantiated by calling them, as if they were functions. 
> So we can pass a class in, where it expects a function, and it all works 
> just fine:
> 
>      >>> from UserString import UserString
>      >>> map( UserString, range(4) )
>      ['0', '1', '2', '3']
> 
> We could even use a variable to store the item to pass... resulting in 
> code like this:
> 
>      >>> f1 = add5
>      >>> f2 = UserString
>      >>> [ map(f, range(4)) for f in f1, f2]
>      [[5, 6, 7, 8], ['0', '1', '2', '3']]
> 
> So the fact that all things are just "objects" and don't have separate 
> namespaces is highly useful, since it comes closer to making 
> "everything" first class objects, giving the language more power.

Thanks it makes sense, I see where it can be useful.
I think I'm gonna like python...
--
Philippe Gendreau



From cce at clarkevans.com  Fri Jul 12 20:29:47 2002
From: cce at clarkevans.com (Clark C . Evans)
Date: Fri, 12 Jul 2002 20:29:47 -0400
Subject: XML overuse? (was Re: Python to XML to Python conversion)
In-Reply-To: ; from jonathan@onegoodidea.com on Fri, Jul 12, 2002 at 09:07:53AM +0100
References:   <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com>  
Message-ID: <20020712202947.D2393@doublegemini.com>

On Fri, Jul 12, 2002 at 09:07:53AM +0100, Jonathan Hogg wrote:
| I'm not sure it is possible to "overuse" XML. If you need to read and write
| structured data, why bother coming up with your own format? (see: the entire
| contents of /etc) Or why use something that is proprietary to a particular
| language or system? (see: Pickle)

For my purposes, YAML (http://yaml.org) is doing just
perfectly.  It has lots of advantages over XML, first 
it is readable and second it uses native Python objects
(instead of a document object model)

Best,

Clark
Yo! Check out YAML!
http://yaml.org

-- 
Clark C. Evans                   Axista, Inc.
http://www.axista.com            800.926.5525
XCOLLA Collaborative Project Management Software




From hst at empolis.co.uk  Fri Jul 12 11:03:36 2002
From: hst at empolis.co.uk (Harvey Thomas)
Date: Fri, 12 Jul 2002 16:03:36 +0100
Subject: XML overuse? (was Re: Python to XML to Python conversion)
Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C7C@hendrix.empolisuk.com>

Fran?ois Pinard wrote:
[...snip...]
 
> I do not think so.  SGML already has these virtues, and much 
> more than XML.
> The main goal of XML was to please machines, because full SGML is so
> difficult to parse.  The price to pay to please machines was a loss of
> readability for humans.  XML is so verbose that real information gets
> overwhelmed under tags.  The fish often gets drawn in practice.

[..snip...]

I think you should substitute "software writers" for "machines". A full SGML parser, which must always be validating, is indeed very hard to write (I only know of two that really meet the spec), but an XML parser, particulatly a well-formdness only parser, is much easier to write.

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




From jdhunter at nitace.bsd.uchicago.edu  Fri Jul 26 12:15:24 2002
From: jdhunter at nitace.bsd.uchicago.edu (John Hunter)
Date: Fri, 26 Jul 2002 11:15:24 -0500
Subject: Derivative of string as a name of list or dictionary (or
 class?)
References: <82fe0bb.0207260749.3059e20a@posting.google.com>
Message-ID: 

>>>>> "Roman" == Roman Tarantowicz  writes:

    Roman> I received string1, string2, ... etc from handle_data in
    Roman> MyParser(SGMLParser)

    Roman> I dont know how to create list or dictionary which name be
    Roman> derivative of the received string?

    Roman> I would like to have the following containers:

    Roman> Top_Category = [derivative_of_string1,
    Roman> derivative_of_string2, ...]

    Roman> Derivative _of_string1 = [derivative_of_another_string1,
    Roman> derivative_of_another_string2, ...]

    Roman> Derivative_of_another_string1 = {'id1': 'str1', 'id2' :
    Roman> 'str2', ...}

    Roman> Is this any direct method or I have to apply something
    Roman> complicated as a Factory Pattern (is it possible to
    Roman> automate producing new classes which names will be given
    Roman> during execution of program)?  Any tips or direction in
    Roman> which my mind should be pushed I'll embrace wholeheartedly
    Roman> ;)

If you want to set attributes of a class you can use setattr and name
the attributes with a string, as in

class SomeClass:
    pass

name = 'seq'
val = ['John', 'Hunter', 'was', 'here']

x = SomeClass()
setattr(x, name, val)

print x.seq
#or
print getattr(x,name)

If you want to set variable names in the global namespace, I am
reasonably sure you can do a similar thing by manipulating a global
object, but I don't know what it is.  You can always use exec, but you
will probably have people frown at you

name = 'seq'
val = ['John', 'Hunter', 'was', 'here']
exec('%s=val' % name)
print seq

But I would hold out to see if a better solution exists.

John Hunter


From irmen at NOSPAMREMOVETHISxs4all.nl  Tue Jul 23 18:24:07 2002
From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong)
Date: Wed, 24 Jul 2002 00:24:07 +0200
Subject: A better self
References:  <2259b0e2.0207231348.7496eca0@posting.google.com>
Message-ID: <3D3DD787.4060906@NOSPAMREMOVETHISxs4all.nl>

Michele Simionato wrote:

> It has not been mentioned in this thread, but there a simple way to cope 
> with this problem without changing the language: a Python preprocessor.

This will work if you know that the code you're dealing with has to be
processed first before it is real Python code.

It will not work if you are somehow unable to run the preprocessor first.
Think about importing modules. They have to be processed first,
otherwise the import will not work because the module is not correct
Python code.

Irmen.



From skip at pobox.com  Sat Jul 20 22:36:56 2002
From: skip at pobox.com (Skip Montanaro)
Date: Sat, 20 Jul 2002 21:36:56 -0500
Subject: Funny behaviour of MySQLdb
In-Reply-To: <20020720173325.51C943E6AB@cali-2.pobox.com>
References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de>
        
        <15673.23606.257022.388489@localhost.localdomain>
        <20020720173325.51C943E6AB@cali-2.pobox.com>
Message-ID: <15674.7752.888722.873627@localhost.localdomain>

    Alex> If MySQLdb.threadsafety >= 2, and there are no errors in your
    Alex> implementation, you're supposed to be safe.  

I just checked the docs for MySQLdb.threadsafety (version 0.9.2).  It's
value in that version is 1.  About this the docs says:

    The MySQL protocol can not handle multiple threads using the same
    connection at once....

    You can certainly do things like cache connections in a pool, and give
    those connections to one thread at a time. If you let two threads use a
    connection simultaneously, the MySQL client library will probably
    upchuck and die.  You have been warned.

I think this means I'm safe.  I do precisely what the second paragraph
suggests, cache several connections in a pool and give them out to one
thread at a time.

    Alex> If each "chat" is complicated enough and can't easily be
    Alex> encapsulated as a callable, you may even have some advantage wrt
    Alex> the architecture I'd consider even safer -- five dedicated
    Alex> threads, one per connection, all waiting for work requests on a
    Alex> single queue and returning results on a separate queue per
    Alex> requestor thread: you're saving a few resources by having 5 fewer
    Alex> threads and many fewer Queues around.

Each time I .get() a connection from the pool, I do tend to execute multiple
SQL statements.  Using a fixed numbers of threads associated with each
connection is a bit more complicated, especially since I already wind up
with a thread per request courtesy of SocketServer.ThreadingMixin.  Why
waste it? 

    Alex> But the moment problems should start appearing, good luck.  

Well understood.  I was really quite surprised that I had very few problems
as I added locks to the shared objects when I converted the server from
single to multiple threads.

Skip




From bh at intevation.de  Fri Jul 12 15:09:12 2002
From: bh at intevation.de (Bernhard Herzog)
Date: 12 Jul 2002 21:09:12 +0200
Subject: Q: What does "Sparse is better than dense" mean? (Python Zen)
References: <33803989.0207110328.5ef01f1e@posting.google.com>
Message-ID: <6q3cuon4pz.fsf@abnoba.intevation.de>

tebeka at cs.bgu.ac.il (Miki Tebeka) writes:

> Hello All,
> 
> Although it's in the Humor section I take the Python Zen
> (http://www.python.org/doc/Humor.html#zen) quite seriously.
> However I can understand what does "Sparse is better than
> dense" means.

Simple: Dense code much like mass increases the space-time curvature and
hence interferes with the operation of the time-machine.

Even though the time-machine itself uses dense code to warp space time
it does so with a Perl interpreter[1]! That language is hopelessly
entangled with the continuum (quite intentionally[2]) but Python is
still light enough to be easily influenced by time-travellers.
Unfortunately, it seems to be getting harder, otherwise the number of
proposed incompatible changes to fix earlier design mistakes wouldn't
have to increase.


[1]: According to http://groups.google.com/groups?selm=an_614140340, timbot
     said (after the time-machine crash at Roswell, 1947):

     "For some decades, at least. It will be a long time before
      technology develops far enough for us to build a new time machine. The
      blueprints I have call for a Perl interpreter, for instance. We need
      spacetime convolution regexes."

[2] Same source as [1].



   Bernhard

hoping-that-non-existing-tree-letter-organization-won't-


From ggossen at hotmail.com  Fri Jul  5 16:55:20 2002
From: ggossen at hotmail.com (Gordian Gossen)
Date: 5 Jul 2002 13:55:20 -0700
Subject: XML content in a POST request (httplib)?
Message-ID: <9e495aef.0207051255.3d10a628@posting.google.com>

Hello,

I would like to transmit the content of a XML-file in the body of a
POST request.

-------------------------------------------------------------
What i did not understand:
--------------------------

How to put the a string, which contains the XML content, into the body
without making a key value pair?

Does I need a key value /pair to transmit data in the POST request
body?

-------------------------------------------------------

The examples I found about httplib always transmitt one or more key /
value pairs.

eg.
...
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
...
conn.request("POST", "/cgi-bin/query", params, headers)


-------------------------------------------

Thank you for your time.

MFG.
Gordian Gossen

-------------------------------------------------
p.s. 
I am making my diploma at University of Applied Science in Germany and
hang with at this point.

Please help.


From ld at nospam.com  Tue Jul 16 14:51:52 2002
From: ld at nospam.com (Larry)
Date: Tue, 16 Jul 2002 18:51:52 GMT
Subject: Making code faster
References: 
Message-ID: 

"Sean 'Shaleh' Perry"  wrote in message
news:mailman.1026839920.5742.python-list at python.org...

> Have you actually used a profiler on the code to see where the time was
going?

What's a profiler...and how is it used to see where the time is going?

Larry




From maxm at mxm.dk  Wed Jul  3 16:35:14 2002
From: maxm at mxm.dk (Max M)
Date: Wed, 03 Jul 2002 22:35:14 +0200
Subject: Tuples --> How to use them ?
References: 
Message-ID: <3D236002.4040401@mxm.dk>

Marcus Vinicius Laranjeira wrote:

> Supose I have an arbitrary tuple of values that came from a sql query. I 
> need to run this algorithm:
> 
> t1 <-- new tuple
> t1 <-- results from an arbitrary query
> l <-- new list
> for each value in the tuple do:
>     a <-- new tuple
>     add this value to the tuple a
>     add the tuple a to a the list l
> 
> i.e. I need to create a list of tuples and these tuples will have one, 
> and only one, number that came from the original tuple.

l = [(value,) for value in t1]

If I understand the problem correctly??

regards Max M



From cce at clarkevans.com  Wed Jul  3 21:44:52 2002
From: cce at clarkevans.com (Clark C . Evans)
Date: Wed, 3 Jul 2002 21:44:52 -0400
Subject: [OT] What is Open Source? (was Re: ANN: Twisted 0.16.0...)
In-Reply-To: <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp>; from stephen@xemacs.org on Thu, Apr 18, 2002 at 04:31:22PM +0900
References:        <87zo083vgg.fsf@tleepslib.sk.tsukuba.ac.jp> <20020417135054.A88552@doublegemini.com> <87k7r5qx85.fsf@tleepslib.sk.tsukuba.ac.jp>
Message-ID: <20020703214452.A28696@doublegemini.com>

On Thu, Apr 18, 2002 at 04:31:22PM +0900, Stephen J. Turnbull wrote:
|     Clark> There is a difference between "trademark" and "copyright".
|     Clark> RMS firmly believes in trademarks;
...
|     Clark> as it does not hurt your ability to fork the code and
|     Clark> do-as-you-please.
| 
| Hmm.  This is a good point.  rms certainly displays an emotional
| attachment to some of the code (especially Emacs)[1], which I have
| confused with belief in a property-like right to control.  But what
| really is happening is that he uses his control over GNU and FSF
| resources (eg, for development and distribution), and moral suasion.
| He's not using control over the code itself.
| 
| So this is consistent with denial of property right in software.
| Rather, he's saying "don't hijack my _effort_ for purposes I don't
| like; isn't the software itself enough?"
| 
| Thank you, that helped.

Welcome (thanks for reading ;)

|     Clark> Not that you have to believe in RMS's vision
| 
| But I do believe in RMS's vision of a free-software-only world.

I don't.  I firmly believe that copyright and patent are 
fundamentally good ideas (trademark is the best of the three).
They are a contract between the public as a whole to a inventor/author.
It goes something like this, to encourage disclosure
of works which will benifit society at large, we will grant you
a few particular rights for a limited time.  It is a ballence.
Too many rights for too long, and the concept has the exact
opposite effect.   I like to picture it as a bell curve,

      [2]
       *               ^
     ** **             | SOCIETY
   **     ** [3]       | BETTER OFF
 **         **         |
 [1]          **       | SOCIETY
                ** [4] | WORSE OFF

[1] Life without copyright law... kinda hard, read
    up about how the distributors end up controlling
    ideas rather than the creators (1600's)

[2] Life with perfect copyright law, not too weak,
    not too strong.   Perhaps we hit this in the 1800's?

[3] Life with too much copyright law... kinda hard,
    creators find it hard beacuse they are always
    violating someone elses work or can't build upon
    the work of others.

[4] Life with _way_ too much copyright law... we are here!


So, RMS is right, [1] is better than [4].  But, I think [2]
is an ideal.  However, given that we are at [4], [2] does
indeed look rozy, doesn't it?

Unfortunately, over the last century, our government has
taken a good thing and turned the dial all the way up.
Just like Food is good... too much food and you get FAT.
Everything in moderation.

So, I don't find fault with the concept of copyright or
patent; what I do find fault is that the laws are currently
so out of ballence that they have lost all legitimacy.

| [2]  I just believe that GNU and the FSF are not primus inter pares
| any more, and that the concentration of ownership of free software in
| the FSF is no longer especially useful.

Ahh.  Here I agree with RMS; if you want to use GNU, you
really should be donating the code to the FSF.  Why?  It 
is not about arrogance.  GNU software has yet to be
seriously challenged and when it is only the copyright
holder can enforce challenges.  Currently there is much GPL
software out there that is not owned by anyone (just try 
and find the owner for some peices)  and as such, enforcing 
it will be damn near impossible.  I bet 90% of GPL holders 
don't even send in the correct forms to the copyright office.   
Without the filings, it is the claimant's responsibility 
to *prove* that they actually own the copyright... and this 
is _hard_.  The FSF plays a crutial role in making GPL enforcable
by handling all of this legal stuff.   It may not seem 
important yet... but the true test of GPL has yet to arrive.  

Clark

-- 
Clark C. Evans                   Axista, Inc.
http://www.axista.com            800.926.5525
XCOLLA Collaborative Project Management Software




From peter at engcorp.com  Thu Jul 18 18:25:22 2002
From: peter at engcorp.com (Peter Hansen)
Date: Thu, 18 Jul 2002 18:25:22 -0400
Subject: starting other programs from within python
References: <20020716.171155.619290071.333@beer.com> <3D349AA0.1AE34452@engcorp.com> <20020717.123645.824272813.337@beer.com> 
Message-ID: <3D374052.8BC19745@engcorp.com>

Frank Fejes wrote:
> 
> On Wed, 17 Jul 2002 11:36:57 -0500, hejduk wrote:
> 
> > In article <3D349AA0.1AE34452 at engcorp.com>, "Peter Hansen"
> >  wrote:
> > I'm using python 2.2, on slak linux using gnome, and i'm monitoring the
> > memory usage with gtop.
> >
> > my main concern really is whether i'm starting the processes in the
> > right manner. would spawnv or something else be better? i'm new to
> > threads so i don't know whether they need to be stopped manually or
> > whether they'll shut down automatically.
> 
> If your goal is simply to execute applications from a menu, threads seem
> like overkill to me.  I'd simply use the usual fork/exec methods.  In
> Python, these are in the os module along with the spawn methods you refer
> to.

Just to clarify, I did not write any of the text included above.  
hejduk's response was in response to something I wrote, which
Frank has removed but forgot to delete the attribution line.

-Peter


From cliechti at gmx.net  Wed Jul 24 12:50:07 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 24 Jul 2002 18:50:07 +0200
Subject: syntax questions
References: 
Message-ID: 

Philippe Gendreau  wrote in 
news:mailman.1027526320.10233.python-list at python.org:

> Hi!
> I'm fairly new to python and there a thing I don't understand in the
> syntax. What is it with the "_". I have seen it used in many places for
> what seems to be different puposes like:
> 
> from x import _
> 
> Also, I'd like to understand this syntax: "((_(name),))"
> here's an example where it's used:
> 
>         # stuff a list
>         for dir in os.listdir('/usr/share/themes'):
>             row = self.theme.append ((_(dir),))
>             self.theme.set_row_data (row, dir)
> 
> More precisely, what are the comma and underscore for?

you want to call "append" on the variable "self.theme" which seems to be a 
list, therefore the outher parantheses:
self.theme.append(...)

you want to add a tuple to the list:
(...,)

a tuple with just one argument needs a coma at the end, otherwise it would 
be an arithmetic expression ans no tupple.

and finaly you call a function with the name "_":
_(dir)

that is sometimes used to localize names i.e. the "_" function translates 
the given string to the local language. to be sure what it does you have to 
search for the implementation in you current sourcecode.

note that "dir" is somewhat a bad name for that variable because
a) there is a builtin function that name that you hide
b) its not a directory name but a filename without path in the above case

in the intercative prompt "_" is bound to the last result so that you can 
do further calculations:
>>> 1+1
2
>>> _*3
6

chris

-- 
Chris 



From phr-n2002b at NOSPAMnightsong.com  Mon Jul  8 02:30:07 2002
From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin)
Date: 07 Jul 2002 23:30:07 -0700
Subject: Linux clock-setting script
References: 
Message-ID: <7x7kk691g0.fsf@ruckus.brouhaha.com>

"David LeBlanc"  writes:
> No, the ftp site I pointed to has a simple client in C - admittedly with
> some "windowisms" for setting the cmos clock on a PC mobo (which might
> translate pretty directly over to linux). It's spread over several files and
> looks to be about 20kb total of c source.

Yeah, that's what I mean.  I'd rather have 10 lines of Python than
20kb of C.


From hesterloli at hotmail.com  Mon Jul 29 23:45:29 2002
From: hesterloli at hotmail.com (George Hester)
Date: Tue, 30 Jul 2002 03:45:29 GMT
Subject: Disappearing Output?
References:  <3D4476FB.70200@skippinet.com.au>
Message-ID: 

Oh Mark oh Mark thank you.  Where is that page of yours?  I have been yanking my
hair out on this one.  I was about to just trash Python for good.  Thanks.

--
George Hester
_________________________________
"Mark Hammond"  wrote in message
news:3D4476FB.70200 at skippinet.com.au...
> George Hester wrote:
> > I have a very simple Python script in a ASP page.   The ASP looks like this:
> ...
> > But if I try to run an ASP as shown above I get output sometimes but often I
get
> > absolutely nothing.  No output.  No errror.  Just absolutely nothing.
> >
> > Is this a Python issue, a Python Script issue or something else under the
sun?
>
> This is a Python bug.  It has been fixed in the latest versions of
> win32all - see my starship page.
>
> Mark.
>




From usenet at thinkspot.net  Mon Jul  8 03:27:29 2002
From: usenet at thinkspot.net (Sheila King)
Date: Mon, 08 Jul 2002 00:27:29 -0700
Subject: procmail replacement in Python
References:  <3u8pea.617.ln@127.0.0.1>       
Message-ID: 

On 07 Jul 2002 17:47:56 -0400, pinard at iro.umontreal.ca (Fran?ois Pinard)
wrote in comp.lang.python in article
:
 
> I glanced through `pycmail' and decided to postpone for now, so I do not
> have much experience to share with you.
> 
> The Python source is file `pycmail' at the top-level after extraction.
> It does not have a `.py' extension.

Thank you.

I feel totally silly now. I must've looked at almost every file in the
package except that one. :/

Anyhow, thank you, I've looked at it now. It looks very interesting and is
something I may work with further when I get more time. Hope that the
author gets his DNS situation sorted out.

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/



From eugene1977 at hotmail.com  Sat Jul 20 02:55:48 2002
From: eugene1977 at hotmail.com (eugene kim)
Date: Sat, 20 Jul 2002 01:55:48 -0500
Subject: UnicodeError: ASCII decoding error: ordinal not in range(128)
References:     
Message-ID: 

thx again..

i got PyGreSQL(pyPgSQL gave me error ImportError: No module named libpq)
i looked at 
>>>help(pgdb)
that was about all docs i could get including from web

python looks really clean(<->perl), and requires a lot less coding(<->java)
so i'm trying to learn python..
compared to other languages such as java/perl
it seems like it's really hard to find docs about python..
should i buy bunch of books? such as python cookbook?
thank you

by the way

my last question about java was..
is this form below also available in java?
---------------------------
cursor.execute("insert into history (col1, col1, col3) values (%s, %s, %s)",
>                  (self.url, self.title, self.firsttime))
---------------------------

and..also
first-time is integer type..
strings are title/url only




From logiplexsoftware at earthlink.net  Thu Jul  4 20:32:28 2002
From: logiplexsoftware at earthlink.net (Cliff Wells)
Date: 04 Jul 2002 17:32:28 -0700
Subject: How to represent the infinite ?
In-Reply-To: 
References: <3d11ee9b$1@news.swissonline.ch>
	 
	
Message-ID: <1025829150.8643.24.camel@localhost.localdomain>

On Thu, 2002-07-04 at 02:42, Steve Tregidgo wrote: 
> Cliff Wells  wrote in message news:...
> > from __future__ import generators
> > 
> > class Infinity(int):
> >     def __init__(self):
> >         int.__init__(self)
> >         self.sign = 1
> > 
> >     def __str__(self):
> >         return "%sInfinity" % {-1: "-", 1: ""}[self.sign]
> > 
> >     def __repr__(self):
> >         return "<%s>" % self
> [followed by many other good things]
>

Thanks! 

> Nice implementation.  May I suggest two small changes:
> 
>     def __init__(self, sign=1):
>         int.__init__(self)
>         self.sign = sign
> 
>     def __repr__(self):
>         return "%s(%s)" % (self.__class__.__name__, self.sign)
> 
> It's partially tested (my version of Python doesn't have generators...
> I really should get with the times); the point is that, assuming
> Infinity is available in the calling namespace, this will work:
> 
> Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> from some_module import Infinity
> >>> i = Infinity()
> >>> repr(i)
> 'Infinity(1)'
> >>> j = eval(repr(i))
> >>> j == i
> 1
> >>> k = -eval(repr(i))
> >>> k + i
> 0

Looks good to me.  I was more concerned with the other stuff and kind of
stuck the __repr__ implementation in as a placeholder. 

However, I think I prefer this:

class Infinity(int):
    def __init__(self):
        int.__init__(self)
        self.sign = 1

    def __repr__(self):
        return "%s()" % self

Basically the same effect, but it prints as "-Infinity()" rather than
"Infinity(-1)", not to mention being a bit shorter.

>>> from infinity import Infinity
>>> m = -Infinity()
>>> m
-Infinity()
>>> `m`
'-Infinity()'
>>> str(m)
'-Infinity'
>>> j = eval(repr(m))
>>> j
-Infinity()
>>> j == m
1
>>> k = -eval(repr(j))
>>> k
Infinity()
>>> 

> Quoting from the Python reference manual (section 3.3.1):
> > If at all possible, this should look like a valid Python expression
> > that could be used to recreate an object with the same value (given
> > an appropriate environment).
> 
> I'd be interested to hear if these minor modifications work with the
> class proper; I had to remove the generator/yield lines, and the
> subclassing from int, to get it to run under 1.5.2 :-)

I can't see how the __repr__ change would have any effect (other than
making it better).  Not subclassing from int will be an issue:

>>> from infinity import Infinity
>>> i = Infinity()
>>> i / 1
Infinity()
>>> 1 / i
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for /: 'int' and 'instance'
>>> 

But since that was supposed to raise an exception anyway, it may not be
much of an issue (it just raises a less informative exception).  The
exception raised by Infinity(int) is:

>>> from infinity import Infinity
>>> i = Infinity()
>>> i / 1
Infinity()
>>> 1 / i
Traceback (most recent call last):
  File "", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 

Which isn't entirely correct either but a bit more informative.

> Anyway, as I said: I like the class.

It's always fun (and surprisingly easy) to write little things like this
in Python.

> just-wanted-to-join-in-ly y'rs,
> Steve

Regards, 
Cliff





From sdrake at knology.net  Tue Jul 30 11:10:29 2002
From: sdrake at knology.net (Steve Drake)
Date: 30 Jul 2002 08:10:29 -0700
Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3
References:  <3D45E665.3C34CDF@alcyone.com>  
Message-ID: 

Here's what I got...

>>> import pyexpat
>>> pyexpat.__version__
'2.57'
>>> pyexpat.ParserCreate(intern={})
Traceback (most recent call last):
  File "", line 1, in ?
    pyexpat.ParserCreate(intern={})
TypeError: 'intern' is an invalid keyword argument for this function

Jonathan Hogg  wrote in message news:...
> On 30/7/2002 9:36, in article B96C0EAF.EC64%jonathan at onegoodidea.com,
> "Jonathan Hogg"  wrote:
> 
> > Is this some weird mismatch in expat module version?
> 
> Hate following up to myself, but try this:
> 
> >>> import pyexpat
> >>> pyexpat.__version__
>  '2.67'
> >>> pyexpat.ParserCreate( intern={} )
>  
> >>> 
> 
> and tell us what happens.
> 
> Jonathan


From cliechti at gmx.net  Wed Jul 24 06:32:01 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 24 Jul 2002 12:32:01 +0200
Subject: wxPython and wxLocale
References: 
Message-ID: 

Uwe Schmitt  wrote in 
news:ahlrhp$g3fv5$1 at hades.rz.uni-sb.de:
> I have the problem, that in a self written application dialog buttons
> are labled in german instead of english. 

those are the yes, no, ok or cancel buttons (in file dialogs etc.), right? 
i think that wx takes the windows functions which show the buttons in the  
language windows is set to. this means that an english windows will show 
english buttons. don't know about linux but i would expect the same there.

chris

-- 
Chris 



From tim.one at comcast.net  Wed Jul 17 00:02:32 2002
From: tim.one at comcast.net (Tim Peters)
Date: Wed, 17 Jul 2002 00:02:32 -0400
Subject: inheriting from C types
In-Reply-To: <3D34E854.8020200@something.invalid>
Message-ID: 

[Martin v. Loewis, out of context]
> What is k.__mro__?

[Greg Ewing]
> I believe it stands for Method Resolution Order, and
> it contains a flattened list of all the base classes,
> in the order they should be searched for methods.

All correct, except that it also contains the class itself first (unless you
create a really weird custom metatype that defines a bizarre resolution
order for its instances).  But Martin knows that.  In context, if we knew
the *value* of k.__mro__, that would help in answering the OP's question.





From mnations at airmail.net  Wed Jul 24 15:20:04 2002
From: mnations at airmail.net (Marc)
Date: 24 Jul 2002 12:20:04 -0700
Subject: Strange Queue error
Message-ID: <4378fa6f.0207241120.1876187b@posting.google.com>

I was attempting to use the Queue and came across a strange error. Why
is Python wanting a Queue instance as an argument and not accepting
the tuple. I was simply trying to put this on the queue:


    qlist.put( (sleep, 5) )

Here is the error.

C:\Python22\CAP v1.0\queue>python temp2.py
Project is a go
in check
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python22\lib\threading.py", line 408, in __bootstrap
    self.run()
  File "C:\Python22\lib\threading.py", line 396, in run
    apply(self.__target, self.__args, self.__kwargs)
  File "temp2.py", line 586, in launch
    main.launchUTStest()
  File "main.py", line 31, in launchUTStest
    eval( modules.securityFunctions[mod] )(gui, qlist)
  File "security.py", line 35, in uid_gen_format
    qlist.put( (sleep, 5) )
TypeError: unbound method put() must be called with Queue instance as
first argu
ment (got tuple instance instead)

Does anyone know what this means?

Thanks,
Marc


From whisper at oz.net  Fri Jul 12 17:15:05 2002
From: whisper at oz.net (David LeBlanc)
Date: Fri, 12 Jul 2002 14:15:05 -0700
Subject: Is count supposed to still work?
In-Reply-To: 
Message-ID: 


> > something, a different way to express the same thing.
>
> Exactly what we DON'T want in Python -- the ideal, alas
> unreachable, would be to have *ONE* way to express one thing.
> Alex

By all means, everyone should express themselves in eactly the same way at
all times. Will you be wearing the grey Mao jacket or the gray Mao jacket
today?

Come to think of it there are sorts of sligthly divergent cultural groups we
could merge into the *ONE* way: Germany, Holland and Denmark are close
enough; definately a unification into the "German Federation" (aka
UberDeutchland) would just have to be sucessful. And then there's Spain and
Italy; Language and temperment make them a perfect match as "Spanish Italy"!
The Spanish can fight the Italian bull!

I'll be in my bomb shelter now :->

Dave LeBlanc





From beej at piratehaven.org  Wed Jul 17 14:24:00 2002
From: beej at piratehaven.org (Beej Jørgensen)
Date: 17 Jul 2002 18:24:00 GMT
Subject: Python 2.2.1 Build Trouble
References: 
Message-ID: 

In article , Peter Chiu  wrote:
>Modules/posixmodule.c:1310: `stat' undeclared (first use in this function)
>Modules/posixmodule.c:2227: warning: implicit declaration of function
>`plock'
>Modules/posixmodule.c:3380: `lstat' undeclared (first use in this function)
>Modules/posixmodule.c:4118: warning: implicit declaration of function
>`unsetenv'

Sounds like includes are missing.  The Right Thing would be to fix up
the configure scripts and sources so it works properly with your
platform.  Instead, do the easy thing:

1) Check the man page for stat (man stat) and see what include files
   it wants.
   
2) Then edit Modules/posixmodule.c and make sure you #include
   all of them at the top of the file.  (Some will be there, and some
   won't, is my guess.)

3) Do the same for plock, lstat, and unsetenv.

Then try make again.

YMMV, as I don't use this platform.

-Beej



From loewis at informatik.hu-berlin.de  Mon Jul  8 10:05:25 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 08 Jul 2002 16:05:25 +0200
Subject: Unicode utf-8 doesn't do back-and-forth?
References:    
Message-ID: 

Piet van Oostrum  writes:

> Well, I looked into the Unicode specs and it says that even if single
> surrogates appear in a string, the UTF-8 encoding should generate a valid
> UTF-8 byte sequence, which on encoding should give the same surrogate. So
> I would say this is a bug in the UTF-8 encoding.

Which Unicode specs did you look at? Unicode TR #28 (aka Unicode 3.2),

http://www.unicode.org/unicode/reports/tr28/

says


The definition of transformation formats such as UTF-8 allowed
conformant processes to interpret certain sequences called irregular
sequences. These irregular sequences are those that would be produced
by transforming supplementary code points as if they were a sequence
of two surrogate code points.

To tighten the definitions, in Unicode 3.2 such irregular sequences
are now illegal.


Table 3.1B of the same document explicitly lists the byte sequences
that would denote code points D800-D8FF as illegal.

There is special permission given to recovery tools to deal with
irregular or illegal sequences without indicating an error, but the
standard Python UTF-8 codec certainly does not fall into this
category.

Regards,
Martin


From h_schneider at marketmix.com  Mon Jul 29 03:41:15 2002
From: h_schneider at marketmix.com (Harald Schneider)
Date: Mon, 29 Jul 2002 09:41:15 +0200
Subject: wxPython: wxColumnSorterMixin, iterate over wxListCtrl ...
Message-ID: 

Hi,

I have a wxListCtrl that is already filled with data.
When I want to use wxColumnSorterMixin, then this method requires
self.itemDataMap as a dictionary filled with all the ListCtrl data.

What is the most easy way to populate itemDataMap dictionary with the data
from the wxListCtrl ?
How can I iterate ove a wxListCtrl ?
Are there alternate ways of implementing a column sort method `?

Thank you very much in advance!

Bye,
Harald





From merman at snafu.de  Sat Jul  6 13:40:37 2002
From: merman at snafu.de (merman)
Date: Sat, 6 Jul 2002 19:40:37 +0200
Subject: Understanding properties
References:  
Message-ID: 

> class MyObject(object):

Why it needs the inheritance from object - I don't understand.

Can you enlighten me please?

Thomas






From raphael.berbain at bigfoot.com  Tue Jul  2 09:31:56 2002
From: raphael.berbain at bigfoot.com (=?iso-8859-1?q?Rapha=EBl?= Berbain)
Date: Tue, 02 Jul 2002 15:31:56 +0200
Subject: Python as an embedded extension language
Message-ID: <85znxazd21.fsf@ID-110038.user.dfncis.de>

Hi,

I am quite new to the python language (a couple of days, really).  So
please be nice, I can commit huge mistakes quite easily.  I came
across it because I am looking for an extension language for a
C++-based application I am writing.  Here are the points that caught
my eyes :

- Python is simple and readable (If I understand correctly, these are
  design goals).

- Functions are first class objects.

- Interfaces well with C++ (thinking of using the Boost python lib) -
  I found a lot a languages that interface with C, but much less with
  C++.

- Well documented.

- Large and active community.

Now before I invest any further into Python I have a couple of
questions :

- Licensing issues:  Python license (2.2.1) seems to be quite
  permissive.  From what I read, it seems I can do pretty much
  anything with Python, as long as I leave copyright notices and
  explain my modifications.  For the moment, I am thinking of some
  kind of BSD-type license for my own code.  Would this be working
  together ? (see below for how I plan to use Python in more details).

- I'd like to embed Python in my app statically, maybe with some
  modifications.  Primary goals are that it only includes needed
  features and that it doesn't interfere or depend on a user random
  Python installation.  Is that doable ?  I mean, pruning the python
  base install to the strict minimum and completely isolate my app
  from any existing python installation on the system ?

- Would this kind of manipulation enlarge by any significant amount
  the embedding app size and/or memory footprint ?  Incidentally,
  what is the garbage collecting scheme used by Python ?  More
  generally, is there any studies about Python memory usage ?

- I read here and there that Python is really slow.  That's ok with
  me, I am not a speed freak (especially given that if I need speed,
  there's always the C++ side of the app).  Does anyone have relevant
  figures about Python speed ?

- I also read that Python can vary a lot between versions.  What is
  people experience with this ?  This might not be an actual problem
  in this case, since I intend to include Python statically in the
  app, so I can always stay with a version that works instead of
  being forced to support the last version.  Still, it would be nice
  to know.

- Is there a way to enter the debugger when some run-time error is
  encountered (a bit like the Emacs elisp debugger, when
  debug-on-error is t).  This may not be needed, since for the moment
  I foresee a much more closed system than the Emacs' one, but this
  would still be convenient.

More generally, I would be interested in hearing people's experience
with embedding Python, especially with C++ (Boost python lib
impressions wlecome).

Thanks for your attention.

-- 
Rapha?l


From ms at NOMAIL.de  Mon Jul 15 21:15:25 2002
From: ms at NOMAIL.de (Michael Schmitt)
Date: Tue, 16 Jul 2002 03:15:25 +0200
Subject: implementing large trees
References:  
Message-ID: 

Hello, thanks for your thought-provoking questions.

Bengt Richter wrote: [ordering of citations changed!]
> - What does your tree actually represent IRL?
The tree represents factors of a maximal length of event sequences. In 
these sequences patterns should be discovered.

> - What about buying more memory ;-)
Well..., most of the algorithms seem to have linear complexity. If this 
would run on hard disc, with a "nice linear factor", it would scale 
sufficiently with problem size. My budget does not scale with problem size, 
so this is not an option at present.

> - Are your nodes and edges class instances? Are you using __slots__ ?
> - What are you using as keys in your dictionaries?
I'm not using nodes instances to avoid object overhead. As it seems, the 
__slot__ suggestion would make it affordable.

Actually, the node dictionary maps node ids to a tuple of parent id, data, 
child ids. The data field contains also information about the incoming edge.
The edge dictionary maps (nodeid,edge) tuples to nodeids.

> - Do you need to touch every node as you follow edges?
Yes. As path construction is a main point, I can see no way around it.

> - How many total nodes and edges?
300.000 are o.k for in-memory, 3.000.000 would be nice, 50.000.000 would 
make me happy.


> - How many edges per node? Min? Max? Usual?
At the root are about 2% of the edges, a bit less for larger node numbers.
At inner nodes very often 1, but up to 0.2 % in very rare cases.

> - Is it very deep or very wide?
Depth is limited to something between 5 to 15. Width at leaf level is about 
10%-20% of the number of nodes.

> - Is the tree essentially static for many traversals, so that it might pay
> to do some special overall pre-procesing to speed traversal?
The tree is static. Build tree, traverse, finished.

> - Is part of the tree "hot" and other parts hardly ever visited? Would
> caching pay off?
The tree is traversed rather uniformly. Probably it is possible to restrict 
traversal to breadth- or depth-first only, which would make caching simpler.

After answering all these questions, i'm not shure, what answer i expected. 
I hoped to find a simple tree on disc universal solution, but as it seems 
it has to be tailored for the algorithms that work on the tree.

Bengt, thanks for your questions.

Thanks for any further hints.

Michael



From b.hall at irl.cri.nz  Sun Jul  7 17:51:41 2002
From: b.hall at irl.cri.nz (Blair Hall)
Date: Mon, 08 Jul 2002 09:51:41 +1200
Subject: COM Client problem with Excel
Message-ID: <3D28B7ED.8B8A4CB5@irl.cri.nz>

I am not sure how to handle Python exceptions when my Python
program is using Excel as a client.

At present, if anything raises
a Python exception while I have an active reference to Excel, then the
behaviour of the Python-Excel link is damaged until I close Pythonwin
and start
all over again (worse it is sometimes necessary to reboot).

At the end of this message  is some code that will cause the problem to
occur (by calling the 'problem' function). I.e.

>>> xl = Excel('test')
>>> xl.problem()

If I then try

>>> xl = Excel("test2")

for example, I will get only part of the Excel toolbar on screen, or
perhaps
Excel will not start properly, or something else will be wrong...

I  am using win95 with the latest version of Python and the windows
extensions.

What should I be doing to keep Excel happy? Indeed, where should I be
looking
to find out how to write more stable Com-Python code?

import win32com.client
import pythoncom

def comExceptionHandler(hr,msg,exc,arg) :
    print 'COM call failed: %s' % msg
    if exc is not None:
        wcode, source, text, helpFile, helpID, scode = exc
        print 'Error source:',source
        print text
        print 'See also: %s (id=%d)' % (helpFile,helpID)

class Excel:
    def __init__(self,filename,visible=1):
        """
        Create a new file in the current working directory
        and save a new Excel workbook in it.
        """
        import os
        filename = os.path.join( os.getcwd(), filename )
        try:
            self.app = win32com.client.Dispatch("Excel.Application")
            wb = self.app.Workbooks.Add()
            wb.SaveAs(filename)
            wb.Activate()
            self.app.Visible = visible
        except pythoncom.com_error, (hr,msg,exc,arg):
            comExceptionHandler(hr,msg,exc,arg)

    def __del__(self):
        wb = self.app.ActiveWorkbook
        wb.Save()
        self.app.Quit()

    def problem(self):
        raise "something"




From SBrunning at trisystems.co.uk  Wed Jul  3 05:06:29 2002
From: SBrunning at trisystems.co.uk (Simon Brunning)
Date: Wed, 3 Jul 2002 10:06:29 +0100 
Subject: Useful RE patterns (was: Variable Interpolation - status of P
	EP 215)
Message-ID: <31575A892FF6D1118F5800600846864DCBD49A@intrepid>

> From:	Mike C. Fletcher [SMTP:mcfletch at rogers.com]
> I'm actually doing something very similar for SimpleParse (pre-built 
> parsers for common constructs that can automatically be included in your 
> grammars).
 
Interesting project. But you might want to call it something else - there is
already a SimpleParse. See
 and
.

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




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




From fredrik at pythonware.com  Mon Jul  1 07:32:22 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Mon, 01 Jul 2002 11:32:22 GMT
Subject: Python needs better error reporting
References: 
Message-ID: 

"Opus" wrote:

> This being said, the fact that this is not a compiled language

it is.

> it still needs to read the source file to make sure it is up to
> date

it doesn't -- it asks the *file system* for a timestamp.  the
parser's got nothing to do with that.

> Maybe even an option for the parser to spot bad-practice code.
> I.E. Is is faster to call 'var += 1' or 'var = var + 1'.

it's not.

(let's hope whoever implements the "newspeak" module cares enough to
run benchmarks -- and makes sure that we can tell it to shut up when
writing code supposed to run on more than one Python version...)






From gerhard.haering at gmx.de  Thu Jul 18 13:19:13 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: Thu, 18 Jul 2002 19:19:13 +0200
Subject: audio dev for linux
In-Reply-To: <27E327AB8201B54495D54105FBBBB1485D2053@SRVMSG.GERLAND2.local>
References: <27E327AB8201B54495D54105FBBBB1485D2053@SRVMSG.GERLAND2.local>
Message-ID: <20020718171913.GA2112@lilith.my-fqdn.de>

* Maric MICHAUD  [2002-07-18 12:36 +0200]:
> Do anyone know a way to play a cdrom track on linux.

Install pygame, then you can play audio CDs.

Here's an example snippet:
http://pygame.org/pcr/submissions/05182001a.html

Gerhard

PS: If you use Debian, it's already packaged for you.
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




From mcherm at destiny.com  Tue Jul 23 09:15:26 2002
From: mcherm at destiny.com (Michael Chermside)
Date: Tue, 23 Jul 2002 09:15:26 -0400
Subject: A better self
Message-ID: <3D3D56EE.9030208@destiny.com>

> (1) t, x, y, z=self.t, self.x, self.y, self.z
          [...]
> (2)t=self.t;   x=self.x;   y=self.y;   z=self.z; 
          [...]
> I still prefer (1) -- most readable, but I like minimum overhead.

Then I recomend that you avoid Python.

Seriously, Python is interpreted, and the overhead for performing a 
simple mathematical calculation like

      sin(t) * x**y + sqrt(z)

in Python vs doing it directly in C, Fortran, or some other 
close-to-the-machine language is FAR, FAR greater than the difference 
between (1) and (2) above.

Think about it like this. Suppose there were two ways to write your 
code. Method (A) was clear and easy to read, and not particularly 
difficult to modify. Method (B) was much harder to read, and a real pain 
to modify. But method (B) runs X microseconds faster.

If X makes the difference between your whole program running in 5 
minutes vs 5 hours, or the difference between your user interface 
responding in 0.5 seconds vs locking for 5 seconds, then you probably 
care deeply, and you probably want to use method (B). If X makes the 
difference between your whole program running in 5 minutes vs 6 minutes, 
or the user interface responding in 0.3 seconds or 0.5 seconds, then 
many programmers would prefer method (A).

If you are one of those who would choose method (B) even when the 
difference in runtime was between 5 and 6 minutes, then you probably 
shouldn't be using Python. Yes, Python is a nice language, and yes, it 
can be sped up by recoding key portions of an application in C/C++, but 
it is never going to be as fast as an algorithm hand coded in assembly.

I guess what I'm trying to say here is, yes... having the functions 
separate WILL slow things down, and by a *LOT* more than the difference 
between (1) and (2) above. But you REALLY shouldn't be worrying about 
the difference in execution time between (1) and (2)... if you ARE 
worrying about such things, then there are MUCH bigger gains to be had 
by trying a different kind of language.

-- Michael Chermside






From tebeka at cs.bgu.ac.il  Mon Jul 22 04:31:24 2002
From: tebeka at cs.bgu.ac.il (Miki Tebeka)
Date: 22 Jul 2002 01:31:24 -0700
Subject: NEWBIE: Removing HTML/JavaScript from a webpage
References: <3D3B0491.4000605@NOSPAM.bardstowncable.net>
Message-ID: <33803989.0207220031.53b2a8d5@posting.google.com>

> import urllib
> 
> response = 
> urllib.urlopen('http://movies.go.com/cgi/movielistings/request.dll?ZIPSPECIFIC&zip_code=40004&date=07/20/2002')
> 
> resp = response.read()
> 
> This grabs the movie playtimes for my area. Now, my big question -- how 
> do I remove all of the junk Javascript and HTML? I stole this bit of 
> code from somewhere:
> 
> import re
> split = re.sub("<[^>]*>","",resp)
> 
> But, this only removes the HTML -- the Javascript is still there; and I 
> have no idea on how to modify that so it eliminates the script.
Have a look at http://starship.python.net/crew/tibs/python/html2text

HTH
Miki


From marklists at mceahern.com  Mon Jul 15 23:00:27 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Mon, 15 Jul 2002 22:00:27 -0500
Subject: Base-class method access
In-Reply-To: 
Message-ID: 

> Is it possible for a derived class to access overridden methods of its
> base class? For example:
>
>
> class Foo:
>       def frob():
>           print "Spam"
>
> class Bar(Foo):
>       def frob():
>           print "Eggs"
>           # In C#, the syntax to call Foo's frob() would be
>           # base.frob()
>           

Here's the syntax:

            Foo.frob(self)

However, this only makes sense if you fix your definition of frob().  It's
missing the implicit reference to the instance, normally spelled self:

        def frob(self):

You can also look into super(), but the above should work.

Cheers,

// m

-





From jdhunter at ace.bsd.uchicago.edu  Tue Jul 30 11:22:52 2002
From: jdhunter at ace.bsd.uchicago.edu (John Hunter)
Date: Tue, 30 Jul 2002 10:22:52 -0500
Subject: Check undefined variable
In-Reply-To: <3D46AD2E.709@img-online.de> (Michael Grabietz's message of
 "Tue, 30 Jul 2002 17:13:50 +0200")
References: <3D46AD2E.709@img-online.de>
Message-ID: 

>>>>> "Michael" == Michael Grabietz  writes:

    Michael> Hi, how is it possible to check whether a variable 'a' is
    Michael> undefined or not.

The namespace is stored in a dictionary that maps variable names to
values.  You can access the namespace with the functions globals() and
locals().  Since these return a dictionary, you can use the method
has_key() to see if the name exists

>>> globals().has_key('a')
0
>>> locals().has_key('a')
0
>>> a = 1
>>> globals().has_key('a')
1
>>> locals().has_key('a')
1


John Hunter



From lalo at laranja.org  Tue Jul  2 19:17:15 2002
From: lalo at laranja.org (Lalo Martins)
Date: Tue, 2 Jul 2002 20:17:15 -0300
Subject: [Python-Dev] [development doc updates]
In-Reply-To: <20020702222813.8990118EC22@grendel.zope.com>
References: <20020702222813.8990118EC22@grendel.zope.com>
Message-ID: <20020702231715.GG25927@laranja.org>

On Tue, Jul 02, 2002 at 06:28:13PM -0400, Fred L. Drake wrote:
> The development version of the documentation has been updated:
> 
>     http://www.python.org/dev/doc/devel/
> 
> Many updates and corrections to the documentation, including docs for the
> new textwrap module.

Re: textwrap.TextWrapper.fix_sentence_endings

} ... Furthermore, since it relies on string.lowercase ... it is specific to
} English-language texts.

Well, actually the convention of separating sentences by two spaces is also
specific to the English language, so I don't see that as a problem.

[]s,
                                               |alo
                                               +----
--
  It doesn't bother me that people say things like
   "you'll never get anywhere with this attitude".
   In a few decades, it will make a good paragraph
      in my biography. You know, for a laugh.
--
http://www.laranja.org/                mailto:lalo at laranja.org
         pgp key: http://www.laranja.org/pessoal/pgp

Eu jogo RPG! (I play RPG)         http://www.eujogorpg.com.br/
Python Foundry Guide http://www.sf.net/foundry/python-foundry/




From aleax at aleax.it  Thu Jul 25 12:33:11 2002
From: aleax at aleax.it (Alex Martelli)
Date: Thu, 25 Jul 2002 16:33:11 GMT
Subject: xml processing : too slow...
References:    
Message-ID: 

Terry Reedy wrote:

>> I suspect you'll need to get a new parser for each line.
> 
> Is is possible, and might it be faster, to make and use a copy of the
> parser for each line?
> With copy module?

copy.copy is unable to copy objects of type pyexpat.xmlparser -- I
didn't know that, but it took me about 5 secs to try:-).


Alex



From guido at python.org  Thu Jul 25 12:32:24 2002
From: guido at python.org (Guido van Rossum)
Date: Thu, 25 Jul 2002 12:32:24 -0400
Subject: [Python-Dev] Powerpoint slide for keynotes available
References: <200207250004.g6P04pP20522@pcp02138704pcs.reston01.va.comcast.net>
Message-ID: <009b01c233f8$de6bade0$7f00a8c0@pacbell.net>

I wrote:
> If someone can donate PDF that would be great (the HTML
> generated by Powerpoint sucks too much to be worth it IMO).
> 
> http://www.python.org/doc/essays/ppt/
> 
> (scroll to end)

I've received about 5 offers of PDF.  The first one is now on the web.
Mark Hadfield won the race. :-)

--Guido van Rossum (home page: http://www.python.org/~guido/)





From syver-en+usenet at online.no  Wed Jul 17 12:57:08 2002
From: syver-en+usenet at online.no (Syver Enstad)
Date: Wed, 17 Jul 2002 16:57:08 GMT
Subject: gettext i18n
References:  
Message-ID: 

Alex Martelli  writes:

> I once posted a small walked-through example, see: 
> 
> http://groups.google.com/groups?selm=9fkubv0i48%40enews2.newsguy.com
> 
> Some readers found it helped them get started.

As usual excellent advice. Got it up and running in minutes. Thanks!

-- 

Vennlig hilsen 

Syver Enstad


From bokr at oz.net  Thu Jul 18 14:42:49 2002
From: bokr at oz.net (Bengt Richter)
Date: 18 Jul 2002 18:42:49 GMT
Subject: get a list printed in hexadecimal notation
References:    
Message-ID: 

On Thu, 18 Jul 2002 09:39:56 +0200, Oliver Eichler  wrote:

>
>Another tip I received from Harvey Thomas & Fran?ois Pinard:
>
>print  [isinstance(x,int) and hex(x) or x for x in l]
>
That's fine if this is acceptable:

 >>> l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)
         ^                                   ^^^^^                   ^
 >>> print  [isinstance(x,int) and hex(x) or x for x in l]
 ['spam', '0xa', '0xf', 'more spam', ['nested', 65535, 'spam'], 'spam', '0xff']
 ^                                              ^^^^^                         ^

Regards,
Bengt Richter


From shalehperry at attbi.com  Sat Jul  6 13:39:20 2002
From: shalehperry at attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 06 Jul 2002 10:39:20 -0700 (PDT)
Subject: Understanding properties
In-Reply-To: 
Message-ID: 

On 06-Jul-2002 merman wrote:
>> class MyObject(object):
> 
> Why it needs the inheritance from object - I don't understand.
> 
> Can you enlighten me please?
> 

deriving from 'object' causes the class to be a new style python 2.2+ class. 
This enables the properties code.  If you do not derive from object python
creates a class just like it always has, with no new features.




From glingl at aon.at  Fri Jul 12 14:48:38 2002
From: glingl at aon.at (Gregor Lingl)
Date: Fri, 12 Jul 2002 20:48:38 +0200
Subject: dir(y) containing strange stuff
References: <886c5e4b.0207120919.1d24749@posting.google.com>
Message-ID: <3d2f2496$0$15894$91cee783@newsreader02.highway.telekom.at>

The following posting didn't get any replies from
Python Tutor nor VPython-users. So I'll try here:


When playing around with VPython I encountered the
following:

>>> from visual import *
Visual-2002-06-14
>>> s=sphere() # beautiful white sphere displayed immediately
>>> s

>>> dir(s)
['__class__', 'axis', 'blue', 'color', 'constr',
 'display', 'frame', 'green', 'name', 'pos', 'radius',
'red', 'rotate', 'up', 'visible', 'x', 'y', 'z']
>>> s.__methods__
['rotate']
>>> s.__dict__
{'__class__': }
>>> s.__members__
['axis', 'blue', 'color', 'display', 'frame', 'green',
'pos', 'radius', 'red', 'up', 'visible', 'x', 'y', 'z']
>>> s.name
Traceback (most recent call last):
  File "", line 1, in ?
    s.name
AttributeError: name
>>>

So, what are 'name' and 'constr', which both do not appear
neither in s.__members__ nor in s.__dict__ nor in s.__methods__,
but in the list returned by dir(s)?

(Or: what is generally returned by dir() ?)

Perhaps there is somebody who can explain this.

Thanks, Gregor


In other words: what happens in the following example, should not
happen in my understanding:

>>> from visual import *
Visual-2002-06-14
>>> s = sphere()
>>> for att in dir(s):
        print att, ':',
        print type(eval('s.'+att))


__class__ : 
axis : 
blue : 
color : 
constr :
Traceback (most recent call last):
  File "", line 3, in ?
    print type(eval('y.'+att))
  File "", line 0, in ?
AttributeError: constr
>>>




From here at I.am.me  Tue Jul  9 11:10:03 2002
From: here at I.am.me (me)
Date: Tue, 09 Jul 2002 15:10:03 GMT
Subject: Converting a hex string to a number
References: <4b628986.0207090252.5338178d@posting.google.com> <3d2adb64$0$12283$e4fe514c@dreader4.news.xs4all.nl>
Message-ID: 

Yigal Duppen  wrote:
>>  I am trying to convert a hex string (for example: "0x12345678") to a
>> number (0x12345678 or just 12345678).

YD# You can use int(), with 16 as the value for the second argument (radix) 
>>>> int("0x1A2B", 16)
YD# 6699

YD# Of course, if the number is very large, this won't work. In this case, 
YD# use long

>>>> int("0x123456789ABCDEF", 16)
YD# Traceback (most recent call last):
YD#   File "", line 1, in ?
YD# ValueError: int() literal too large: 0x123456789ABCDEF
>>>> long("0x123456789ABCDEF", 16)
YD# 81985529216486895L

YD# YDD
YD# -- 
YD# .sigmentation Fault

Like this solution.  Is there a way to use that long as hex, so bit
operations can be done on it piecewise?  Slice a byte, then xor it or
and it, and put it back?

thanks,

stan



From peter at engcorp.com  Sun Jul  7 23:40:02 2002
From: peter at engcorp.com (Peter Hansen)
Date: Sun, 07 Jul 2002 23:40:02 -0400
Subject: How to organize test cases with PyUnit
References:  <3D2898DC.B59538B1@engcorp.com>   
Message-ID: <3D290992.A9AD9AD9@engcorp.com>

Roy Smith wrote:
> 
> class dictionaryEntries (parserTestCase):
>     def runTest (self):
>         tables = self.parser.parse ('data/rulex.envmon')
>         self.assertEqual (type (tables), DictType)
>         self.assertEqual (1, 0)
>         for table in tables:
>             print type(table)
>             self.assertEqual (type (table), DictType)
> 
> if __name__ == "__main__":
>     dictionaryEntries().run()
> ====================================
> 
> parser.parse() is supposed to (and does) return a dictionary of
> dictionaries.  The line "for table in tables:" should read "for table in
> tables.keys():".  As written, it should raise a TypeError.  In the
> process of trying to figure out why it wasn't, I added the "print
> type(table)" line, and it doesn't print anything.  Then I added the
> "assertEqual (1, 0)", and it still does nothing.
> 
> Obviously, I'm doing something wrong.  I suspect something has wrapped
> my methon in a try block that catches all these exceptions, but then
> doesn't do anything with them.

Not sure, but you might try this instead.  Rename the runTest()
method to start with the text "test", and then change the __main__
content to be simply 'unittest.main()' instead of the dictEntries.run
that you have.

PyUnit not only supports various command line options for you this
way, but it also finds all 'testXXX' methods automatically and it
shouldn't give the above behaviour.

-Peter


From see_reply_address at something.invalid  Thu Jul  4 20:47:14 2002
From: see_reply_address at something.invalid (Greg Ewing)
Date: Fri, 05 Jul 2002 12:47:14 +1200
Subject: "my brain hurts" or is isinstance broken?
References:     
Message-ID: <3D24EC92.9070105@something.invalid>

robert_kuzelj at yahoo.com:

> class ProtoFactory:
>    def __init__(self):
>       self.SourceObjects = {}
>    def register(self, name, source):
>       self.SourceObjects[name] = source
>    def create(self, name):
>       source = self.SourceObjects(name)
>       if isinstance(source, types.Instance.Type):
>          return copy.copy(source)
>       else:
>          return source()


I would split the register method into two methods,
register_factory and register_prototype. That would
put the responsibility on whatever registers the
object to know what kind of thing it is.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



From irmen at NOSPAMREMOVETHISxs4all.nl  Tue Jul 23 18:58:30 2002
From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong)
Date: Wed, 24 Jul 2002 00:58:30 +0200
Subject: What unicode character has a certain value?
References: 
Message-ID: <3D3DDF96.8080805@NOSPAMREMOVETHISxs4all.nl>

DogWalker wrote:

> If I have the decimal value for a unicode character, how do I convert it to
> a unicode character?  A unicode apostrophe has a decimal value of 8217. How
> do I get a string with an apostrophe starting with 8217?

s = u'\u2019'

note: 0x2019 is hex(8217)

Irmen



From sholden at holdenweb.com  Mon Jul  1 10:34:31 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Mon, 1 Jul 2002 10:34:31 -0400
Subject: Most efficient way to write data out to a text file?
References: <3d1a6993.248534625@netnews.attbi.com>  <3d1dc547.468619140@netnews.attbi.com>   
Message-ID: 

"Bengt Richter"  wrote in message
news:afl9d1$5k0$0 at 216.39.172.122...
> On Sat, 29 Jun 2002 19:05:18 GMT, "Fredrik Lundh" 
wrote:
>
> >Dave Kuhlman wrote:
> >
> [...]
> >> Is finding things in globals slower than finding them in locals?
> >
> >yes.  Python assigns integer indices to local names, and
> >stores the corresponding objects in an array.
> >
> Is this done for built-in keywords also? ISTM a standard list
> of indices could be defined for a particular Python version,
> and code generated to take advantage.
>
I'm not sure this would help as much as you think, given that before a
built-in is used the interpreter must check that it isn't a module-global
name. Try

>>> None = "hello"
>>> print __builtins__.None
None
>>> print None
hello
>>> del None
>>> print None
None
>>> del __builtins__.None # now you're hosed...
>>> print None
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'None' is not defined
>>>

[...function call optimization...]

>
> If necessary to make it unambiguous and to make compilation easier, you
could have
> a "builtin" declaration analogous to "global." Or the usage might be
popular enough
> that you'd want a way to opt out instead of opt in. Since it's a bad idea
to rebind
> keywords anyway, maybe backwards compatibility wouldn't be too much of a
problem if
> it were default for some builtins functions in a future version?
>
There seems to be quite a lot of resistance to making such builtins
non-overridable. I suspect this is to do with wanting to retain as much
intropsection capaibility as possible.

> Hm, seems like you could do static arg count checks too for this kind of
builtin use.
>
> Hm2, wonder if you could allow user-defined assignment of functions to
dynamically
> assigned byte codes within a user range using "builtin user_func"
declarations,
> so that compilation would make analogous code like that suggested for real
builtins.
>
> OTTOMH just now, not exactly PEP-ready ;-)
>
Well, even if less than half-baked, at least considering some of the
problems you would actually encounter. Not sure this would be my first
choice for optimization when we don't even use constant-folding yet!

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------







From tdelaney at avaya.com  Mon Jul  8 22:07:16 2002
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Tue, 9 Jul 2002 12:07:16 +1000 
Subject: j2ee vs. python (and what our evil competitors are saying abo
	ut python)
Message-ID: 

> From: Neil Schemenauer [mailto:nas at python.ca]
> 
>     Their application code was edited using Emacs and Vi.  We only use
>     the Espressomatic 3501(TM) in our shop.  Vi and Emacs suck because
>     ....

There needs to be a "because" ...?

*Ducks*

Tim Delaney




From opengeometry at NOSPAM.yahoo.ca  Tue Jul  9 00:51:34 2002
From: opengeometry at NOSPAM.yahoo.ca (William Park)
Date: 9 Jul 2002 04:51:34 GMT
Subject: Linux clock-setting script
References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com>  <7xu1nb59qu.fsf@ruckus.brouhaha.com> 
Message-ID: 

William Park  wrote:
> Paul Rubin  wrote:
>> William Park  writes:
>>> >  http://www.nightsong.com/phr/python/setclock.py
>>> > 
>>> > I find it pretty useful for adjusting my computer clock every now and
>>> > then, without the hassle of setting up a real NTP system.
>>> 
>>> Thanks for the pointer, Paul.  Exactly what I needed.  Do you know any
>>> pure shell script that does the same thing?  I don't have Python
>>> installed on every machine.
>> 
>> I don't know about shell but it should be simple to write the same thing
>> in Perl or even in C.  
> 
> I've found a partial solution.  I'm now using, ntpdate time.apple.com
> time.windows.com time.nrc.ca ntp1.cmc.ec.gc.ca where 'ntpdate' comes from
> NTP package.  Still, shell solution would be desireable, because I
> sometime don't have access to Perl, Python, or NTP packages.  But, I do
> have access to shell all the time.
> 
> I'll update when I find solution. :)

Found it!

For those of you who need to set system clock only periodically, say once a
day, here are methods that are available:

1.  Network Time Protocol (RFC-1305, port 123):
	ntpdate time.nist.gov ...

    'ntpdate' is part of standard NTP package on any Linux distribution.

2.  Time Protocol (RFC-868, port 37):
	netdate time.nist.gov ...

    Slackware includes 'netdate' as part of base TCP/IP package.  You can
    use 'rdist' from
	ftp://ibiblio.org/pub/Linux/system/network/misc/
    but it is now deprecated in favour of 'netdate'.

3.  Daytime Protocol (RFC-867, port 13):
	date -u -s `telnet time.nist.gov 13 | grep UTC | cut -f2,3 -d' '`

    This is shell solution that I've been after.

Of course, one the system clock is set, you can set the CMOS clock by
    hwclock --systohc

-- 
William Park, Open Geometry Consulting, 
8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin


From cliechti at gmx.net  Mon Jul 22 19:07:10 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 23 Jul 2002 01:07:10 +0200
Subject: read-only character buffer, list
References: <85cee405.0207221446.750c36e3@posting.google.com>
Message-ID: 

akuip at yahoo.com (aaron) wrote in
news:85cee405.0207221446.750c36e3 at posting.google.com: 

> Ths following message is from a previous question.....my question is
> what if l = [0,1,2,3,4] is not a sequence...for example
> l=[.2,.009,.008,.05] how do I handle this?

this is still called a "sequence" in python. lists and tuples as well as 
strings are sequences. the order of the elements in the does not matter at 
all.

>>>> l=[0,1,2,3,4] 
>>>> f=open('e', 'w')
> >>> f.write(l) 
> Traceback (most recent call last): 
> File "", line 1, in ? 
> TypeError: read-only character buffer, not list <<< inserted "not" here

write() expects a string
writelines() expects a list of strings (lines or not does not matter, name 
symmetry because of readlines)

(a read-only buffer can be created with "buffer":
>>> b = buffer("hello")
>>> sys.stdout.write(b)
hello>>>

and now just forget it - you won't need "buffer"....)

> One could, of course, do the below: 
>>>> l = [0,1,2,3,4] 
>>>> f = open('e','w') 
>>>> f.write(''.join(map(str,l)))

yes, thats the way to go if the list contains non-strings 

chris

-- 
Chris 



From tdelaney at avaya.com  Tue Jul  2 22:32:08 2002
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Wed, 3 Jul 2002 12:32:08 +1000 
Subject: what can i expect...
Message-ID: 

> From: Shagshag13 [mailto:shagshag13 at yahoo.fr]
> 
> what can i expect if i change my python application to java ?
> (or when do you think it's time to change parts of python 
> code to java ? for what purposes ?)

Apart from the other (very well reasoned answers) ...

The only time you would generally want to change python code to java is so
you can run on a JVM or interface with java code.

In which case you do *not* want to convert your code to java. Instead, you
want to run your Python code on a JVM.

	http://www.jython.org/

Tim Delaney




From tim.one at comcast.net  Sat Jul 13 22:51:26 2002
From: tim.one at comcast.net (Tim Peters)
Date: Sat, 13 Jul 2002 22:51:26 -0400
Subject: switch recipe?
In-Reply-To: 
Message-ID: 

[Tim]
> ...
> For the same reason, range(10, 10) doesn't complain in Python, or
> string [i:i], etc -- doing nothing gracefully is important because
> there's sometimes nothing that needs be done .

[Mark McEahern]
> I think I'll continue to scratch my head and profit from that observation
> for quite some time.  Thank you.
>
> Profit--or better yet, lose.  My misconceptions, that is.  

If you can tolerate a little theory, the natural way to define "a sequence
of X" is

1. It's empty.
2. Or it's an X, followed by a sequence of X.

It's the 0 in "0 or more" that gives us empty files and empty lists and
empty generators (etc), and which in turn, e.g., makes "while" loops less
error-prone than "repeat ... until" loops in real life.  A program that
can't tolerate empty input vastly overestimates the real world's interest in
what it's doing .

> So where I've ended up is a place I'm sure there's some fancy
> name for--but I don't know it.

I don't think there's any overwhelmingly standard terminology in this area.
You make it up as you go along.  Generators are fundamental in the Icon
language (*every* Icon expression is "a generator" in theory, even integer
literals like 3), so that's a good place to look for a consistent set of
names in use for a long time:

    http://www.cs.arizona.edu/icon/





From cbbrowne at cbbrowne.com  Mon Jul 15 18:23:19 2002
From: cbbrowne at cbbrowne.com (Christopher Browne)
Date: Mon, 15 Jul 2002 18:23:19 -0400
Subject: Python's Lisp heritage 
In-Reply-To: Message from Ian Bicking  
   of "15 Jul 2002 16:09:43 CDT." <1026767383.703.298.camel@lothlorien.colorstudy.net> 
References:   <1026767383.703.298.camel@lothlorien.colorstudy.net> 
Message-ID: <20020715222319.AB5043C1FC@cbbrowne.com>

> On Mon, 2002-07-15 at 15:35, Christopher Browne wrote:
> > If a new Emacs mode requires adding in a bunch of additional
> > parameters, dynamic scope lets them be visible throughout the scope
> > during which they are "live" as opposed to just within the environment
> > in which they were defined.
> [snip]
> > If all you have is lexical scoping, parameters have to get explicitly
> > passed down the chain in order to get from function A to function C.
> > That means introducing additional parameters to function B, which
> > didn't actually care about those extra values.

> Interesting argument.  I think that you can achieve similar results
> with big state-holding objects (for better or worse).

Agreed.

Thinking of the Emacs context, from which this comes, if Emacs were
implemented using something nearer to Common Lisp, with an object
system more like CLOS, it would certainly be possible to attach extra
"slots," as needed, to the "big state-holding object."

That might very well be more manageable.

> With a web framework, that might be the request object.  Or in an
> editor in might be a buffer object.  If you have an object that
> persists for about the same scope as you need this extended
> information, you just set an attribute on that new object (or use a
> mix-in or some other technique).  Then, in your extensible
> application, this object gets passed around (perhaps indirectly) to
> most functions and methods that would be extensible.

I think that nicely characterizes the little bit of dilemma that is
involved.

Dynamic scope addresses the issue of "well, this shouldn't _really_ be
global data, but it's not as local as we'd like."

When that comes up, you've definitely hit something that's messy.

Dynamic scope tries to attach the data to the "overall scope of the
code," which is definitely extremely nebulous to try to grasp.  In
effect, the data gets tied to the environment; it works, but has
considerable risk of confusion, particularly because the data isn't
tied to anything that forcibly has an identity.

Attaching the data to "some big, state-holding object" is an approach
where, well, "it's using an object."  

In this context, the crucial definition of "object" is the classical
one that an object is a thing with an identity.  "Somewhere in the
environment" is certainly NOT an identity :-).

> This does kind of defeat lexical scoping, though it avoids use of
> globals.  While function signatures don't change, it's at the
> sacrifice of object interfaces.  OTOH, it seems to work okay.

I'd contend that there's no "defeat" involved.  This isn't a "battle"
with "winners" and "losers;" it's a situation of Trying to Solve
Problems.
--
(concatenate 'string "cbbrowne" "@ntlug.org")
http://www.ntlug.org/~cbbrowne/sap.html
Did you  hear about the dyslexic  agnostic insomniac who  stays up all
night wondering if there really is a Dog?




From aleax at aleax.it  Sun Jul 21 02:58:59 2002
From: aleax at aleax.it (Alex Martelli)
Date: Sun, 21 Jul 2002 08:58:59 +0200
Subject: unloading imported modules
In-Reply-To: 
References:   
Message-ID: <02072108585902.14257@arthur>

On Sunday 21 July 2002 00:33, Fran?ois Pinard wrote:
> [Alex Martelli]
>
> > > > > Is it possible in python intepreter to unload imported modules?
> > > >
> > > > No.
> >
> > Use sys.getrefcount(x) to know how many references there are to object
> > x, be it a module or any other kind of object.  When the reference
> > count of an object drops to 0, the object is freed (at once, or
> > eventually).
>
> So, when the reference count of a module drops to 0, and I get that this
> is possible, then the module is unloaded.  Isn't it?  Also, I wonder if

Sure should be.  To double check, add prints in moduleobject.c, function
module_dealloc, rebuild Python and give it a try.

> a module coming from an `.so' file be effectively reloaded.  And then, if

Sure, why not?  

>>> import _socket
>>> _socket.ssl

>>> _socket.ssl=23
>>> _socket.ssl
23
>>> reload(_socket)

>>> _socket.ssl


See -- _socket.ssl is put back to the value at module load time,
because we used reload, even though we had bound it to something
else in the meantine.  Or what do you mean by "effectively reloaded"?

> the previous copy (the memory area in which the `.so' is paged) gets
> freed?

I would expect that to be platform-dependent, specifically
dependent on what dlclose does on the platform.  But, how
hard can it be to give it a try on the platform of your interest?


Alex




From alife at narod.ru  Sat Jul 13 07:35:47 2002
From: alife at narod.ru (Serge Terekhoff)
Date: 13 Jul 2002 04:35:47 -0700
Subject: Q: DjVu on Python
Message-ID: <98322540.0207130335.4974ce32@posting.google.com>

Dear all:

Is there any support of DjVu document format (read and write)
on Python?

Sincerely
Serge A. Terekhoff,
http://alife.narod.ru/eng/


From charles at a3a.com.br  Mon Jul  8 15:11:07 2002
From: charles at a3a.com.br (Charles)
Date: Mon, 8 Jul 2002 15:11:07 -0400
Subject: Flush
Message-ID: <02070815110700.28840@magneto>

HI,
Anyone know if python has a flush() function like PHP,
to buffer dump in CGI ?


Regards
Charles





From sholden at holdenweb.com  Fri Jul 26 09:45:32 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Fri, 26 Jul 2002 09:45:32 -0400
Subject: how to count lines in a file ?
References:  <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> 
Message-ID: 

"Richard Jones"  wrote in message
news:mailman.1027633713.1308.python-list at python.org...
> On Fri, 26 Jul 2002 12:45 am, Alex Martelli wrote:
> > Michele Simionato wrote:
> > > Can somebody provide a simple example where the idiom
> > >
> > > file(name,'w').write(something)
> > >
> > > fails, in the sense that the file is not closed or something is not
> > > written ? I tried to hang the program with a memory overload
> >
> > [alex at lancelot jython-2.1]$ jython
> > Jython 2.1 on java1.4.0_01 (JIT: null)
> > Type "copyright", "credits" or "license" for more information.
> >
> > >> open('aname','w').write('something\n')
> >
> > [alex at lancelot jython-2.1]$ cat aname
> > [alex at lancelot jython-2.1]$ ll aname
> > -rw-rw-r--    1 alex     alex            0 Jul 25 16:41 aname
> > [alex at lancelot jython-2.1]$
> >
> > I exited the interactive interpreter with a clean, normal
> > control-D, but as you see file aname was created but its
> > contents not written.
> >
> > Any implementation of Python is perfectly free to choose
> > this behavior if it provides some other advantage.
>
> I think the major problem that we're running into here is that before
there
> was GC, the refcounting-based cleanup of objects was clear,
straight-forward
> and reliable. Now it's not clear when objects are cleared up. That's a
fairly
> major problem for some of us old-timers (and, quite possibly, a lot of
> newbies) to come to terms with. I hadn't realised that GC threw such a
big,
> ugly spanner in the works :(
>

The "ugly spanner" thrown by GC is simply the ability to collect cyclic
garbage. By definition, in prior implementations of CPython, such garbage
was never collected (and therefore the __del__() method was never called on
objects in cycles) because the refcount never went down to zero.

So what you appear to dislike is that there is now a *chance* that __del__()
will be called on cyclic garbage, when there wasn't before.

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------







From fperez528 at yahoo.com  Tue Jul  9 17:59:01 2002
From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=)
Date: Tue, 09 Jul 2002 15:59:01 -0600
Subject: Why self?
References:  <090720020820257031%pecora@anvil.nrl.navy.mil>  <090720021359063518%pecora@anvil.nrl.navy.mil>
Message-ID: 

Louis M. Pecora wrote:

> 
> Hmmm...a pretty bizzare example or else I just don't have enough
> programming experience.??I've?never?done?anything?close?to?that.??I
> will have to rely on others experience (including yours, which I know
> is substantial).??Is?this?realistic?or?are?you?just?pulling?out?a
> pathological example for argument?

Well, if you care you can look at http://www-hep.colorado.edu/~fperez/ipython/

IPython is a replacement for the normal interactive interpreter with a ton of 
added features. Amongst those, it is fully extensible by the user, even at 
run time. This requires adding methods to the instance of the interpreter you 
are running on top of while it is running, and those methods are actually 
automatically generated code (via parametrized method templates). So it's 
somewhat funky kung-fu, but it works beautifully.

In my view, that flexibility (users can customize the environment a lot 
without ever touching the source) is one of ipython's strong points, and a 
lot of it would have been an utter nightmare to write (if possible at all) in 
a language without the dynamism and flexibility of python.

So I for one, would scream bloody murder if you tried to remove python's 
ability to dynamically modify objects at run-time and even with code they 
themselves autmatically write and compile while active.

If you call that bizarre, I simply call it 'you hadn't thought of it yet'.

Cheers,

f.


From peter.maas at mplusr.de  Fri Jul 19 04:22:13 2002
From: peter.maas at mplusr.de (Peter Maas)
Date: Fri, 19 Jul 2002 10:22:13 +0200
Subject: property problem
References: <3D36C65A.5040300@mplusr.de> <3d36d97f$1_2@hpb10302.boi.hp.com>
Message-ID: <3D37CC35.30101@mplusr.de>

Daniel Fackrell wrote:
>>class proptest:
>>
>>  def __init__(self):
>>  self.__data = 0
> 
> 
> This declaration invokes python's name mangling.  The creation of x later
> will call this constructor and the __data attribute will appear as
> x._proptest__data (I think).

[...]

>>This is my testcode:
>>
>> >>> x = proptest()
>> >>> x.data=234
> 
> 
> This line creates a new attribute named x.data, which is completely
> unrelated to x._proptest__data

Daniel,

it's not unrelated because of the property call
in my code. I missed the fact that I had to subclass object.
Thanks for your help.

Regards,

Peter Maas

-- 
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de
-------------------------------------------------------------------



From martin at v.loewis.de  Fri Jul 12 15:26:03 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 12 Jul 2002 21:26:03 +0200
Subject: Linking to Python 2.2
References: 
Message-ID: 

"Nathan Cassano"  writes:

> 	I am having trouble linking to the Python library for
> development purposes. Does anyone know the correct way to link to Python
> version 2.2? 

The correct way depends on the operating system. In this case, you
should study and understand the error messages, and correct them.

> /usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function
> `posix_tempnam':
> /usr/src/packages/BUILD/Python-2.2.1/./Modules/posixmodule.c:4451: the
> use of `tempnam' is dangerous, better use `mkstemp'

This is a warning; you can ignore it.

> /usr/src/packages/BUILD/Python-2.2.1/Objects/complexobject.c:148:
> undefined reference to `sin'

This is an error. The symbol "sin" is defined by the math library, so
you need to link with "-lm". Add this linker option, then see what
other errors remain. Proceed for other undefined symbols in the same
way: find out where these symbols are defined, and add the missing
libraries.

In principle, you can use both distutils and the installed
Makefile.pre to obtain the necessary information in a
platform-independent way. However, it would be simpler to just adjust
the build process manually if you target only a few systems.

HTH,
Martin


From thehaas at binary.net  Wed Jul 17 18:38:19 2002
From: thehaas at binary.net (thehaas at binary.net)
Date: Wed, 17 Jul 2002 22:38:19 GMT
Subject: 'capwords' is not a string method
References:  
Message-ID: 

Alex Martelli  wrote:
> Apparently, they took occasion of the introduction of string
> methods to replace the semi-crippled capwords (which only
> capitalizes words _preceded by whitespace_) with the better
> method title, which capitalizes words even when they are
> preceded by punctuation, as well as whitespace.  It seems
> sensible to me -- the need met by .title() is more frequent,
> and if the issue is backwards compatibility, capwords is
> still around (in the semi-obsolescent string module -- only
> semi, because it supplies crucial constants such as digits,
> letters, whitespace, etc).

I didn't know about the 'title' method . . .I'll try that.  I'd rather
use string's built-in methods than (how you put it) the semi-obsolescent
string module.

-- mikeh


-- 
Mike Hostetler          
thehaas at binary.net 
http://www.binary.net/thehaas 
GnuPG key: http://www.binary.net/thehaas/mikeh.gpg 


From mcfletch at rogers.com  Tue Jul  2 15:45:30 2002
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Tue, 02 Jul 2002 15:45:30 -0400
Subject: Useful RE patterns (was: Variable Interpolation - status of PEP
 215)
References:  <4PfQ8.44245$n4.10307683@newsc.telia.net>  <3D1203A2.B2A3AD9@email.sps.mot.com>  <3D21FF32.6090902@rogers.com>
Message-ID: <3D2202DA.2030302@rogers.com>

Mike C. Fletcher wrote:
...
 >     Irrational numbers (under numbers, i or j forms)

Obviously that should have been complex numbers, though it might be nice 
to have support for:

	Irrational Numbers: pi, e, any others of note? (allow 2pi, 2.5pi, (3/2) 
pi, pi*3, but not pi3 or pi4 etceteras) := (expression)?,pi

(though it doesn't seem spectacularly difficult to create with any 
grammar anyway) as well as:

	Complex numbers: (under numbers, i or j forms)

Which, I suppose, are almost the same basic structure, call it 
"mathematical numeric units" or something (i.e. act like a unit in that 
they don't need explicit * signs, but have a mathematical value when 
used alone)... anyway...

Enjoy,
Mike





From abhijit_som at yahoo.co.in  Fri Jul 19 01:55:53 2002
From: abhijit_som at yahoo.co.in (Abhijit Soman)
Date: Fri, 19 Jul 2002 05:55:53 +0000 (UTC)
Subject: Recursion
Message-ID: 

In the recursive function below i want to add the individual bits to a 
string and return that string to the caller
Can anyone tell me how to do that


    def showbits(x):
        if x != 1:
          showbits(x >> 1)        
        if x & 01:
	    print 1,
        else:
	    print 0,



From paul at boddie.net  Tue Jul  9 13:38:05 2002
From: paul at boddie.net (Paul Boddie)
Date: 9 Jul 2002 10:38:05 -0700
Subject: python & web services
References: <6pNV8.24555$2w.1181063@news20.bellglobal.com>
Message-ID: <23891c90.0207090938.364fe91e@posting.google.com>

"John"  wrote in message news:<6pNV8.24555$2w.1181063 at news20.bellglobal.com>...
> What is currently available for the development of web services in python?
> Does Zope provide a complete solution? (I am new to both and plan to learn
> them together)

I believe Zope supports XML-RPC "out of the box" combined with its own
usual paradigms. Apart from that, there are various projects which are
summarised in a presentation given at EuroPython:

  http://www.europython.org

Specifically:

  http://europython.zope.nl/sessions/presentations/WebServices/EPC2002-Duncan_Grisby-Web_Services_Parts_1_and_2.pdf

Paul


From m.laranjeira at datacraft.com.br  Tue Jul 30 11:08:59 2002
From: m.laranjeira at datacraft.com.br (Marcus Vinicius Laranjeira)
Date: Tue, 30 Jul 2002 12:08:59 -0300
Subject: How to find out if february has 29 or 28 days ?
In-Reply-To: 
References: 
 
Message-ID: <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br>


Folks,

I use the mx.DateTime package, and I need to know if in one particular year 
has a february with 28 or 29 days ? I don't know how to do that !

Cheers,

Marcus




From dig.list at telkel.net  Tue Jul 30 04:35:47 2002
From: dig.list at telkel.net (DIG)
Date: Tue, 30 Jul 2002 03:35:47 -0500
Subject: global interpreter lock not working as it should
In-Reply-To: ; from "Just" on Tue, Jul 30, 2002 at 09:52:52AM
References:   <200207292348.TAA31011@test-area.com>  
Message-ID: <20020730033546.C4976@lifebook>

Hi, Just !

 On Tue, Jul 30, 2002 at 09:52:52AM +0200, Just wrote:

> I can see it on MacOSX, three different Linux boxes and a FreeBSD box. 
> Various Python versions. The output is always sequential.
                                                ^^^^^^^^^^
Same here:

$ python -c "import sys; print sys.version"
1.5.2 (#1, May 28 2000, 18:04:10)  [GCC egcs-2.91.66 19990314/Linux (egcs-
$ uname -r
2.2.16
   

Best regards,

-- 
DIG (Dmitri I GOULIAEV)



From sdeibel at wingide.com  Wed Jul  3 14:04:40 2002
From: sdeibel at wingide.com (Stephan R.A. Deibel)
Date: Wed, 3 Jul 2002 14:04:40 -0400 (EDT)
Subject: PythonWin + other GUIs = CRASH! 
Message-ID: 

>IDLE crashes with Qt and pygame, too. It seems to be a general problem:
>It is not possible to start a GUI-Toolkit, when the application or the
>IDE is using a GUI itself. The only GUI which seems to work with most
>IDEs is tkInter. PyQt, wxPython and Pygame will crash.

Try Wing IDE.  Definately works with tkInter, PyQt, wxPython, and pygtk.
Also Zope, mod_python, numpy, and a bunch of other environments.  Not sure
about pygame, although Wing 1.1.5 makes improvements that might solve the
problems we had previously due to pygame's mucking with thread state

Sorry for the shameless plug (Wing IDE is a commercial product and I'm one
of the developers).  However, it does very likely solve the problem you
have.

Also, if you use Wing solely to develop non-commercial open source code,
you can apply for a free license.

BTW, I believe IDLE runs the debug process inside its own process, which
explains why it would crash if you introduce another mainloop that takes
control.  Not sure about PythonWin off-hand.  To avoid this, Wing always
runs the debug code in a seperate process.

It's definately not easy to write an industrial-strength Python debugger
than handles everything correctly... we've had to put a lot of effort into
it and there are still things that need to be done.

- Stephan

------------------------------------------------------------------------
Wing IDE for Python                          Archaeopteryx Software, Inc
www.wingide.com                              Take Flight!






From claird at starbase.neosoft.com  Mon Jul  8 20:15:46 2002
From: claird at starbase.neosoft.com (Cameron Laird)
Date: 8 Jul 2002 19:15:46 -0500
Subject: j2ee vs. python (and what our evil competitors are saying about python)
References: <96c7f32.0207081518.52ea644a@posting.google.com>
Message-ID: 

In article <96c7f32.0207081518.52ea644a at posting.google.com>,
curt finch  wrote:
>Our free web timesheet app is written totally in Python.  
>One of our competitors is saying the following
>things about python to our customers.  Help me make them look stupid. 
			.
			.
			.
>Summary
>Python is often used as pseudocode to conduct rapid development. Its
>major users are web sites that do not reuse code and often conduct
>“throw away” development to meet internet development time
>tables. It is a very new language and has very little support compared
>to the Java development community. It is also not J2EE compliant.
			.
		[much more]
			.
			.
Python has plenty of problems.  I advise against it
for specific clients.

What this person has written, though, is so ridicu-
lous as to beg serious, detailed rebuttal.  To begin,
Python's nearly twice as old as Java.  Java's major
users are college students who still don't pay for
their own housing (or, at least, that's as true as
the quoted slander).  The person who wrote the comments
above cannot, I'll speculate, coherently answer whether
Java itself is J2EE-compliant.
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://starbase.neosoft.com/~claird/home.html


From aleax at aleax.it  Wed Jul 24 12:11:13 2002
From: aleax at aleax.it (Alex Martelli)
Date: Wed, 24 Jul 2002 16:11:13 GMT
Subject: Callable modules?
References: <7xznwk1hfy.fsf@ruckus.brouhaha.com>  <3D3E9BCF.90806@mxm.dk>  
Message-ID: 

Jonathan Hogg wrote:
        ...
> For example, there is no way of redefining the 'repr' of a function, or
> the attribute interface. Without __call__ the closest I could come would
> be to define a metaclass that creates class objects with a __new__ method
> implementing the call interface - a truly monstrous idea.

You have a point.  Such a need is so rare and weird that I would not be
highly troubled by having to use weird ways to meet it.  However, taking
"callability" as outside the range of polymorphically emulable behaviors
would indeed reduce regularity, so it might be a bad idea even though the
serious use cases for it ARE weird:-).


Alex



From chris.lyon at spritenote.co.uk  Sun Jul  7 05:28:51 2002
From: chris.lyon at spritenote.co.uk (chris lyon)
Date: Sun, 7 Jul 2002 10:28:51 +0100
Subject: Concept Error 
References: <3d27d274$0$24427$afc38c87@news.easynet.co.uk>
Message-ID: <3d2809cc$0$24392$afc38c87@news.easynet.co.uk>

Apologies the variable 'a' below should be 'conn'

"chris lyon"  wrote in message
news:3d27d274$0$24427$afc38c87 at news.easynet.co.uk...
> I've been at it all night and I don't understand why this does work:-
> (Its derived from www.e-coli.net/pyado.html , ok it's a straight copy )
>
>
> import win32com.client
>
> class RecordSet:
>     def __init__(self, DBConnection):
>         """Initialize a Record Set Object"""
>         self.rs = win32com.client.Dispatch(r'ADODB.Recordset')
>         self.conn = DBConnection
>
>     def listfields(self):
>         for x in range (self.rs.Fields.Count):
>             print 'Name:-',self.rs.Fields.Item(x).Name
>             print 'DefinedSize:-',self.rs.Fields.Item(x).DefinedSize
>             print 'Type:-',self.rs.Fields.Item(x).Type
>             print 'Value:-',self.rs.Fields.Item(x).Value
>
> conn = win32com.client.Dispatch(r'ADODB.Connection')
> DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/octavia/c4i.mdb;'
> conn.Open(DSN)
>
>  fred = RecordSet(a)
>  fred.rs.CursorLocation = 3
>  fred.rs.Open('[Categories]',a.conn,1,3)
>  fred.listfields()
>
>
>
> But this fails to run.
>
> import win32com.client
>
> class RecordSet:
>     def __init__(self, DBConnection):
>         """Initialize a Record Set Object"""
>         self.rs = win32com.client.Dispatch(r'ADODB.Recordset')
>         self.conn = DBConnection
>
>     def listfields(self):
>         for x in range (self.rs.Fields.Count):
>             print 'Name:-',self.rs.Fields.Item(x).Name
>             print 'DefinedSize:-',self.rs.Fields.Item(x).DefinedSize
>             print 'Type:-',self.rs.Fields.Item(x).Type
>             print 'Value:-',self.rs.Fields.Item(x).Value
>
>     def getalltable(self , tablename, conn):
>         self.rs.CursorLocation = 3      #adUseClient
>         self.rs.Open('[Categories]', conn , 1 ,3)   #adOpenKeySet
> adLockOptimistic
>
> conn = win32com.client.Dispatch(r'ADODB.Connection')
> DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/octavia/c4i.mdb;'
> conn.Open(DSN)
>
> fred = RecordSet(a)
> fred.rs.CursorLocation = 3
> fred.getalltable('Categories', a)
> fred.listfields()
>
>
> It Fails with:-
>
>   File
>
"C:\Python21\win32com\gen_py\00000205-0000-0010-8000-00AA006D2EA4x0x2x5.py",
> line 2008, in Open
>     return self._oleobj_.InvokeTypes(0x3fe, LCID, 1, (24, 0), ((12, 17),
> (12, 17), (3, 49), (3, 49), (3, 49)),Source, ActiveConnection, CursorType,
> LockType, Options)
> TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a
> buffer object.
>
> Why can't I just treat rs as a property of the class RecordSet ?
> Obviously I can get functionality I require but I do not understand why I
> can't treat the RecordSet this way.
>
> I've examined as much of the underlying code as I can but I'm quickly
lost,
> and I notice that win32com.client.Dispatch is a function not a class so I
> can't sub-class it so that way seems closed.
>
> It feels that I am missunderstanding some aspect of the class mechanism so
I
> would dearly like to know what I'm doing wrong.
>
> ( And I will NOT write this app in VBScript :-)
>
> Chris Lyon
>
>
>
>
>
>




From ianb at colorstudy.com  Tue Jul  9 22:40:26 2002
From: ianb at colorstudy.com (Ian Bicking)
Date: 09 Jul 2002 21:40:26 -0500
Subject: php function "addslashes" / "removeslashes" in python
In-Reply-To: 
References: 
Message-ID: <1026268826.498.24.camel@lothlorien.colorstudy.net>

I find these PHP functions rather crude -- proper encoding is
domain-specific, and it's not clear what the domain for addslashes is. 
Usually it is SQL, I suppose.  Most (all?) database adapters include an
encoding routine.

You can use repr() as a quoter, but it acts a little funny.  You could
use something like this:

def addslashes(s):
    return repr('"' + s)[2:-1].replace('"', '\\"')

This is fairly fast, but I don't know of a good way to decode this
(except eval, which I would strong suggest you not use).

  Ian






From debl2nonspammyno at bellatlantic.net  Mon Jul 29 00:50:49 2002
From: debl2nonspammyno at bellatlantic.net (David Lees)
Date: Mon, 29 Jul 2002 04:50:49 GMT
Subject: How to install Jython?
Message-ID: <3D44C9CC.A0DBC792@bellatlantic.net>

I need very basic configuration advice to install jython-21 on my
win98SE box.  I am doing something wrong. I downloaded
jython-21.class.exe but am unable get it do self-extraction.  I gather
that this is not an windows .exe, but some sort of machine independent
self extracting file that you run java to extact.  I open up a DOS
window, go to the directory with the download and type:
java jython-21
and get a message 'Exception in thread "main"
java.lang.NoClassDefFoundError: jython-21'

I know I have java on my system and I even took the trouble of
downloading from the sun site java 1.3.1_04, installing it and typeing
the full path to it and I still get the same message.

Thanks in advance.

David Lees


From mgerrans at mindspring.com  Mon Jul 22 11:24:32 2002
From: mgerrans at mindspring.com (Matt Gerrans)
Date: Mon, 22 Jul 2002 08:24:32 -0700
Subject: unsigned ints and operator.rshift
References: <3D3C1802.948E2D99@mill.co.uk>
Message-ID: 

I'm sure there's a better way, but in the mean time, here is a shamelessly
cheesy method:

def rShift( i, n ):
   leftbit = 0x80000000
   if i & leftbit:
      return ((i& ~leftbit)>>n)|(0x40000000 >> n-1)
   return i >> n

(this is won't work so well on platforms that have 64-bit ints, either)




From logiplexsoftware at earthlink.net  Thu Jul 11 14:35:06 2002
From: logiplexsoftware at earthlink.net (Cliff Wells)
Date: Thu, 11 Jul 2002 11:35:06 -0700
Subject: Python in the enterprise: Pros and cons
In-Reply-To: 
References: <200207110952.21663.b.maryniuk@forbis.lt>
	
	
	
Message-ID: <20020711113506.2afdd7ea.logiplexsoftware@earthlink.net>

On 11 Jul 2002 16:37:33 GMT
Martijn Faassen wrote:

> Cliff Wells  wrote:
> > On Thu, 11 Jul 2002 05:47:22 -0400
> > Tim Peters wrote:
> [the enterprise]
> >> It's an especially annoying American buzzword for "business use, as
> >opposed> to consumer, research, or educational use".  Your enterprise-ready
> >software> is primed to take on the challenge of synergizing mission-critical
> >business> logic in empowering ways.  IOW, it computes the sales tax right
> >more often> than not .
> >> 
> 
> > I always took "enterprise" to mean "runs on an AS/400 with a text
> > interface", or possibly as a synonym for "token-ring".
> 
> I thought it involved that starship with the federation and the vulcans and 
> such. Their computer system gets taken over by alien entities quite
> frequently, so I imagine they run software for the Enterprise.

Haven't those fools on the Enterprise installed all of the service packs??? 
SP5 for Windows SD45245 will have been available for some time by then.


-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




From sjoshi at ingr.com  Sun Jul 28 12:17:47 2002
From: sjoshi at ingr.com (Sunit Joshi)
Date: 28 Jul 2002 09:17:47 -0700
Subject: Help! Python to compare dates in diff. timezones
Message-ID: <8f8ffe67.0207280817.6fc327b8@posting.google.com>

Hello All

I have problem which is like this: 
I have two sites A & B which are in diff. countries in diff.
timezones.
Now both sites have same drawings (Microstation files with same names)
whose revision dates (as integer since epoch) are stored in a table in
database at both sites. The database structure is same on both sites
with identical table names.

Now since the sites are different timezones, I was wondering what
would be the best way to compare drawings, using Python, that have
changed between two sites; for e.g. if site A wants to gets a list of
all models that have changed at site A.

I'm open to any suggestion like using a query over HTTP, using XML,
etc.

thanks
Sunit
sunitjoshi at netzero.net


From johnroth at ameritech.net  Tue Jul 30 19:22:50 2002
From: johnroth at ameritech.net (John Roth)
Date: Tue, 30 Jul 2002 19:22:50 -0400
Subject: Let's Talk About Lambda Functions!
References: <20020726024901.2725.176.Mailman@mail.python.org><3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org>  
Message-ID: 

"Ian Bicking"  wrote in message
news:mailman.1028054866.6584.python-list at python.org...
> On Tue, 2002-07-30 at 11:05, John Roth wrote:
> > I tend to agree with you on that one, but it's a matter of style. I
> > observe
> > that e.g. Smalltalk style does anonymous code blocks all over the
place.
>
> I've seen people argue that you can do all the same things with
> iterators as Smalltalk does with code blocks.  And, really, it's not
as
> though Smalltalk has truly novel control structures -- everything
still
> boils down to while, for, and if.  Smalltalk does give you easy
> callbacks, though.
>
> > There's no reason my proposal couldn't be extended to anonymous
> > classes: the syntactic issues are exactly the same. The difficulty
is
> > in extending it to methods, as opposed to functions. The only way
> > to distinguish a method from a function today is to observe that
> > methods are defined at the top level of a class; a def anywhere
> > else is a function (I think.)
>
> A method is just a function that is bound to a class variable.  So you
> can do something like:
>
> class X:
>     pass
>
> X.func = lambda self, x: x * 2
> x = X()
> x.func(10)
> ==> 20
>
> In fact, you can even do:
>
> class X:
>     func = lambda self, x: x * 2

Unfortunately, that won't work. The word 'self' is not
magic - using it doesn't convert a function to a method.

On the other hand, if 'self' was the name assigned
to the instance in the enclosing method definition, it
would acomplish just about everything required. I suspect
there are a few corner cases it wouldn't handle, to
the confusion of all and sundry.

Someone who knows the language in more depth
than I do would have to comment on that.

John Roth





From whisper at oz.net  Sun Jul 28 17:27:41 2002
From: whisper at oz.net (David LeBlanc)
Date: Sun, 28 Jul 2002 14:27:41 -0700
Subject: Guide to the python interp. source?
In-Reply-To: <15684.23324.498143.792539@localhost.localdomain>
Message-ID: 

Even better, how about putting it on the Python org wiki?

David LeBlanc
Seattle, WA USA 

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Skip Montanaro
> Sent: Sunday, July 28, 2002 13:59
> To: Andreas Kostyrka
> Cc: Tim Gahnstrom /Bladerman; python-list at python.org
> Subject: Re: Guide to the python interp. source?
> 
> 
> 
>     >> I noticed, but thought that I just had missed it. I thought there
>     >> must be some where for such a large project. But the problem is
>     >> ofcourse ever present, "nobody likes to do documentation"
> 
> Something occurred to me last night...  How about a PyVM Wiki?  Once the
> content is there we could see about organizing it in a suitable form for
> inclusion in the standard document set.
> 
> I started things off with some notes I wrote a few months ago:
> 
>     http://manatee.mojam.com/pyvmwiki/
> 
> -- 
> Skip Montanaro
> skip at pobox.com
> consulting: http://manatee.mojam.com/~skip/resume.html
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



From danieleburrow at yahoo.com  Fri Jul 19 14:15:48 2002
From: danieleburrow at yahoo.com (Daniel E. Burrow)
Date: 19 Jul 2002 11:15:48 -0700
Subject: HTML DOM parser?
References: 
Message-ID: 

"David LeBlanc"  wrote in message news:...
> adding time.sleep(2) made it work - gave the browser time to _have_ a
> document :-)
> 
> David LeBlanc
> Seattle, WA USA
> 
> > -----Original Message-----
> > From: python-list-admin at python.org
> > [mailto:python-list-admin at python.org]On Behalf Of David LeBlanc
> > Sent: Thursday, July 18, 2002 18:11
> > To: Paul Rubin; python-list at python.org
> > Subject: RE: HTML DOM parser?
> >
> >
> > > The exception might be legitimate, because of the 403 error.  Try
> > > www.yahoo.com instead of www.nightsong.com.  www.nightsong.com really
> > > does return a 403.
> > > --
> >
> >
> > Nope - it's the call to ie.document that chokes. ie.navigation does open
> > www.w3.org just fine, but trying to get to the DOM isn't working.
> >
> > It looks like there's no attribute "document" for this interface...
> >
> > Dave LeBlanc
> >
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list

Greetings!

I still get the exception if I don't use the ".Document" reference. My
code is suppose to wait for IE to return a "not busy" result before
going on.

I recall Mr. Hammond giving an example where he was waiting for IE's
"ReadyState" to return what would be true when ready state was
obtained. I used to use a method to determine ready state and then go
on to determine if IE was "Busy". I found that using the "Navigate2"
method seemed to obviate the need for checking IE's ready state.
Perhaps I should leave the ready state method in?

Here are a few snippets:

################## start of snips #####################

In main I call:

            o_AleApp.NavigateIE(s_URL)
            ##fire events after nav test
            o_AleApp.ClickCrossFrameElement(1, 'Sub1t')

In NavigateIE I run:

    def NavigateIE(self, s_URL):
        i_Sleep = self.GetDelaySecondsBetweenPageNavs()
        print "Class: AleAppWebReporter Method: NavigateIE: Sleeping",
i_Sleep, "seconds prior to navigating..."
        time.sleep(i_Sleep)
        print "Class: AleAppWebReporter Method: NavigateIE: Navigating
to:\n" + s_URL
        self.o_IE.Navigate2(s_URL)
        ##now lets make sure the page has fully loaded                
        s_NotBusy = self.WaitForNotBusy()
        if s_NotBusy == 'TRUE':
            return 'TRUE'
        else:
            return s_NotBusy

In WaitForNotBusy I run:

    def WaitForNotBusy(self):
        print "Class: AleAppWebReporter Method: WaitForNotBusy:
Current URL:", self.GetIELocationURL()
        i_IEBusy = int(self.GetIEBusy())
        print "Class: AleAppWebReporter Method: WaitForNotBusy:
i_IEBusy:", i_IEBusy
        if i_IEBusy != 1:
            return 'TRUE'
        else:
            i = 1
            i_State = 0
            while i_State == 0:
                print "Class: AleAppWebReporter Method:
WaitForNotBusy: Waited:", i, "seconds for IE to complete
downloading..."
                time.sleep(1)
                i_IEBusy = int(self.GetIEBusy())
                print "Class: AleAppWebReporter Method:
WaitForNotBusy: i_IEBusy:", i_IEBusy
                if i_IEBusy != 1:
                    i_State = 1 
                i += 1
            return 'TRUE'

In GetIEBusy I run:

    def GetIEBusy(self):
        return self.o_IE.Busy

################## end of snips #####################


From gerhard.haering at gmx.de  Fri Jul 19 10:26:57 2002
From: gerhard.haering at gmx.de (Gerhard Haering)
Date: 19 Jul 2002 14:26:57 GMT
Subject: Newbie Word  & Text file access?
References: <3D381EB2.1030506@mcw.net>
Message-ID: 

In article <3D381EB2.1030506 at mcw.net>, David Wilson wrote:
> Newbie question after checking about 500 messages on comp.lang.python : 
> Using W2K on Intel, Python 2.2.1, and IDLE 0.8
> 
> Unsuccessful open() of MS Word (.doc) , Abiword (.abw) and text (.txt) 
> files after successfully opening and reading HTML (.html) and LOG files.
> 
> Sample IDLE output:
> 
> >>> open("C:\DownLoad\test1.txt","r")
> Traceback (most recent call last):
>    File "", line 1, in ?
>      open("C:\DownLoad\test1.txt","r")
> IOError: [Errno 2] No such file or directory: 'C:\\DownLoad\test1.txt'
                                                   ^^        ^^
The \\ is an escaped backslash, the \t is a tab.

> 1) What else is necessary to open these types of files?

Be careful when using backslashes in strings. In normal Python strings, they
need to be escaped with an additional backslash, like \\, as there are special
sequences like \t (Tab), \n (newline), and others. Here's the full
specification: http://www.python.org/doc/current/ref/strings.html

> 2) Please advise where I can find documentation on IDLE and/or Python 
> errors such as "[Errno 2]" above?

The interesting part is the IOError string "No such file or directory." It says
all there is to know ;-) Errno 2 is AFAIK just the error code from the
underlying operating system, and IMO normally irrelevant.

> 3) Is there a parser utility which can massage these formatted document files
> for faster/easier subsequent manipulation?

For M$ Word .doc files, you could try to automate Word with the win32 COM
extensions. Abiword uses an XML-based format, right? So you can operate with
XML libraries on it. And on .txt files, you can operate with the standard
Python libraries.

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))


From jonathan at onegoodidea.com  Tue Jul  2 06:13:17 2002
From: jonathan at onegoodidea.com (Jonathan Hogg)
Date: Tue, 02 Jul 2002 11:13:17 +0100
Subject: Where python especially good ?
References: 
Message-ID: 

On 2/7/2002 9:02, in article afrmbm$d28$07$1 at news.t-online.com, "Andrey
Koubychev"  wrote:

> What do you think, at what tasks pythons shows great benefits comparing to
> other script languages ?

I think the Python language shows its greatest strength when you aren't
writing scripts ;-)

Seriously, I don't think of Python as a scripting language the way I'd think
of perl or sh or awk. I view it as a systems programming language, and some
fair size systems have been written in it.

The main advantages of it to me are speed of development and ease of
maintenance. I think Python has the edge over other "scripting" languages in
both of these areas: it has an interactive interpreter; it is strongly, but
simply, object-oriented (Perl doesn't come close here); it has a very good
standard library; Python code tends to be readable.

I think comparing Python to Java is fairer, and I find Python to be a much
more pleasant language to work with.

[When I was doing my last big Java project, we prototyped the whole thing in
Python first then re-coded it into Java. Even during the Java development I
used Jython to test and explore the Java code.]

If you just want to munge a log file with some heavy regular expressions and
spit out some statistics or something, then you might be better off with
Perl. But if you want to write a program, look at Python.

Jonathan



From a at b.com  Sun Jul  7 18:07:35 2002
From: a at b.com (Thinkit)
Date: Sun, 07 Jul 2002 22:07:35 GMT
Subject: openprojects python room is ruled by dangerous people
References: <3eeda89d.0207070906.1fa45916@posting.google.com> 
Message-ID: 

"Gerhard H?ring"  wrote in message
news:mailman.1026076451.27466.python-list at python.org...
> Somebody with the uncool pseudonym of "Thinkit" wrote:
> > These people are dangerous, and will boot you if you do not agree to
their
> > narrow worldview.
>
> Their twisted worldview? You can safely ignore twisted, if you're not into
> network programming. At least I do and I still feel safe, despite not
agreeing
> with dash and moshez on everything :-) And I don't think anybody gets
kicked
> there unless (s)he's trolling repeatedly.
>
> > They are an affront to the python language--especially "dash".
>
> I don't think so. Just don't try to argue about Free Software, C++ or
LISP,
> unless you've done your homework. Apart from that, it's the coolest irc
channel
> I've seen yet.

That's why I keep trying to get back in.

> Gerhard, aka Xamines
> --
> mail:   gerhard.haering at gmx.de              registered Linux user #64239
> web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
> public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
> reduce(lambda x,y:x+y,map(lambda
x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
>
>
>




From mfranklin1 at gatwick.westerngeco.slb.com  Mon Jul 29 15:32:18 2002
From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin)
Date: Mon, 29 Jul 2002 19:32:18 +0000
Subject: Pmw.MenuBar hotkeys
In-Reply-To: 
References: 
Message-ID: <200207291832.g6TIWf028183@helios.gatwick.geco-prakla.slb.com>

On Monday 29 Jul 2002 6:23 pm, Matthias Huening wrote:
> Hi,
>
> I seem unable to get the hotkeys to work with Pmw.MenuBar.
> They should be activated with +hotkey, but nothing happens... When a
> menu is opened, the hotkeys of the different menu items do work. The
> problem is only with the hotkeys on the menu bar. Any ideas?
>
> Matthias

Matthias,

Have you got a small example?  I think I've had these working.....


Martin



From aleax at aleax.it  Sun Jul  7 10:28:35 2002
From: aleax at aleax.it (Alex Martelli)
Date: Sun, 07 Jul 2002 14:28:35 GMT
Subject: FancyURLopener: no HTTP status codes?
References: <3D281E6F.2080909@snakefarm.org>
Message-ID: 

Carsten Gaebler wrote:

> Hi there,
> 
> is there any possibility of getting the HTTP status code from a
> urllib.FancyURLopener object?

I don't think class FancyURLopener keeps any memory about what
happened on its most recent open method call, if that's what you
mean.  I guess you could subclass it in order to do so, but that
seems fragile and error-prone.  Maybe using lower-level httplib,
or fancier urllib2, provides better architectural prospects.


Alex



From akuchlin at ute.mems-exchange.org  Thu Jul 18 12:57:11 2002
From: akuchlin at ute.mems-exchange.org (A.M. Kuchling)
Date: 18 Jul 2002 16:57:11 GMT
Subject: python2 import trouble (linux - redhat)
References: <20020714141757.128895ce.mmellor1@yahoo.com>  <3D35A628.A9ADF9B6@noaa.gov> <1026930878.3325.1.camel@jwilhelm.ofsloans.com>  <3D36EE51.4CC0E9CD@noaa.gov>
Message-ID: 

In article <3D36EE51.4CC0E9CD at noaa.gov>,
	Chris Barker wrote:
> Does anyone know an appropriate contact at RedHat that we could mass
> mail to?

Report it in Bugzilla at http://bugzilla.redhat.com/bugzilla/ .

--amk


From smarsh at hotmail.com  Tue Jul  2 18:16:44 2002
From: smarsh at hotmail.com (scott)
Date: Tue, 02 Jul 2002 22:16:44 GMT
Subject: Is Python growing?
References:   <3D1D3D34.6080001@hotmail.com> 
Message-ID: <3D22263A.8090007@hotmail.com>

Gerhard H?ring wrote:
> Am Sat, 29 Jun 2002 04:53:23 GMT schrieben Sie:
> 
>>Gerhard H?ring wrote:
>>
>>>Mark McEahern wrote:
>>>
>>>
>>>>[...] What's so
>>>>beautiful about Python is that all I had to do was fire up the
>>>
>>interactive
>>
>>>>interpreter and do this to remind myself of what map does:
>>>>
>>>>
>>>>>>>print map.__doc__
>>>>>>
>>>
>>>help(map) in 2.2.
>>
>>Or 2.1.1.
> 
> 
> No. Of course, for anything more recent than 2.2.0, yes.
> 
> Gerhard

You are mistaken Gerhard. 2.1.1 (Activestate on NT4) is demonstrated below:

bash-2.02$ python
ActivePython 2.1.1, build 212 (ActiveState)
Python 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
 >>> help(map)
Help on built-in function map:

map(...)
     map(function, sequence[, sequence, ...]) -> list

     Return a list of the results of applying the function to the items of
     the argument sequence(s).  If more than one sequence is given, the
     function is called with an argument list consisting of the 
corresponding
     item of each sequence, substituting None for missing values when 
not all
     sequences have the same length.  If the function is None, return a 
list of
     the items of the sequence (or a list of tuples if more than one 
sequence).

 >>> print map.__doc__
map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of

-- 
Colorless green ideas sleep furiously.
      Chomsky



From CousinStanley at HotMail.com  Thu Jul 11 15:53:01 2002
From: CousinStanley at HotMail.com (Cousin Stanley)
Date: Thu, 11 Jul 2002 12:53:01 -0700
Subject: pyCard_turtleTimes
Message-ID: 

I think I need to go to the 'puter store ...

Yesterday I ran the PythonCard turtle samples 
and became quite disgusted with the results of 100,000 iterations
on my modest machine after reading comments in the  hopalong  sample 
pertaining to a machine with a bit more punch ... 

    # 500,000 iterations takes approximately 15 seconds 
    # on my AMD 1.2GHz Windows 2000 box
    # with a GeForce 2 video card, so an older machine 
    # is  LIKELY   to take much longer ... 

It did ... 
    15 minutes ... compared to 15 seconds 
    for 1/5 the number of iterations ...
    
I'd be interested to know how other  machines/platforms  compare 
for the ones that take the longest here ... 

    ChaosScript2and3 ..... 1306    ~22 min
    hopalong ......................  893    ~15 min
    madness ...................... 2771    ~46 min

Cousin Stanley

------------------------------------------------------

Hardware 

  Compaq Presario 5304
    Processor ... CyrixInstead 686MX 250 MHz
    Memory ...... 192 MB
    Video ........... On-board 

Software

  Win98  1st Ed
  Python 2.2.1

PythonCard ... Samples ... turtle

    Sample ....................... Seconds 

    3Turtles ..................... 214
    4bugs ............................  33
    automata ..................... 213
    bytedesign ................... 112
    ChaosScript1 ................  66
    ChaosScript1Direct ......  29
    ChaosScriptFastest ......  22
    ChaosScript2and3 ..... 1306    ~22 min
    coordinates ....................    3
    distance .........................    0.4
    generalPlot ...................   86
    HelloTurtle ...................    0.17
    hilbert ...........................   36
    hopalong ......................  893    ~15 min
    kochCurves ..................   14
    madness ...................... 2771    ~46 min
    originalbytedesign ......  113
    pentests ........................   21
    raceturtles ...................   82
    spingon .........................    2.75
    sun ...............................  113
    toitles ...........................   50
    trees ...........................  400  
    TurtleScript ..............  182
    TurtleScript2 ............   39
    TurtleScriptFirst ......    3.7



From wjdandreta at worldnet.att.net  Tue Jul 30 14:22:30 2002
From: wjdandreta at worldnet.att.net (Bill Dandreta)
Date: Tue, 30 Jul 2002 18:22:30 GMT
Subject: Using += in a loop
References:  
Message-ID: <3d46d722.18669034@netnews.worldnet.att.net>

Hi Alex,

On Sat, 27 Jul 2002 20:42:03 GMT, Alex Martelli 
wrote:

>As a nice plus, it's also *WAY, WAY* faster.  A loop with += takes
>O(N squared) time, joiner.join takes O(N) time, where N is the
>size of the input.  Don't use loops of += on strings except in
>really short, trivial cases -- prepare a list and join it at the
>end, or use a cStringIO instance x and call x.write, etc, etc.

I am using the following code structure in some very long (10's of
thousands of iterations) loops.

Is there a more efficient way that doesn't use +=?

Would s5 = '%s,"%s"' % (s5,x[1]) be better?

t = ()
s5 = ''
for i in range(0,5):
  q = breaks[brk][i]
  x = mkup(cost*q,list*q)
  if x[0]: t+=(x[0]/q,)
  else: t+=(0,)
  if x[1]: s5+=',"'+x[1]+'"'
  else: s5+=',"-"'
t += (0,0)
s5 += ',"-","-"'

Bill


From b.maryniuk at forbis.lt  Thu Jul 25 08:51:09 2002
From: b.maryniuk at forbis.lt (Bo M. Maryniuck)
Date: Thu, 25 Jul 2002 14:51:09 +0200
Subject: how to count lines in a file ?
In-Reply-To: 
References:   
Message-ID: <200207251451.09586.b.maryniuk@forbis.lt>

On Thursday 25 July 2002 13:27, Jonathan Hogg wrote:
> As noted earlier in the thread, files don't take part in gc. This is
> because they don't (at least for the moment) hold references to other
> objects. Generally only container objects (lists, dictionaries, tuples,
> instances, classes, etc.) take part in gc and show up in the gc statistics.

Therefore code:
----------8<------------
>>> a = open('file')
>>> a.close()
>>> del a
----------8<------------

...and just...
----------8<------------
>>> open('file')

----------8<------------

..."make" different garbage in the memory and second one provides more "crap"?

-- 
Sincerely yours, Bogdan M. Maryniuck

linux: the choice of a GNU generation
(ksh at cis.ufl.edu put this on Tshirts in '93)




From emile at fcfw.fenx.com  Mon Jul  1 15:29:08 2002
From: emile at fcfw.fenx.com (Emile van Sebille)
Date: 1 Jul 2002 14:29:08 -0500
Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul  1)
Message-ID: 

QOTW:  "So not only is the language incredibly expressive, clear, and
pragmatic, but it provides tools for exploration that make it easy to
focus on what works.  Those tools allow you to expand your working
subset of the language slowly over time as needed."
    -- Mark McEahern, on comp.lang.python 6/28/02
    http://groups.google.com/groups?selm=mailman.1025267736.21565.python-list at python.org


    Uwe Mayer looks for a way for a class to create a class instead
    of an instance.
        http://groups.google.com/groups?threadm=3D16E465.F0D2509E at ifib.uni-karlsruhe.de
    
    Oleg Broytmann announces mimedecode.py version 1.1.4, a program
    to decode MIME messages that allows, for example,  one to put
    mail messages into an archive, make HTML indices, and run a
    search indexer by converting messages to text in one character
    set and skipping binary attachments.
        http://groups.google.com/groups?selm=mailman.1024912231.9257.python-list at python.org
    
    Drew Csillag a mainly bugfix release of SkunkWeb 3.2.3
        http://groups.google.com/groups?selm=mailman.1025107715.1032.python-list at python.org
    
    Hans Nowak puzzles over how getattr can work in the class, but
    not directly, and Greg Ewing supplies the answer.
        http://groups.google.com/groups?threadm=3D180042.6000902 at earthlink.net
    
    Mark Hammond replies to questions of properly unloading
    multithreaded COM servers
        http://groups.google.com/groups?threadm=3D1A7A9A.4050208 at skippinet.com.au
    
    John Hunter asks for hints on getting to the base roots of words,
    and gets pointers to two python solutions...
        http://groups.google.com/groups?threadm=m24rfn88jp.fsf at mother.paradise.lost
    
    Russel E. Owen wants to support extrospection by converting FK5,
    ICRS, Galactic, Apparent Geocentric and Apparent Topocentric coordinates
        http://groups.google.com/groups?threadm=rowen-CE3C0F.13020226062002 at nntp1.u.washington.edu
    
    Dr. Gary Herron searches for a winnt-ish equivalent of os.setuid
        http://groups.google.com/groups?threadm=mailman.1025028033.22480.python-list at python.org
    
    The search is on for getting DCOracle2 to function properly for
    stand alone python on a W2K machine with python2.1.3 and Zope 2.5.1
    where ZOracleDA under Zope works fine.
        http://groups.google.com/groups?threadm=talon34-C09E81.19332125062002 at netnews.attbi.com
    
    Ian McMeans asks for someone to give an example of a problem that is
    solved with metaclasses, which would be difficult or impossible to
    solve with inheritance...
        http://groups.google.com/groups?threadm=ghTS8.58749$mh.1826422 at news1.telusplanet.net
    
    Here're two techniques to install Pyrex on windows.  Pyrex lets you
    write code that mixes Python and C data types any way you want, and
    compiles it into a C extension for Python.
        http://groups.google.com/groups?threadm=3d1749d3.19107439 at news1.news.adelphia.net
    
    If you have enough slots, it's easy to fall through the cracks...
        http://groups.google.com/groups?threadm=mailman.1025089474.17780.python-list at python.org
    
    Christopher Saunter want to build Pythoniac: a hardware processor that
    directly executes Python bytecode.
        http://groups.google.com/groups?threadm=afc52t$2pj$1 at sirius.dur.ac.uk
    
    Fran?ois Pinard announces a new release of Pymacs, which allows
    Emacs users to extend Emacs using Python, where they might have
    traditionally used Emacs LISP.
        http://groups.google.com/groups?selm=mailman.1025049814.27896.python-list at python.org
    
    Rimon Barr releases SPYCE - Server Python Pages Version 1.1.8, a
    drop-in Apache plugin that supports simple and efficient Python-based
    dynamic HTML scripting.
        http://groups.google.com/groups?selm=mailman.1025155654.6600.python-list at python.org
    
    Bengt Richter spawns an interesting thread by asking "if you were
    hoping for an improvement over current practice [of web templating],
    which do you consider to be the tool(s) to beat, and what would the
    killer improvement(s) be?"
        http://groups.google.com/groups?threadm=af2gh6$2c2$0 at 216.39.172.122
    
    Mark McEahern posts a first draft tutorial on metaclasses, in a record
    of his experiences trying out aspect-oriented programming (AOP) in
    Python, which holds the promise that you should ideally write your
    classes in complete ignorance of the aspects that you want to plug
    in later.
        http://groups.google.com/groups?selm=mailman.1025278420.26105.python-list at python.org
    
    Anton Vredegoor releases a rubiks cube simulation for visual python.
        http://groups.google.com/groups?selm=afkrn2$obb$1 at news.hccnet.nl
    
    Christian Tismer says 'EuroPython was just -- great!', and posts a link
    to slides from his Stackless talk.
        http://groups.google.com/groups?selm=mailman.1025372865.19860.python-list at python.org
    
    
========================================================================

Everything you want is probably one or two clicks away in these pages:

    Python.org's Python Language Website is the traditional
    center of Pythonia
        http://www.python.org
    Notice especially the master FAQ
        http://www.python.org/doc/FAQ.html

    PythonWare complements the digest you're reading with the
    daily python url
         http://www.pythonware.com/daily  
    Mygale is a news-gathering webcrawler that specializes in (new)
    World-Wide Web articles related to Python.
	 http://www.awaretek.com/nowak/mygale.html 
    While cosmetically similar, Mygale and the Daily Python-URL
    are utterly different in their technologies and generally in
    their results.

    comp.lang.python.announce announces new Python software.  Be
    sure to scan this newly-revitalized newsgroup at least weekly.
        http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

    Michael Hudson continued Andrew Kuchling's marvelous tradition
    of summarizing action on the python-dev mailing list once every
    other week, into July 2001.  Any volunteers to re-start this
    valuable series?
        http://starship.python.net/crew/mwh/summaries/
        http://www.amk.ca/python/dev

    The Vaults of Parnassus ambitiously collect Python resources
        http://www.vex.net/~x/parnassus/   

    Much of Python's real work takes place on Special-Interest Group
    mailing lists
        http://www.python.org/sigs/

    The Python Software Foundation has replaced the Python Consortium
    as an independent nexus of activity
        http://www.python.org/psf/

    Cetus does much of the same
	http://www.cetus-links.org/oo_python.html

    Python FAQTS
        http://python.faqts.com/

    The old Python "To-Do List" now lives principally in a
    SourceForge reincarnation.
	http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse
	http://python.sourceforge.net/peps/pep-0042.html
     
    The online Python Journal is posted at pythonjournal.cognizor.com.
    editor at pythonjournal.com and editor at pythonjournal.cognizor.com
    welcome submission of material that helps people's understanding
    of Python use, and offer Web presentation of your work.

    *Py: the Journal of the Python Language*
        http://www.pyzine.com

    Links2Go is a new semi-automated link collection; it's impressive
    what AI can generate
        http://www.links2go.com/search?search=python

    Tenth International Python Conference 
        http://www.python10.org            

    Archive probing tricks of the trade:
        http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100
        http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.*

Previous - (U)se the (R)esource, (L)uke! - messages are listed here:
  http://www.ddj.com/topics/pythonurl/         
  http://purl.org/thecliff/python/url.html (dormant)
or
  http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python


Suggestions/corrections for next week's posting are always welcome.
[http://www.egroups.com/list/python-url-leads/ is hibernating.  Just
e-mail us ideas directly.]

To receive a new issue of this posting in e-mail each Monday morning
(approximately), ask  to subscribe.  Mention
"Python-URL!".


-- The Python-URL! Team--

Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and
sponsor the "Python-URL!" project.
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://starbase.neosoft.com/~claird/home.html


From emile at fenx.com  Sat Jul  6 12:49:48 2002
From: emile at fenx.com (Emile van Sebille)
Date: Sat, 06 Jul 2002 16:49:48 GMT
Subject: Understanding properties
References: 
Message-ID: 

"Graham Ashton"  wrote in message
news:pan.2002.07.06.16.27.21.228231.28052 at effectif.com...
> I clearly don't get it. I just tried a simple test:
>
> class MyObject:

try:

class MyObject(object):

--

Emile van Sebille
emile at fenx.com

---------



From mwarden22 at hotmail.com  Fri Jul 12 16:10:00 2002
From: mwarden22 at hotmail.com (nealj)
Date: 12 Jul 2002 13:10:00 -0700
Subject: Debugging Embedded Python
References: 
Message-ID: 

Check out Hap www.sourceforge.net/projects/hapdebugger - it is very
close to what you need and I'll be posting an update in the next few
days that will make it even easier to use it to debug embedded python
scripts.

mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote in message news:...
> We've got a (win32) C++ program that has an embedded python interpreter 
> that runs a bunch of scripts. We've been asked to enable it's users to run 
> the python scripts under a debugger, allowing the users to put in 
> breakpoints, examine/alter values etc.
> 
> Now the C++ program basically does the following...
> 
> - Initialises some C++ stuff
> - loads in the python DLL
> - initialises some python stuff
> - starts a long complicated bunch of processing that bounces between 
> python and C++
> 
> One way to get the python running under a debugger is to tweak the system 
> so that the C++ executable becomes a C++ DLL that can be loaded as a 
> python extension. Then it's just a case of having a tiny python script 
> that
> 
> - initialises some python stuff
> - loads in the C++ DLL
> - initialises some C++ stuff
> - starts a long complicated bunch of processing that bounces between 
> python and C++
> 
> It's then a simple matter of running the above python script in a python 
> debugger.
> 
> While this would work, it has two irritants
> 1) the work required to change the C++ executable into a python extension 
> DLL
> 2) the python debugger will (presumably) be built to use release-build 
> DLL's. Which means that any build where we can run the whole thing under a 
> python debugger (i.e. a release build) can't easily be run under a C++ 
> debugger and vice versa.
> 
> Are there any win32-compatible python debuggers out there which can
> a) do an "Attach to process" and debug any executable that's using the 
> python DLL
> and/or
> b) have source or pre-built debug builds available?
> 
> Many TIA


From me at michaelbauers.com  Tue Jul  9 23:39:05 2002
From: me at michaelbauers.com (Michael Bauers)
Date: Tue, 9 Jul 2002 22:39:05 -0500
Subject: Lunar lander example
Message-ID: 

I wrote a simple Lunar Lander program in Python, and I thought it
demonstrated a lot of basic Python features.

I was wondering if there was a place for example programs for new Pythoneers
to look at?






From mikeb at mitre.org  Fri Jul 12 14:31:55 2002
From: mikeb at mitre.org (Mike Brenner)
Date: Fri, 12 Jul 2002 14:31:55 -0400
Subject: COCOMO - appropriate for languages like Python
Message-ID: <3D2F209B.C65E74B3@mitre.org>

Mike > ... is it possibly a bug in Internet Explorer or comp.lang.python? ...

Andreae > ... None of the above ... see what your post looks like ... google ...

http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&safe=off&selm=mailman.1026318496.22583.python-list%40python.org

Thank you very much for this reference. I reported this terrible display bug to GOOGLE. Here is the post with hard carriage returns.

--------------------------------

[REPOSTED WITH HARD CARRIAGE RETURNS]


> From a management standpoint ... strive to hire the very best people 
> and to break projects into moderate sized, easily handled chunks.
> From a schedule estimation standpoint, LOC 
> (however you choose to count them) appears to be a pretty good 
> estimator to use for a fixed staff and fixed project sizes. 
> How the prediction varies as you change staff or project sizes is
> something you'll have to measure or guess at yourself.


IMO, the following measurements apply to most Python efforts 
more than lines of code:

        - Most software has achieved the status of "maintenance" 
rather than "development". Thus, millions of lines of code might 
require, say, a one-line change. Some of those one-line changes 
take a month of research and testing, while others take a few seconds. 
The lines of code changed (and the lines of code in the whole project) 
only correlate to new code, not to code under maintenance.

        - Software Maintenance time primarily increases as backlog 
increases (e.g. programmer overtime which the company intends to not 
pay, other work awaiting action, inadequate functional testing, 
deferred regression testing which detects reappearance of prior bugs, 
incomplete impact analysis of past and present changes, 
incorrect documentation, and the age of parallel development
paths). For example, parallel development paths that last more 
than a few days (fractured baselines) start to take on lives 
of their own, and become more expensive to merge into a single 
"golden" baseline as they age.  

        - Software Maintenance time decreases as the technology 
factor (the part of the COCOMO model that applies to software 
maintenance rather than to new development) increase. Thus, 
to save time, get better tools for: comparison, visualization,
cross-referencing, text pattern search, automatic testing, slicing, 
and other tools to assist in determining the impact of changes. 
Also, use an interpreted language like Python with good debugging, 
tracing, and other tools. Measure the number of seconds it takes 
to find the line of code that caused a problem (something that 
gets harder when you add wxWindows, threads, servlets, graphics, 
COM objects, operating system calls, web services, soaps,
and additional levels of interpretation to the software). 
        
        - Software Maintenance time increases with the number 
of data integrity problems possible in the languages and tools 
used (coding bugs, data design flaws, data flaws, network design 
flaws, rifts, and sabotage). Coding bugs include off-by-one errors, 
aliasing, global variables, hanging pointers, out-of-range errors, 
missing actions, extra actions, global typing violations (even in 
interpreted languages), and memory leakage. Data design flaws include
failure to trigger an action (e.g. busting a referential 
integrity constraint), implementing a many-to-many relationship 
inefficiently, mismatching keys, inappropriate level of normalization,
performing a wrong action, or incomplete design. Data flaws include 
conversion round-offs or other loss of precision, incorrect origin 
or units of measure, inaccurate numbers, inappropriate null 
data, obsolete data, out of range errors, two-digit years, and 
local type mismatches. Network design flaws include bandwidth 
too low (errors or noise), bottlenecks, inadequate error detection,
notification, correction, speed mismatch, missing packets, 
power failures, race conditions such as deadlocks, 
insufficient redundancy, loss of resolution, simultaneous modifications, 
and slow response time. 
Rifts are another name for the backlogs above which were called 
out separately because of their large effect on time. Sabotage 
(tampering with the data, trojan horses, viruses, authentication 
where none is needed, weak authentication where authentication 
is actually needed, worms, failure of CM to preserve the parts, 
management destroying service requests which were completed or 
cancelling to remove the evidence, and lack of backups). 

        - Software Maintenance time positively correlates to 
the amount of time that maintenance organization last maintained 
that type of code (after subtracting the time it takes to open up 
the configuration, which relates to how long since a project 
last opened that code).

        - Software Maintenance time negatively correlates with 
syntactic standards. For example, a rule like "indent each level 
3 spaces" slows down software maintenance and development in 
two ways. First, humans (like programmers, reviewers, and 
quality assurance auditors) will tend to spend time enforcing and 
carrying out such a rule, because of their ego-needs for 
control; people should only impose such a rule by providing 
a tool to enforce the rule automatically. Second, such rules 
limit the visualization possibilities -- for example, someone 
might discover a bug more quickly by viewing the code 
with several different indentations.

        - When management decides to use a metric, and the 
programmers become aware of that metric, then the programmers 
take whatever action required to make that metric reach 100%. 
For example, if management pays the programmers by the line 
of code, the lines of code will increase.

        - When management (personal, government, corporate, 
academic) requests non-applicable metrics like lines of code 
(a metric which makes sense only at development time) or 
McCabe Cyclomatic Complexity (a metric which makes sense only 
at testing time since it counts test paths and dings programmers 
for good stuff like nested SWITCH/CASE statements and BREAKs) 
to describe maintenance effort, consider get rid of that entire level of management.

        - Without an accepted standard definition of 
"lines of code", one cannot know whether to count every line 
in every IMPORTed module, or just those the INVOKED lines, 
or just those lines that do the invoking. For example, do 
we count every line in the python runtime module STRING.PY or 
just the lines in STRING.PY that our modules call, or just 
the lines in our module that call STRING.PY? These different 
counting strategies differ by orders of magnitude. 

Mike Brenner





From tim at bladerman.com  Sun Jul 28 15:23:51 2002
From: tim at bladerman.com (Tim Gahnström /Bladerman)
Date: Sun, 28 Jul 2002 19:23:51 GMT
Subject: Guide to the python interp. source?
References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com><_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com>  
Message-ID: 

"Andreas Kostyrka" 
>Am Sam, 2002-07-27 um 21.15 schrieb Tim Gahnstr?m /Bladerman:
>> This is not the comon way, I know that but I am inclined to say that it
is
>> "undoubtley" more intuitive. Remember that this is a language for
complete
>> beginners with no programming experience.
>Well, and how does it work with recursion? Just wondering. ;)

Hmm... havn't thought about it yet but I dont think it will be a problem. It
might be a mess to explain but I don't really think it will be a problem.
def f(x):
    x=x+2
    if x>100:
        return
    f(x)

The result of x is obvious but it will probably be a mess to make that
happen in the interpreter. I don't know, it will ofcourse depend on how / if
I implement this CBR feature.

>[And recursion is such a fundamental pattern in programming, that you
>want your students to understand it quickly. Actually it's also needed
>for the maths.]

Deffinitley agree. Recursion will be possible and it will work in a
straightforward way. Recursion is still possible in languages that support
CBR so I am sure that it is possible.

>> Ofcourse this is just the simplest case possible and ther vill be issues
>> further down the way but I intend to handle them later. right now I am
>> getting to no the python interpreter, and its interaction with C and the
IDE
>> Maybe I have gotten the names wrong imutable/mutable/CBR/CBV etc etc. But
my
>> intentions are as outlined above.
>Well, I've got the strong impression, that you have not yet the feeling
>for the Python datamodel. While it can probably somehow done, you are in
>myriad of troubles. (And I suspect that you will not be able to work it
>out in a semester. Perhaps even two semesters ;) )

Well I am getting more and more aquainted to agree with you the more I hear
about the Python datamodel.
I didn't study that before I choose Python, I must admit that. I knew the
syntax and that it was a really good and extendable interpreter. That is why
I choose it.

>And consider the fact, that you would have to completely rewrite the
>python library also, because basically every piece of python code relies
>upon call by value.

That, ofcourse is impossible and won't happen. Still, if this is such an
utterly impossible feature I will just dropp it. That is not a fundamental
thing.

>> After I had written this mail actually thought that I had to add this on
>> top:
>> CBR is not a die hard feature that I must have if it gets a whole lot of
>> work to fix it. But I would apreciate anny suggestions on how to make it
>> with a limited amount of work.

>Forget it :)
Cough, cough... may I throw out a wild guess... you are on the higher end of
the age scale right? ;-)

>Write some small (~1000KLOC) applications in Python, do some data
>manipulation stuff, and then reconsider your project ;)

Actually that is what I am doing... I am writing a small application with
datamanipulation stuf :-)

>> That I understand but hadn't thought about it. What might be possible now
>> when you point it out like that is that maybe I can use the current
Python
>> model untill I come to a return statement in a function. At that time I
>> reattatch the internal object to the pointer/refference/name that I sent
in.
>> Clearly neither this is well thought over. I will come there in a month
or
>> so.
>Well, it's usually a bad idea to try fixing a language, that you do not
>know well enough. Especially if you don't know the basic "idioms".

Some people chose easy master thesises that they wouldn't show to a future
employer even with a gun to there head. (they usuallu succed)
Some people chose a project that have the possibillity of being awesome if
it is finished as the utopi is in there head.
I guess I am in the second group and might fail with a splash and I migh
also succed by an inch and end up haiting my project, but atleast I tried .

>>And I strongly question the fact if passing values by reference is
>>easier to understand than assigning values. (which call by value is)

Well that is your opinion not mine.

ask a complete novice what he think this peace of code will do

#Here is the program
x=3
inc(x)
print x

#Bellow is al the function deffinitions
def inc(x):
    x= x+1

You might have to tell him about assignment but not much else for him to
understand that this program will print 4
I think it is intuituve you don't I am fine with that but I dont agree.
But on the other hand, I am not ready to work that much to get it my way.


>> I might even throw in a preprocessor that changes the usercode into
python
>> right before it is ran. That ofcourse is not a good solution but I have t
in
>> mind.
>Nope. Preprocessor would be a quite bad idea.

I am just trying to see possibilities and give ideas, maybe someone will see
a possible solution.

Imagin this:
A whole lot of talented programmers is presented with an idea about creating
a language that works like Python except that it is uses CBR. Al of them
agree that it is impossible without rewriting the whole interpreter AND the
Python library.

To me can only mean two things.
1. It really is impossible
2. We have the programmers to blame for the "dot com" crash. :-) (means they
are narrow minded)

I don't know wich one is correct and I guess I am not (yet) ready to bet my
Master thesis on the second one.

Tim




From chandan_mathur at hotmail.com  Wed Jul  3 16:17:42 2002
From: chandan_mathur at hotmail.com (chandan mathur)
Date: Wed, 3 Jul 2002 16:17:42 -0400
Subject: win32com and internet explorer
Message-ID: <3d235b64$1@post.usenet.com>

**** Post for FREE via your newsreader at post.usenet.com ****

Hi...,
    I am new to python/programming.. I was trying to read and save a page
from the internet using win32com and internet explorer..., easy rite? well..
not workin for me.. this is what i have so far

import win32com.client,time
# Get the browser object
ie = win32com.client.DispatchEx("InternetExplorer.Application")
# open a page
ie.Visible = 1
ie.Navigate("http://www.google.com")
time.sleep(5) #to make sure the page has finished loading
print ie.Document.toString()


result: -- [object] ...I was expecting to see the html junk displayed.

help appreciated.... thank you
chandan





-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 *** Usenet.com - The #1 Usenet Newsgroup Service on The Planet! ***
                      http://www.usenet.com
Unlimited Download - 19 Seperate Servers - 90,000 groups - Uncensored
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


From pinard at iro.umontreal.ca  Sat Jul 20 16:26:37 2002
From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard)
Date: 20 Jul 2002 16:26:37 -0400
Subject: unloading imported modules
In-Reply-To: 
References: 
	
Message-ID: 

[Alex Martelli]

> xeon wrote:

> > Is it possible in python intepreter to unload imported modules? or are

> No.

Hello, Alex.

Suppose we reload, and reload and reload the same module, are the previous
copies freed from memory?  If not, then, sigh, I guess, this is it...
Otherwise, if I remove the module from sys.modules and from the module
namespace having imported it, what would keep it in memory?

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




From peter at engcorp.com  Sun Jul 21 13:22:30 2002
From: peter at engcorp.com (Peter Hansen)
Date: Sun, 21 Jul 2002 13:22:30 -0400
Subject: Scope of instantiated class
References: <3D3ACCA6.7030002@lmco.com> <3D3ACE59.1060004@lmco.com>
Message-ID: <3D3AEDD6.78B39D70@engcorp.com>

Jeff Layton wrote:
> 
> >    If I instantiate a class in a function,
> > leave the function via a return and then
> > go back to the same function, will the
> > instantiation of the class still be there
> > or is it local to the function so it is
> > "destroyed"? (Does this make any sense?)
> >
> Oops, as a follow-up the function the instantiates
> the class and the routine it returns to are in
> different modules.

Where the functions are is irrelevant in this case.

When you create an object ("instantiate a class") you
must bind it to a name ("assign it to a variable").  If
the name you use is local to the function, then when
the function exits the binding is removed and the object,
if no other names are by now bound to it, is destroyed.

If you have a particular goal in mind (as opposed to
just curiosity about the mysterious inner workings of
programming languages), then if you describe it someone
will be able to explain how to accomplish what you want
in a different way.

-Peter


From whisper at oz.net  Thu Jul 25 23:03:56 2002
From: whisper at oz.net (David LeBlanc)
Date: Thu, 25 Jul 2002 20:03:56 -0700
Subject: DOS-Shell hangs up, python/Tkinter
In-Reply-To: 
Message-ID: 

Last visible CVS activity for anygui is/was today!

David LeBlanc
Seattle, WA USA 



> I've been patiently waiting for AnyGUI in the hopes that it would
> provide the ability to use a working graphics library under each
> environment. Unfortunately, I haven't seen any progress posted
> on AnyGUI in a while. That may mean they just aren't keeping
> their projected next release date updated (I hope).
> 
> John Roth
> >
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



From gmcm at hypernet.com  Fri Jul  5 10:10:34 2002
From: gmcm at hypernet.com (Gordon McMillan)
Date: 05 Jul 2002 14:10:34 GMT
Subject: Metakit help
References: 
Message-ID: 

David LeBlanc wrote:

> Working more with Metakit, i'm finding that there is some information
> not in the documentation, so I have a few questions:
> 
> I think I figured out how to create a nested schema, but not how to
> insert or append a row with nested data - how is that done?

Insert / append the containing row. It will have an
empty subview, and row.subview is a view. Insert / append
as needed.
 
> How do you get a view from a pre-existing database?

storage.view('viewname')

> Can you modify the schema of an existing database? How?

Do another storage.getas(...). Adjusting the type
of a column is (almost) like dropping and adding
the column.
 
> How do you put a pickle in a database? 

Put it in as a B (binary string).
 
> Are the various attributes of
> that pickle accessable while it's in metakit storage? How about the
> pickled object's attributes?

To Metakit, it's just a binary string.

> How would you enforce a uniqueness constraint on a key field?

Depends. If it's a what in RDBMS-land you'd call a 
primary key, I'd make it the first column and 
make sure it's sorted (easy when the view's empty :-)).

if isnew:
  v = db.getas('myview[key:S,...]')
else:
  v = db.view('myview')
v = v.ordered(1)

Now v.find(...) will use a binary search.

If your key is just a unique key, I'd build an
index view '_myview[key:S,ndx:I]'.

Either way, it's pretty easy to wrap the 
view so the constraint is enforced. (These
aren't new-style types yet, so you can't
subclass.)

If your view exists:
 v = storage.view('myview')
 v[:] = v.sort()
 storage.commit()

And join the metakit list:
 http://www.equi4.com/mailman/listinfo/metakit

-- Gordon
http://www.mcmillan-inc.com/


From gerhard.haering at gmx.de  Fri Jul 19 07:43:44 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: Fri, 19 Jul 2002 13:43:44 +0200
Subject: Calling Fredrik Lundh, (dare i ask) Guido, all other Guru's, could this be a bug?
In-Reply-To: 
References:   
Message-ID: <20020719114344.GA1464@lilith.my-fqdn.de>

* G. Willoughby  [2002-07-19 12:31 +0100]:
> as you can see no third party imports are made. Another question, how
> do i go about getting a debug version of python to run this in on
> WinXP?

You compile it yourself using Visual C++.

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




From shalehperry at attbi.com  Wed Jul 31 18:28:37 2002
From: shalehperry at attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 31 Jul 2002 15:28:37 -0700 (PDT)
Subject: re.search question
In-Reply-To: <3mmgkucn8ga1klgrchkmfifkig9i1r4sse@4ax.com>
Message-ID: 

On 31-Jul-2002 michaelian ennis wrote:
> How would I tell python to give me all the text in a string which
> falls between  the first instance of "!" alone on a line and the first
> instance of "end" alone on a line inclusively?
> 
> 
> lines=
> junk 
> !
> important stuff
> end
> more junk
> 
> 
> to 
> 
> cleaned_lines=
> !
> important stuff
> end
> 

Why use a regex here?

NOT_READY, READY = (0, 1)

print '!'
for line in input:
    if line == '!':
        state = READY
    elif line == 'end':
        state = NOT_READY:
    elif state == READY:
        print line
print 'end'




From gumuz at looze.net  Fri Jul  5 04:48:41 2002
From: gumuz at looze.net (Guyon Morée)
Date: Fri, 5 Jul 2002 10:48:41 +0200
Subject: sending a file through sockets
References: 
Message-ID: <3d255c71$0$221$4d4ebb8e@news.nl.uu.net>

wow, really thanx a lot!

this is good stuff, i have to figure out this struct module but i can handle
i guess :)

thanx,
Guyon

 wrote in message
news:mailman.1025817368.17823.python-list at python.org...
> On Thu, 4 Jul 2002, Guyon Mor?e wrote:
>
> > so the trick is to convert a file to a string representation right?
> > i still have to try it out, but maybe you can confirm my way of thinking
> > here :)
>
> Um... you *could* do that, but it wouldn't actually help at all. The
> contents of the file already are in a string representation because Python
> strings can contain anything, including binary characters. The easiest way
> to send a file is to simply read the data from the file and send it out
> the socket, but to send the length of the file first so the receiving end
> knows if and when it got the whole thing. If you need too much more
> functionality than this it might be easier to just use one of the standard
> file transfer protocols, e.g. FTP. Anyway, here's some sample code, but if
> you're not already familiar with sockets then you should spend a little
> time experimenting with them.
>
> The sending side listens for incoming connections and sends out the file.
> The receiving side connects to the "server" and writes the file to disk.
>
> Common code:
> import struct
> PORT = 5555
> FILENAME = 'foo.bin'
> HDR = '!I'
> HDR_SZ = struct.calcsize(HDR)
>
> Sending side:
> import os
> from socket import *
> s = socket(AF_INET,SOCK_STREAM)
> s.bind(('',PORT))
> s.listen(1)
> while 1:
>   q,v = s.accept()
>   q.sendall(struct.pack(HDR, os.path.getsize(FILENAME)))
>   f = open(FILENAME,'rb')
>   while 1:
>     data = f.read(4096)
>     if not data: break
>     q.sendall(data)
>   q.close()
>
> Receiving side:
> from socket import *
> f = open(FILENAME, 'wb')
> s = socket(AF_INET, SOCK_STREAM)
> s.connect(('', PORT))
> size = s.recv(HDR_SZ)
> size = struct.unpack(HDR, size)
> while size > 0:
>   data = s.recv(4096)
>   if not data: break
>   size -= len(data)
>   f.write(data)
> s.close()
>
> Note that if you're not using Python 2.2 or later there isn't a sendall
> method in socket objects so the sending side should check the return value
> from send() to see how many bytes were actually written out and resend any
> that didn't make it.
>
> -Dave
>
>
>




From gerhard.haering at gmx.de  Tue Jul 16 12:31:14 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 16 Jul 2002 16:31:14 GMT
Subject: Making code faster
References: <3d3445f9_7@news.newsgroups.com>
Message-ID: 

JB wrote in comp.lang.python:
> How can I make the following code faster? I open a (text) 
> file and read the lines in the file. The lines of the file 
> have the form
> 
> [,]
> 
> After the lines have been loaded, I set up a new list via 
> the function tmp1.
> 
>     i = -1
>     print 'loading file'
>     def tmp1(s):
>       global i
>       i += 1
>       return QSimpleViewItem(i,self.sv.lv.newColor,eval(s))
> 
>     try:
>       myfile = open(filename)
>     except:
>       pass
>     else:
>       tmp = myfile.readlines()
>       print 'lines loaded'
>       datei.close()
>       self.sv.lv.rows = map(tmp1,tmp)
>       self.sv.lv.visible = range(len(self.sv.lv.rows))
>       print 'lines decoded',self.sv.lv.rows[0].col[0]
> 
> Any ideas? It is astonishing that loading the lines from 
> external storage takes much less time than the mapping 
> itself!

The line "self.sv.lv.rows = map(tmp1,tmp)" makes some call into an
external library (PyQt?) that's likely taking up the whole time.

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))


From rjones at ekit-inc.com  Wed Jul 24 19:36:55 2002
From: rjones at ekit-inc.com (Richard Jones)
Date: Thu, 25 Jul 2002 09:36:55 +1000
Subject: how to count lines in a file ?
In-Reply-To: 
References: 
Message-ID: <200207250936.56045.rjones@ekit-inc.com>

On Thu, 25 Jul 2002 8:31 am, Delaney, Timothy wrote:
> > From: Bo M. Maryniuck [mailto:b.maryniuk at forbis.lt]
> >
> > print len(open('/etc/passwd').readlines())
>
> There is currently discussion on python-dev of the file object possibly
> becoming collectable by GC (and hence not going away immediately the last
> reference you know about disappears).
>
> Whilst is it *extremely* unlikely that this would be allowed (due to the
> preponderance of broken code such as the above) it does point out that such
> code is indeed broken.

Sorry, I'm coming in to this thread halfway through, but I need to know why 
that code is broken? Is it the "open('/etc/passwd').readlines()"? That's a 
very common pattern, as you note, because people think it is perfectly 
legitemate. What about it is broken? Why isn't it pointed out more often that 
it _is_ broken?


   Richard




From boud at valdyas.org  Sat Jul  6 17:21:55 2002
From: boud at valdyas.org (Boudewijn Rempt)
Date: Sat, 06 Jul 2002 23:21:55 +0200
Subject: Python version of STL multimap?
References: 
Message-ID: <3d27636a$0$12309$e4fe514c@dreader4.news.xs4all.nl>

Roy Smith wrote:

> I often want to create a dictionary whose values are lists of items with
> the same key.  I've got variations on:
> 
>    if dict.has_key (key):
>       dict[key].append (value)
>    else:
>       dict[key] = [value]
> 
> sprinkled throughout my code in many places.  Sometimes I write it as:
> 
>    try:
>       dict[key].append (value)
>    except KeyError:
>       dict[key] = [value]
> 
<...>
> So, the question is, is there a standard way in Python to do multimaps,
> or should I just continue to roll my own with one of the above idioms
> whenever I need one?

Isn't this exactly what Alex Martelli posted the other day:

dict.setdefault(key, []).append(value)

in answer to the thread about sorting a dictionary by its value?

-- 
Boudewijn Rempt | http://www.valdyas.org


From shalehperry at attbi.com  Wed Jul  3 16:34:20 2002
From: shalehperry at attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 03 Jul 2002 13:34:20 -0700 (PDT)
Subject: Patterns and all that new fangled stuff ...
In-Reply-To: <3D235E7E.1090100@mxm.dk>
Message-ID: 

> 
> So I think there are many of advantages, but it's just that it gets so 
> verbose
> 

good, easy to maintain code is often longer than we would like.




From tdelaney at avaya.com  Wed Jul  3 19:50:25 2002
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Thu, 4 Jul 2002 09:50:25 +1000 
Subject: "my brain hurts" or is isinstance broken?
Message-ID: 

> From: robert_kuzelj at yahoo.com [mailto:robert_kuzelj at yahoo.com]
> > 
> > if isinstance(source, type) or
> >    isinstance(source, types.ClassType):
> >        return source()
> >    else:
> >        return copy.copy( source )
>
> that is exactly what i did. but i dont like this solution cause
> as i told before it is rather implicit than explicit.

What is implicit about it? It is explicitly saying "if it's a new-style
class or an old-style class".

Perhaps the following would suit you better ...

def isoldstyleclass (obj):
    import types
    return isinstance(obj, types.ClassType)

def isnewstyleclass (obj):
    return isinstance(obj, type)

def isclass (obj):
    return isnewstyleclass(obj) or isoldstyleclass(obj)

if isclass(source):
    return source()
else:
    return copy.copy(source)

Tim Delaney




From spam at ob_scure.dk  Sat Jul  6 18:35:20 2002
From: spam at ob_scure.dk (Thomas Jensen)
Date: Sun, 07 Jul 2002 00:35:20 +0200
Subject: Given PID, make sure a process is running on Unix?
References: 
Message-ID: <3D2770A8.7070900@ob_scure.dk>

VanL wrote:
> Hello,
> 
> I am trying to get write a python script that  on Unix reads a PID from 
> a file and, if that process is still running, exits.  If the process is 
> not running, the process would be started.
> 
> I have everything written except the part that makes sure the process is 
> running.  I have poked through the os module, but I can only seem to 
> find information about the current process or child processes, not just 
> some arbitrary process.

If your system has a 'proc' device, you could do something like this:
     os.path.isdir('/proc/%d' % pid)
Most Unix flavours have a proc device AFAIK.

-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)



From rs at onsitetech.com  Mon Jul  8 17:42:28 2002
From: rs at onsitetech.com (Robb Shecter)
Date: 08 Jul 2002 21:42:28 GMT
Subject: Why self?
References:  <080720021650379803%pecora@anvil.nrl.navy.mil>
Message-ID: <3D2A06F9.7050805@onsitetech.com>

Louis M. Pecora wrote:
> Here's a stab.  
> 
> (1) All self variables have to be initialized in __init__.  That's just
> good practice anyway.  They are labeled with self in __init__ otherwise
> they are local.  
> 
> (2) There can be no name conflicts between local and self variables. 
> Also good practice within an object.
> 

Good ideas.  Or just do nothing: make self optional as in Java, and the 
  innermost scope is searched first if no self is given.  I've done 
years of Java programming, and have never had issues with instance vs. 
local variables.  It just really doesn't happen in practice because of 
the differences in naming and usage of variables.

How does Ruby handle this?

I think that any of these ideas are good.

Robb



From skip at pobox.com  Fri Jul 26 07:44:34 2002
From: skip at pobox.com (Skip Montanaro)
Date: Fri, 26 Jul 2002 06:44:34 -0500
Subject: discriminating ascii, unicode and raw byte strings in XML-RPC
Message-ID: <15681.13858.94044.283242@12-248-11-90.client.attbi.com>

Just kind of curious, how are people distinguishing between ASCII strings,
Unicode strings, and raw byte strings (strings used to transport arbitrary
data, like database blobs or images) when transporting them via XML-RPC?
Its  tag is only supposed to transport ASCII strings.  Base 64
encoding Unicode and raw strings of bytes works, but doesn't distinguish
between the two at the other end.  Prepend "r" or "u" perhaps (no XML-RPC
changes required, but requires a protocol between the client and server)?
Have people established conventions or extended XML-RPC to support Unicode
directly?  I should mention that I do have to interoperate with Perl, so
Python-only hacks (like pickle.dumps) aren't ideal solutions.

Thx,

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html



From aleax at aleax.it  Fri Jul 12 13:17:39 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 12 Jul 2002 17:17:39 GMT
Subject: redirecting stdio
References: <3D2EFC2B.1080504@peardrop.demon.co.uk>
Message-ID: 

Keith S. wrote:

> Hi,
> 
> I'm rather new to Python and am trying to embed it into a C++
> application. The documentation gives the basics of this, but
> I want Python's output (stdio/stderr) to be redirected to C++
> functions (to display the text in a message window).
> 
> Can anyone point me to a description or example of how this is
> done?

Here's a little thing I had laying around -- not quite what
you ask, but it might help.  It's a small demonstrative C
extension which does just about the bare minimum needed to
show how to redirect Python's stdout from C when imported.


#include 
#include 

static PyObject*
redi(PyObject* self, PyObject* args)
{
    char* thestring;
    if(!PyArg_ParseTuple(args, "s", &thestring))
        return 0;
    printf("Print string: (%s)\n", thestring);
    return Py_BuildValue("");
}

static PyMethodDef rediMethods[] = {
    {"redi", redi, METH_VARARGS, "Redirect ouput"},
    {0}
};

void
initredi(void)
{
    PyObject* sys_module = PyImport_ImportModule("sys");
    PyObject* redi_module = Py_InitModule("redi", rediMethods);
    PyObject* redi_dict = PyModule_GetDict(redi_module);
    PyObject* aux;
    char * code = "class Sout:\n"
                  "    def write(self, s): redi(s)\n"
                  "sout = Sout()\n";

    aux = PyRun_String(code, Py_file_input, redi_dict, redi_dict);
    Py_XDECREF(aux);
    aux = PyObject_GetAttrString(redi_module, "sout");
    PyObject_SetAttrString(sys_module, "stdout", aux);
    Py_XDECREF(aux);
}


Alex



From gerhard.haering at gmx.de  Tue Jul  9 10:03:23 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=)
Date: Tue, 9 Jul 2002 16:03:23 +0200
Subject: Problems building a Python module
In-Reply-To: <3D2AE97B.4020908@ilt.fhg.de>
References: <3D2AE97B.4020908@ilt.fhg.de>
Message-ID: <20020709140323.GA17617@lilith.my-fqdn.de>

* Rolf Wester  [2002-07-09 15:47 +0200]:
> Hi,
> 
> I want to build a Python module from C-files. I made the wrapper file
> using swig. During linking I get the following message:
> [...]
> /usr/lib/python2.2/config/libpython2.2.a(thread.o): In function 
> `PyThread_start_new_thread':
> thread.o(.text+0x7f): undefined reference to `pthread_sigmask'
> [...]

This wants to tell you that you should really use distutils to compile
your Python extension module instead.

> I link against following libraries:
> 
> -lpython2.2 -lm -ldl
> 
> Can someone tell me what other libraries I have to link against? And
> what means:

ldd /path/to/your/python will tell you.

> posixmodule.o(.text+0x3614): the use of `tmpnam_r' is dangerous, better 
> use `mkstemp'

This is a warning from the linker that's emitted as soon as certain
functions are linked against. As long as you don't use these functions
in the tmpfile module, you can safely ignore this warning.

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




From johnboik at sbcglobal.net  Tue Jul  2 01:30:13 2002
From: johnboik at sbcglobal.net (John Boik)
Date: Tue, 02 Jul 2002 05:30:13 GMT
Subject: newbie question on getting Blt to work with Pmw on Windows
Message-ID: 

Hello. I have installed Python for windows (XP). I have also installed Pmw
and got it to work. I have also downloaded and used the self-installer for
Blt for windows. However, when I run the Pmw demos, it will not let me run
the Blt-associated ones. The Pmw demo program tells me that Blt is not
installed. Probably there is something I need to do to tell Python that it
is there, but I do not know what that would be.  Do I need to use an import
statement in Python? And if so, what is the name of the modeule I am
importing (what file is it so I can find the path)?

Thanks. John





From cliechti at gmx.net  Sun Jul  7 18:25:24 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 8 Jul 2002 00:25:24 +0200
Subject: make cvs pserver/ssh(2) connection with python
References: <20020707.223646.680466996.4043@tu-bs.de>  <20020708.000822.654887343.4043@tu-bs.de>
Message-ID: 

"Marc"  wrote in
news:20020708.000822.654887343.4043 at tu-bs.de: 
> Im Artikel  schrieb "Chris
> Liechti" :
>> "Marc"  wrote in
>> news:20020707.223646.680466996.4043 at tu-bs.de:
>>> I am searching a way to make a cvs pserver or/and a ssh(protocol
>>> Version 2) connection with python under Linux/Unix. I've tried to
>>> control the cvs pserver
>>> connection by a python frontend which uses the normal cvs binary,
>>> but it won't work without using the 'normal console interaction' for
>>> input (maintainly the cvs login).
>>> I can get the inputstream, but I can't write correctly to the
>>> outputstream. I get the password query, but the answer fails.
>>> Perhaps someone have experience in writing a frontend for
>>> interactive programms under Linux/Unix and can help me.
>> 
>> do you use popen? something like that:
>>>>> i,o = os.popen2("cat - >tmp")
>>>>> i.write("hello")
>>>>> i.close()
>>>>> o.close()
> At this time I use this:
> os.popen(command)
> 
> The Problem isn't the reading and writing input-/outputstream, it's
> the timing(I think).

well it is when you're using only popen. it supports either reading or 
writing but not both at the same time.

> I make a 'cvs login' then I'll be asked for the
> cvs password and the answer of this question fails. Perhaps I've to
> use the tty or ptty module of python, but I don't know how. I'm
> searching a way to handle his problem. I hope someone had similar
> problem (i.e. by writing a frontend for ftp,telnet,ssh,... (for
> interactive applications)). 
> 
> the Python version is 1.5.2 (I think! It is a pool with 20(?)
> workstations, different OS (Linux and Solaris, different versions)).
> I think popen2 is available python-version>2 and if it exists another
> way (as upgrade Pyhon) to solve the problem I'll use that way.

i think the popen2 module is available in 1.5.2 and it provides popen2 (it 
should, given the module name ;-) however the semantics are slightly 
different.

> Insteat, if you know a way to solve my problem by useing popen2 please
> give me a short example.

basicaly you need to read until you find the prompt on the o stream and 
then write the passwd on the i stream.
(untested:)

i,o = os.popen2('cvs -d%s login' % CVSROOT)
while 1:
  if o.readline().strip().endswith('password:'):
    	i.write("secret\n")
    	break
print o.read()    	#read the reset of the output
i.close()
o.close()

in the telnetlib you'll find more andvanced functions like read_until() 
etc. which you could probably adapt for your problem if readline isn't good 
enough.

chris

-- 
Chris 



From mnations at airmail.net  Tue Jul 23 18:56:53 2002
From: mnations at airmail.net (Marc)
Date: 23 Jul 2002 15:56:53 -0700
Subject: Need a better way to pause a thread
Message-ID: <4378fa6f.0207231456.3057babe@posting.google.com>

Hi:

I am trying to find the best way to pause one of my threads. In most
areas where the modules are small or in loops, I have an event created
that I just event.wait() for. This works very well. However, in
another area of code I have a long series of unique commands. I want
to avoid having to place event.wait() dozens of times. I tried the
following:


def check():

    print "in check"

    globals.pause.wait()

    if globals.stop.isSet():

        globals.status.clear()

        globals.stop.clear()

    globals.master.after(100, check)
 

I was hoping that by continually checking this loop it would pause the
thread when it hit the ...pause.wait() command. However, it just seems
to hang. I guess because the after() command for this function is not
sequentially tied to the rest of the code, and the rest of code keeps
going while this command gets confused.


Either way, under Windows with Python there's no way to create a
thread and just pause execution of the thread from an os level. So is
there a better way to be able to pause a long series of unique
commands without having to sprinkle holds everywhere?


Thanks ahead of time,
Marc


From fredrik at pythonware.com  Sat Jul 27 14:06:50 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sat, 27 Jul 2002 18:06:50 GMT
Subject: Python and XML help
References:  
Message-ID: <_iB09.17825$p56.5762976@newsb.telia.net>

Clark Evans wrote:

> For a simple properties list like this you could use YAML
> instead of python... it'd be alot easier.

$ more clarkbot.py

...

hitlist = ["XML", "xml", "type", "marshal", "pickle", ...]

def process_message(text):
    words = text.split()
    for word in hitlist:
        if word in words:
            break
    else:
        if random.random() < 0.98:
            return
    message = quote_relevant_parts(text)
    message = message + random.choice([
        "You want YAML",
        "Hey, use my own YAML standard instead",
        "This reminds me of YAML",
        "Almost sounds like YAML",
        ...
        "Two YAML were walking across the street",
        ]
    )
    post(message + yaml_footer)

...




From ndi at imm.uran.ru  Tue Jul 23 23:50:17 2002
From: ndi at imm.uran.ru (D.I.Neudachin)
Date: Wed, 24 Jul 2002 03:50:17 +0000 (UTC)
Subject: Emacs-21 & Python2.1
Message-ID: 

Help! 

New pdb from Python2.1 d'nt work in gud.el(universal dubug enviroment)
of GNU emacs-21. :(

-- 
Neudachin Denis Il'ich
Junior research
Department of Applied Problems
Institute of Mathematics                      Phone: (7-3432) 742631
and Mechanics,Urals Branch                           (7-3432) 748414
of Russian Academy of Sciences                Fax:   (7-3432) 742581
16, S.Kovalevskaya St.                E-mail: ndi at imm.uran.ru
Ekaterinburg 620219                           
Russia				      ICQ: 768635




From Gabe.Newcomb at noetix.com  Wed Jul 24 19:08:47 2002
From: Gabe.Newcomb at noetix.com (Gabe Newcomb)
Date: Wed, 24 Jul 2002 16:08:47 -0700
Subject: Tkinter Grid manager question
Message-ID: <0C7CA8D8DF75494EB09AB6016990107FF0F895@NOXMAIL.noetixad.com>

This has gotten me the answers I need (thanks), but for one thing: I
can't seem to get sticky to position a widget within a cell. I'm
wondering what I could be doing wrong. Try this little example:

root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f1.grid(row=0,column=0,sticky=N+E+W+S)
f1.grid(row=0,column=1,sticky=N+E+W+S)
l1 = Label(f1,text='L1 here',relief=SUNKEN)
l2 = Label(f2,text='L2 here',relief=SUNKEN)
l1.grid(sticky=W)
l2.grid(sticky=E)


I would expect it to create a root window with two frames next to each
other (it does that). In each frame, the label should appear, and the
one on the left should be all the way to the left of the frame, while
the one in the right frame should be all the way to the right of the
frame.

In practice, however, both labels end up on the opposite sides of the
frames (the left one is on the right side of the frame, and vice-versa.

Am I doing something wrong here, or do I need to approach this a
different way?

FYI:
If I try fixing the size of the frames and then using
frame.grid_propagate(0) for each frame, the labels end up in the center
of each frame.


Thanks,
Gabe


-----Original Message-----
From: jepler at unpythonic.net [mailto:jepler at unpythonic.net]
Sent: Tuesday, July 23, 2002 7:56 PM
To: Gabe Newcomb
Cc: python-list at python.org
Subject: Re: Tkinter Grid manager question


By default, a frame ignores the width= and height= it is given, and
instead
calculates the amount of space needed by the widgets it manages via grid
or
pack.

You can tell the grid manager that it should not behave in this way, and
should instead take the width= and height= you select for the frame and
parcel that space out to the managed widgets:
    f1.grid_propagate(0)
now, f1 will be 900x100

Similarly, if you "grid" things into f1_1 you need to run
    f1_1.grid_propagate(0)
if you "pack" things into f1_1, you need to run
    f1_1.pack_propagate(0)

If you want to make sure the rows are the same width, you need to set
the weight (again on the master):
    for row in range(4):
	f1.grid_rowconfigure(row, weight=1)
now, f1_1, f1_2, f1_3, and f1_4 will be configured to get equal shares
of
the height of f1.

If you still don't get a layout exactly 225 pixels wide, this is
probably
because of the borderwidth.  For instance, if you configure a frame
width a
thick border and then make another frame inside, the inner frame is
smaller (shifting to tcl since that's easier to do):
    %frame .f -bd 25 -relief raised -width 100 -height 100
    frame .f.f
    pack prop .f 0
    pack .f
    pack .f.f -expand 1 -fill both
    wm geo .
    winfo geo .f
    winfo geo .f.f
. and .f have geometries of 100x100, while .f.f is only 50x50, due to
the
border of .f.

Geometry management in Tk is a somewhat complex issue, and you have to
expect to play with the options before you get what you want.

Usually you will want to have as few intervening levels of frames as
possible.

Jeff



From donn at u.washington.edu  Mon Jul 29 13:19:48 2002
From: donn at u.washington.edu (Donn Cave)
Date: 29 Jul 2002 17:19:48 GMT
Subject: Python design failures (was Re: Let's Talk About Lambda Functions!)
References:  <3d455445_9@news.newsgroups.com>  <3d457011_1@news.newsgroups.com>
Message-ID: 

Quoth JB :
| Aahz wrote:
|> In article <3d455445_9 at news.newsgroups.com>, JB 
|>  wrote:
|>|Tim Peters wrote:
|>|>
|>|> two language features are mentioned as being "failed
|>|> experiments" that only compatibility prevents throwing
|>|> away:
|>|> 
|>|>     `back ticks`
|>|>     lambda
|>|
|>| (1) Why are back ticks a failure? I love them.
|> 
|> If you're using backticks frequently, you're probably not
|> programming
|> Pythonically.  There's already repr() to produce the same
|> result as backticks, and backticks have the problem that
|> in many fonts they're nearly indistinguishable from single
|> quotes.
|
| I do not understand this. I use __repr__ *and* backticks. 
| For example
|
| class AnyClass:
|   defr __repr__(self):
|     ...
|
| a = AnyClass()
| myfile.write(`a`)
|
| I use this construction rather frequently. What is wrong 
| with it?

What he said - "... nearly indistinguishable from single quotes."
Density at the expense of legibility is why I'd say it doesn't really
fit with my ideal of Python programming style.

On the other hand, list comprehensions certainly would fall in that
category too, and there's no question that I'm out of touch with the
prevailing sentiment on comp.lang.python about things like this.
And the distribution library appears to use `` rather liberally -
probably more than repr().  Obviously this doesn't make it any
better (is Perl more wonderful for all the people who use it, or
Visual Basic, C++, etc?)  But we can't pretend there's a consensus.

	Donn Cave, donn at u.washington.edu


From max at alcyone.com  Tue Jul  9 20:36:53 2002
From: max at alcyone.com (Erik Max Francis)
Date: Tue, 09 Jul 2002 17:36:53 -0700
Subject: A better self
References: 
Message-ID: <3D2B81A5.E8274781@alcyone.com>

David LeBlanc wrote:

> Except, of course, "self" is not the name of the first argument, it's
> merely
> the identifier most often used for the first argument.

Sure, my suggestion was not meant to give any preference to `self' as
the Magical Self Argument*; the `.attribute' notation would simply be a
shortcut for `(first variable in argument list).attribute'.

Again, I'm not particularly fond of the proposal, although it certainly
is better than introducing some new punctuation pattern (I've seen
`@attribute' suggested for the same thing), but it doesn't seem right to
me to pretend that . is a legal name and then pretend like it isn't.

> I'm not sure what you meant by ".attribute should have an extra
> space...".

Thinko; I meant to say an extra _dot_, although the example which
followed probably got my point across anyway:  If `.' is the self
argument, then its attribute must be referenced by `..attribute', not
`.attribute'.

. 

* Perversity of choosing to name it something other than `self' aside, I
seem to recall some official Python documentation somewhere suggesting
that using a name other than `self' is not supported behavior (i.e., a
warning that at some future time its name of `self' might be enforced),
but a few furtive searches from time to time have failed to turn up what
I might have been remembering.  Does that ring any bells with anybody?

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ See the son in your bad day / Smell the flowers in the valley
\__/ Chante Moore
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.


From walter at livinglogic.de  Wed Jul 24 06:40:21 2002
From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=)
Date: Wed, 24 Jul 2002 12:40:21 +0200
Subject: convert from utf-7 encoded text to normal text?
References: 
Message-ID: <3D3E8415.4070701@livinglogic.de>

Suresh Ananthan wrote:

> Hello List,
> 
>     I'm working on C/C++ platform.  I have recieved mail in the
> following format. There's utf-7(or utf-8) encoded text.
> 
> ------=_NextPart_000_0057_01C2323C.D9CAFA60
> Content-Transfer-Encoding: 7bit
> Content-Type: text/plain;
> 	charset="utf-7"
> 
> test+AEA-qa21.com+ADs- dig+AEA-qa21.com
> test+AEA-qa21.com+ADs- dig+AEA-qa21.com
>  
> 
>    I hope that this is a unicode format.  I need to convert (or)
> decode this
> string.  What algorithm i should use?  (or) any other sample program
> available for convert this unicode string to normal text?????How to
> decode
> this text to get normal chars? I'm newbie and tried some API / C RTL
> functions, but did not get correct result, so detailed answer will be
> very
> helpfull. Please...

Python 2.2.1 (#1, Apr 10 2002, 19:08:12)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> "test+AEA-qa21.com+ADs- dig+AEA-qa21.com".decode("utf-7")
u'test at qa21.com; dig at qa21.com'

And if "I'm working on C/C++ platform" means you need the
algorithms callable from C, then use the function
PyUnicode_DecodeUTF7().

If "I'm working on C/C++ platform" means your program has nothing
to do with Python, this is really the wrong newsgroup, but you
could take a look at PyUnicode_DecodeUTF7() in the Python source,
(in the file Objects/unicodeobject.c, viewable online at
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/unicodeobject.c?rev=HEAD&content-type=text/vnd.viewcvs-markup
) and copy the algorithm from there.

Hope that helps,
    Walter D?rwald




From johan at weknowthewayout.com  Wed Jul 10 03:37:02 2002
From: johan at weknowthewayout.com (Johan Holst Nielsen)
Date: Wed, 10 Jul 2002 09:37:02 +0200
Subject: PDf creating with Python? Howto?
Message-ID: <3D2BE41E.3040508@weknowthewayout.com>

Hi people,

Im right now beginning a project where I have to make a generator to PDF 
files. It includes images, and fonts (thats not are embedded in the 
Adobe PDF specification).

It have to be used for Offset printing, so all images must have a 
resolution about 304 dpi.

Anyone know tutorials or libraries in Python that can help me with this 
project?

Regards,

Johan Holst Nielsen



From keilj_33 at yahoo.com  Sat Jul 27 09:44:56 2002
From: keilj_33 at yahoo.com (Jeffrey Keil)
Date: 27 Jul 2002 06:44:56 -0700
Subject: Python script that writes to an Excel file
Message-ID: <67f6bbe5.0207270544.696f6076@posting.google.com>

Greetings:

I'd like to have a Python script open a text file, process the data in
the text file and then write a report to an Excel file. I'm not sure
how I would write to an Excel file from a Python script. Is there any
books that would give me details on doing this?

Thanks,
Jeff Keil


From fredrik at pythonware.com  Wed Jul 24 20:39:04 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Thu, 25 Jul 2002 00:39:04 GMT
Subject: Callable modules?
References: <7xznwk1hfy.fsf@ruckus.brouhaha.com>  <7xr8hwnu3s.fsf@ruckus.brouhaha.com>   <7xn0sgpte7.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin wrote:

> But that's another special trick, more hair to remember.  Why not just
> do the obvious thing and make modules work the same way as other objects?

you are confused.

have you tried calling other objects?

if you have, you might have noticed that very few
python objects allow you to call them.  some raise
an attribute error, but most objects raise a type
error.  module objects too.






From aleax at aleax.it  Sun Jul 21 10:11:40 2002
From: aleax at aleax.it (Alex Martelli)
Date: Sun, 21 Jul 2002 16:11:40 +0200
Subject: Funny behaviour of MySQLdb
In-Reply-To: <15674.7752.888722.873627@localhost.localdomain>
References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> <20020720173325.51C943E6AB@cali-2.pobox.com> <15674.7752.888722.873627@localhost.localdomain>
Message-ID: 

On Sunday 21 July 2002 04:36 am, Skip Montanaro wrote:
>     Alex> If MySQLdb.threadsafety >= 2, and there are no errors in your
>     Alex> implementation, you're supposed to be safe.
>
> I just checked the docs for MySQLdb.threadsafety (version 0.9.2).  It's
> value in that version is 1.  About this the docs says:

By itself I believe threadsafety == 1 does not imply that different threads
can use the same connection over time.  However, the paragraph you
quote does appear to say that MySQLdb, in particular, can do that -- not
quite a threadsafety of 2, but more than just 1 per se would imply.


>     Alex> If each "chat" is complicated enough and can't easily be
>     Alex> encapsulated as a callable, you may even have some advantage wrt
>     Alex> the architecture I'd consider even safer -- five dedicated
>     Alex> threads, one per connection, all waiting for work requests on a
>     Alex> single queue and returning results on a separate queue per
>     Alex> requestor thread: you're saving a few resources by having 5 fewer
>     Alex> threads and many fewer Queues around.
>
> Each time I .get() a connection from the pool, I do tend to execute
> multiple SQL statements.

Yes, but, if that could be reasonably encapsulated in a callable, you could
just pass the (callable, returnqueue) pair as the work request.  I guess it
does happen that the program's structure is just not easily cut up into
functions, methods, callable instances, etc, but I've never met such cases.

> Using a fixed numbers of threads associated with
> each connection is a bit more complicated, especially since I already wind
> up with a thread per request courtesy of SocketServer.ThreadingMixin.  Why
> waste it? 

Without even having seen your code I suspect your highest gain in
scalability would come from a slightly modified ThreadingMixin that
reuses worker-threads from a thread pool rather than churning out
one thread per request.  I've not specifically tried that, but in other
similar situations in the past (in other languages) moving to a fixed
pool with a reasonable number of threads was always an important
scalability win.


>     Alex> But the moment problems should start appearing, good luck.
>
> Well understood.  I was really quite surprised that I had very few problems
> as I added locks to the shared objects when I converted the server from
> single to multiple threads.

It's nice to get a GOOD surprise once in a while, we're so used to BAD
ones:-).


Alex




From j-jinkins at usa.net  Mon Jul  8 17:46:17 2002
From: j-jinkins at usa.net (Jim Jinkins)
Date: Mon, 08 Jul 2002 21:46:17 GMT
Subject: List assignment, unexpected result
References: 
Message-ID: <3D2A088A.7050200@usa.net>

Steve Coates wrote:

>A friend of mine recently sent me some code and asked if I could
>predict what it would do. I guessed wrong. Code as follows:-
>
>grid = [['.'] * 4 ] * 4
>grid [0][0] = '0'
>grid [1][1] = '1'
>grid [2][2] = '2'
>grid [3][3] = '3'
>for i in grid: print i
>
>The intent is clear i.e. fill the diagonal with 0,1,2,3; but the
>result is somewhat different. Could anyone explain why this doesn't
>work as expected - and even better, come up with an assignment for
>'grid' that would work. My only suggestion was an explicit
>[['.','.','.','.'],['.','.','.','.'],etc. but it gets a bit cumbersome
>for large grids.
>
>Thanks
>Steve
>  
>
The array  rows are  4 references to a single list of 4 columns.  Try 
something like this:

a = [x[:] for x in [['*']*4][:] for y in range(4)]
for ii in range(4): a[ii][ii] = ii

    Jim




From gareth.evans at wideawake.co.uk  Wed Jul 17 06:31:34 2002
From: gareth.evans at wideawake.co.uk (gareth evans)
Date: 17 Jul 2002 03:31:34 -0700
Subject: NetUnjoinDomain causes a memory error
Message-ID: <3a8be3e4.0207170231.2e05a9c9@posting.google.com>

I've written a c extension for python to use some netapi32 functions
i found that I get a memory error when calling NetUnjoin domain
test.py=

#!/bin/python
import netapi
import time

NETSETUP_JOIN_DOMAIN=0x00000001
NETSETUP_ACCT_CREATE=0x00000002
NETSETUP_ACCT_DELETE=0x00000004
NETSETUP_WIN9X_UPGRADE=0x00000010
NETSETUP_DOMAIN_JOIN_IF_JOINED=0x00000020
NETSETUP_JOIN_UNSECURE=0x00000040
NETSETUP_INSTALL_INVOCATION=0x00040000

UNAME="Administrator"
PWORD="w0rf"

def test_func():
	
	print "in test script"
	print "in net unjoin domain"
	status=netapi.NetUnjoinDomain(None,UNAME,PWORD,NETSETUP_ACCT_DELETE)
	print status
	return

test_func()


$ ./test.py
in test script
in net unjoin domain



The instruction at "0x40100000" referenced memory at "0x40100000". The
memory could not be "read".

this seems to be happening during the garbage collection after the
function exits ive no idea why it also only seems to occur if you make
any refrence to the py_lpPassword after the PyArg_ParseTuple if i use
a diffrent variable for the password e.g. the comented py_lpPassword1
it works fine. I'm really stuck.
any ideas? 

//-  NetGetDCName - netapi32
//NetGetJoinInformation - netapi32
//NetJoinDomain - netapi32
//NetUnjoinDomain - netapi32
//SetComputerName - kernel32
#pragma comment(lib, "NETAPI32.LIB")
#ifndef UNICODE
#define UNICODE
#endif
#include 
#include 
#include "Python.h"
#include "TConvert.h"
#include "netapi_py.h"
#include "LMJOIN.h"

static PyObject *NetapiError;


PyObject *Net_GetJoinInformation(PyObject *self, PyObject *args)
{	
	LPWSTR lpServer;
	LPWSTR lpNameBuffer;
	CHAR* py_NameBuffer;
	LPSTR py_Server;
	PNETSETUP_JOIN_STATUS BufferType;
	int status;
	BufferType=new NETSETUP_JOIN_STATUS;
	if (!PyArg_ParseTuple(args, "z",&py_Server))
		return NULL;
	if (py_Server!=NULL)
	{
		_towchar c1(py_Server);
		lpServer=c1;
		status=NetGetJoinInformation(lpServer, &lpNameBuffer, BufferType);	
	}
	else status=NetGetJoinInformation(NULL, &lpNameBuffer, BufferType);
	if (status==0)
	{
		_tochar c2(lpNameBuffer);
		py_NameBuffer=c2;
		delete lpServer;
		return Py_BuildValue("isi",0,py_NameBuffer,*BufferType);
	}
	else{
		return Py_BuildValue("isi",1,"NetGetJoinInformation Failed",status);
	}
}

PyObject *Net_JoinDomain(PyObject *self, PyObject *args)
{
	NET_API_STATUS status;
	LPCWSTR lpServer;
	LPCWSTR lpDomain;
	LPCWSTR lpAccountOU;
	LPCWSTR lpAccount;
	LPCWSTR lpPassword;
	CHAR* py_lpServer;
	CHAR* py_lpDomain;
	CHAR* py_lpAccountOU;
	CHAR* py_lpAccount;
	CHAR* py_lpPassword;
	DWORD fJoinOptions;
	//printf("%",NETSETUP_JOIN_DOMAIN);
	if (!PyArg_ParseTuple(args, "zszzzd",&py_lpServer, &py_lpDomain,
&py_lpAccountOU,
		&py_lpAccount, &py_lpPassword, &fJoinOptions))
			return NULL;
	if (py_lpServer!=NULL)
	{
		_towchar c1(py_lpServer);
		lpServer=c1;
	}
	else lpServer=NULL;
	_towchar c2(py_lpDomain);
	lpDomain=c2;

	if (py_lpAccountOU!=NULL)
	{
		_towchar c3(py_lpAccountOU);
		lpAccountOU=c3;
	}
	else lpAccountOU=NULL;

	if (py_lpAccount!=NULL)
	{
		_towchar c4(py_lpAccount);
		lpAccount=c4;
	}
	else lpAccount=NULL;

	if (py_lpPassword!=NULL)
	{
		_towchar c5(py_lpPassword);
		lpPassword=c5;
	}
	else lpPassword=NULL;

	status=NetJoinDomain(lpServer, lpDomain, lpAccountOU, lpAccount,
lpPassword, fJoinOptions);
	return Py_BuildValue("i",status);
}

PyObject *Net_UnjoinDomain(PyObject *self, PyObject *args)
{
	NET_API_STATUS status;
	LPCWSTR lpServer;
	LPCWSTR lpAccount;
	LPCWSTR lpPassword;
	DWORD   fUjoinOptions;
	CHAR* py_lpServer;
	CHAR* py_lpAccount;
	//CHAR* py_lpPassword1="Tiger";
	CHAR* py_lpPassword;
	if (!PyArg_ParseTuple(args, "zzzd",&py_lpServer, &py_lpAccount,
&py_lpPassword, &fUjoinOptions))
		return NULL;
	if (py_lpServer!=NULL)
	{
		_towchar c1(py_lpServer);
		lpServer=c1;
	}
	else lpServer=NULL;
	
	if (py_lpAccount!=NULL)
	{
		
		_towchar c2(py_lpAccount);
		lpAccount=c2;
	}
	else lpAccount=NULL;
	//printf("%s\n",py_lpPassword);
	if(py_lpPassword!=NULL)
	{
		_towchar c9((LPCSTR)py_lpPassword);
		lpPassword=(LPCWSTR)c9;
		printf("\n");
	}
	//lpPassword=NULL;
	else lpPassword=NULL;
	//delete py_lpPassword;
	status=NetUnjoinDomain(lpServer, lpAccount, lpPassword,
fUjoinOptions);
	//printf ("here");
	return Py_BuildValue("i",status);
}

PyObject *Net_GetDCName(PyObject *self, PyObject *args)
{
	NET_API_STATUS status;
	LPCWSTR servername;  
	LPCWSTR domainname;
//	LPCWSTR result;
	LPBYTE *bufptr;      
	CHAR* py_servername;
	CHAR* py_domainname;
//	CHAR* py_result;
	int len();
	if (!PyArg_ParseTuple(args, "zz",&py_servername, &py_domainname))
		return NULL;
		
	if (py_servername!=NULL)
	{
		_towchar c1(py_servername);
		servername=c1;
	}

	else servername=NULL;

	if (py_domainname!=NULL)
	{
		_towchar c2(py_domainname);
		domainname=c2;
	}
	else domainname=NULL;

	status=NetGetDCName(servername, domainname, bufptr);
	return Py_BuildValue("is",status,bufptr);
}

PyObject *Set_ComputerName(PyObject *self, PyObject *args)
{
	BOOL status;
	LPCTSTR lpComputerName;
	CHAR* py_lpComputerName;
	DWORD err_code;

	if (!PyArg_ParseTuple(args, "s",&py_lpComputerName))
		return NULL;

	_towchar c1(py_lpComputerName);
	lpComputerName=c1;

	status=SetComputerName(lpComputerName );
	if (status!=0)//worked
	{
		return Py_BuildValue("is",0,"WORKED");
	}
	else
	{
	err_code=GetLastError();
	return Py_BuildValue("ds",err_code,"FAILED");
	}
}

static PyMethodDef NetMethods[] = {
    {"NetGetJoinInformation",  Net_GetJoinInformation, METH_VARARGS},
	{"NetJoinDomain", Net_JoinDomain, METH_VARARGS},
	{"NetUnjoinDomain", Net_UnjoinDomain, METH_VARARGS},
	{"NetGetDCName",Net_GetDCName,METH_VARARGS},
	{"SetComputerName",Set_ComputerName,METH_VARARGS},
    {NULL, NULL}      
};

#ifdef MS_WIN32
__declspec(dllexport)
#endif

DL_EXPORT(void)
initnetapi(void){
	PyObject *m, *d;

	m=Py_InitModule("netapi",NetMethods);
	d = PyModule_GetDict(m);
	NetapiError = PyErr_NewException("netapi.error",NULL,NULL);
	PyDict_SetItemString(d,"error",NetapiError);
}


From aahz at pythoncraft.com  Mon Jul  1 19:02:15 2002
From: aahz at pythoncraft.com (Aahz)
Date: 1 Jul 2002 19:02:15 -0400
Subject: New style classes as exceptions (Was: exception handing)
References:   
Message-ID: 

In article ,
holger krekel   wrote:
>Aahz wrote:
>> In article ,
>> Denis S. Otkidach  wrote:
>>>
>>>New style classes don't work when used as exceptions.  I guess it
>>>should be considered as a bug.
>> 
>> Nope, that's just the way it currently works.
>
>what's your definition of a bug, then?

Something that doesn't work as designed.  Guido specifically decided to
wait on making new-style classes work with exceptions -- there are still
too many applications using *string* exceptions.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From gerhard at bigfoot.de  Fri Jul  5 00:33:40 2002
From: gerhard at bigfoot.de (Gerhard =?unknown-8bit?Q?H=E4ring?=)
Date: Fri, 5 Jul 2002 06:33:40 +0200
Subject: Newbie - Stand alone python
In-Reply-To: 
References: 
Message-ID: <20020705043339.GA5580@gargamel.hqd-internal>

* abc  [2002-07-05 12:21 +0800]:
> Hi all, I am a newbie to Python and I want to ask you guys a question.

Welcome to the club and I hope you'll like it.

> Python program is very much like Java where both need a Virture machine to
> run the program, I wonder whether Python program is able to compile into a
> .exe file instead of a .py file so that PC without the VM is also able to run
> the program. Thankz

See item 4.28 of the Python FAQ wizard:

http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.028.htp

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




From fperez528 at yahoo.com  Tue Jul  9 13:51:43 2002
From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=)
Date: Tue, 09 Jul 2002 11:51:43 -0600
Subject: Multi language software development?
References: <3D2B1E91.4070102@gmx.de>
Message-ID: 

Ingo Linkweiler wrote:

> Hi,
> 
> do you know any tools or IDEs, which allow multi-language software
> development with python? (English, German ...) I do not need this for a
> special project, it is just a gernal question.
> 
> I want....
> - GUIs supporting more than one language
> - Replace strings in existing code (list of words)
> - use multiple language strings within my source code
> 
> I have searched with google and at "Vaults of Parnassus" without finding
> something.

google(python i18n) -> hit 'I feel lucky'.

f


From sschwarzer at sschwarzer.net  Mon Jul 22 13:36:45 2002
From: sschwarzer at sschwarzer.net (Stefan Schwarzer)
Date: Mon, 22 Jul 2002 19:36:45 +0200
Subject: Scope of instantiated class
References: <3D3ACCA6.7030002@lmco.com> <3D3ACE59.1060004@lmco.com> <3D3AEDD6.78B39D70@engcorp.com>
Message-ID: <3D3C42AD.8050005@sschwarzer.net>

Hello Peter

Peter Hansen wrote:
> When you create an object ("instantiate a class") you
> must bind it to a name ("assign it to a variable").  If

What about

L = [1, [2, 3]]

? The object [2, 3] can be accessed but it doesn't have a name.

Another example is the use of lambda functions like this:

translations = { 'dos_to_unix': lambda s: s.replace('\r', ''),
                  'unix_to_dos': lambda s: s.replace('\n', '\r\n') }

Here, the lambdas can be accessed via the dictionary keys but are not bound
to a name.

Stefan



From campbells4 at ozemail.com.au  Thu Jul  4 07:25:36 2002
From: campbells4 at ozemail.com.au (Alistair Campbell)
Date: Thu, 4 Jul 2002 21:25:36 +1000
Subject: PythonWin + other GUIs = CRASH!
References: <3D232FEE.3010606@gmx.de>
Message-ID: 

Has anyone tried Komodo, the ActiveState IDE, with this? I haven't but I
have a copy which I haven't installed. I installed the ActiveState Python
version and it kept causing addressing errors in a Windows ME environment.
So, I am not too keen to give Komodo a try. I will though if it fixes the
crashing with GUI scripts.

Alistair Campbell
"Ingo Linkweiler"  wrote in message
news:3D232FEE.3010606 at gmx.de...
> Hi,
>
> when using the PythonWin IDE with other GUI-Toolkits (Qt, wxPython,
Pygame), the application crashes or freezes when running them with
"file->run".
>
> Is it possible to avoid this?
>
> Do you know other IDEs, which can be used with [Qt, wxPython, Pygame]?
>
> Ingo
>
>
>
>
>
>
>




From logiplexsoftware at earthlink.net  Tue Jul  2 19:50:57 2002
From: logiplexsoftware at earthlink.net (Cliff Wells)
Date: Tue, 2 Jul 2002 16:50:57 -0700
Subject: help using (x)inetd
In-Reply-To: 
References: 
Message-ID: <20020702165057.7516af51.logiplexsoftware@earthlink.net>

On Tue, 2 Jul 2002 19:39:22 -0400
rahvee at yaahhoo.com wrote:

> I have xinetd accepting a tcp connection on some port, and spawning a 
> process that I wrote.  
> 
> The process wants to have a conversation.  It can take input, it can 
> make output, but when it prints some output, that output gets buffered 
> by xinetd, and it is never received by the client until the process 
> closes.  My process is written in python.
> 
> How can I signal inetd to flush the buffer?


sys.stdout.flush()


-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




From martin at v.loewis.de  Thu Jul 18 02:26:16 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 18 Jul 2002 08:26:16 +0200
Subject: Installing XMLProc???
References: 
Message-ID: 

"Jim Cerra"  writes:

> How do I "install" XMLProc (Lars Marius Garshol's XML Processor)?

I recommend to install PyXML; it comes with xmlproc bundled.

Regards,
Martin


From jonathan at onegoodidea.com  Tue Jul  9 06:06:54 2002
From: jonathan at onegoodidea.com (Jonathan Hogg)
Date: Tue, 09 Jul 2002 11:06:54 +0100
Subject: making zip with list comprehensions
References: 
Message-ID: 

On 9/7/2002 10:56, in article oryW8.234$xm1.54155 at news0.telusplanet.net,
"Ian McMeans"  wrote:

> I was idly trying to replicate zip's (the function) behavior using list
> comprehensions, but I couldn't do it.
> 
> Can anyone? I came up with these, but they're ugly.
> 
>>>> [(x,y) for x in ['a','b','c'] for y in ['d','e','f'] if
> ['a','b','c'].index(x) == ['d','e','f'].index(y)]
> [('a', 'd'), ('b', 'e'), ('c', 'f')]
> 
> This is ugly because it loops far too many times =)
> 
>>>> [ (['a','b','c'][x], ['d','e','f'][x]) for x in range(3)]
> [('a', 'd'), ('b', 'e'), ('c', 'f')]
> 
> This isn't so bad. Does anyone have better suggestions?
> 
> 

Best I could come up with is:

>>> xs = [ 'a', 'b', 'c' ]
>>> ys = [ 'd', 'e', 'f' ]
>>> 
>>> [ ( x, yi.next() ) for yi in (iter(ys),) for x in xs ]
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>> 

I think the lack of a clean way of doing lockstep iteration is exactly why
'zip' was invented ;-)

-thou-shalt-not-use-for-in-list-comprehensions-to-do-let-bindings-ly y'rs,

Jonathan



From uncleenzo at hushmail.com  Thu Jul 11 12:25:19 2002
From: uncleenzo at hushmail.com (Uncle Enzo)
Date: 11 Jul 2002 09:25:19 -0700
Subject: COM server threads/unloading
References: <10d944cb.0206261529.741da082@posting.google.com>  <10d944cb.0206281302.43de821a@posting.google.com> 
Message-ID: <10d944cb.0207110825.624f986a@posting.google.com>

Thanks for your suggestions Kris, SetDaemon() did the trick!

Enzo


From claxtonr at beer.com  Fri Jul 19 22:20:10 2002
From: claxtonr at beer.com (hejduk)
Date: Fri, 19 Jul 2002 22:20:10 -0400
Subject: problem solved (i think)
References: <20020716.171155.619290071.333@beer.com>
Message-ID: <20020719.222010.492067917.565@beer.com>

In article <20020716.171155.619290071.333 at beer.com>, "hejduk"
 wrote:

> I obtain the path and then send it to the following function:
> 
> def progStart(file):
>       import thread
>       from os import system
> 
>       def progStart(file):
>           system(file)
> 
>       thread.start_new_thread(progStart, (file,))


the following is what i was looking for:

def progStart(file):
	import os
	pid = os.spawnv(os.P_NOWAIT, file, ("",))
	os.waitpid(pid, os.WNOHANG)

i had tried using spawnv sometime ago but with the P_DETACH flag, which
for some reason is not available to me.


From f.steinhaeusler at amatic.com  Fri Jul 19 04:48:00 2002
From: f.steinhaeusler at amatic.com (Franz Steinhäusler)
Date: Fri, 19 Jul 2002 10:48:00 +0200
Subject: Idle Import Error
Message-ID: 

Hello,

I'm new to Python.

I've downloaded wxpython, pil and image_view. (win98)
When I try to start image_view from or from dos prompt, everything is
fine.

But if I want to start it from the idle program, i get the following
error message:

Traceback (most recent call last):
  File "C:\Python22\Lib\site-packages\image_view\image_view.py", line
7, in ?
    import hand_tool
ImportError: No module named hand_tool

the hand_tool.py is in the same folder as image_view.py.

It seems, that the directory, from which image_view.py is started, no
other files are searched there.

I must start idle with with the setting "Aufsf?hren in" (run from) 
"C:\Python22\Lib\site-packages\image_view", then it works.

How can I accomplish, that the directory, from which the .py file is
started, will be searched for other files too?

Many thanks in advance,

-- 
Franz Steinhaeusler


From unlearned at DELETETHIS.learn2think.org  Tue Jul 30 11:24:57 2002
From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell)
Date: Tue, 30 Jul 2002 09:24:57 -0600
Subject: Check undefined variable
References: <3D46AD2E.709@img-online.de>
Message-ID: <3d46afca$1_2@hpb10302.boi.hp.com>

"Michael Grabietz"  wrote in message
news:3D46AD2E.709 at img-online.de...
> how is it possible to check whether a variable 'a' is undefined or not.
>
> e.g.:
>
> if a==NULL :                 # something like that
>      print 'a is undefined !'
>      else
>      print 'a already undefined !'

try:
    type(A)
    print 'A exists'
except NameError:
    print 'A doesn't exist'

--
Daniel Fackrell (unlearned at learn2think.org)
When we attempt the impossible, we can experience true growth.




From dig.list at telkel.net  Tue Jul 23 14:33:11 2002
From: dig.list at telkel.net (DIG)
Date: Tue, 23 Jul 2002 13:33:11 -0500
Subject: good books -- Python Essential Reference by David Beazley
In-Reply-To: ; from "John Hunter" on Tue, Jul 23, 2002 at 09:12:05AM
References:  
Message-ID: <20020723133309.A20383@lifebook>

Hi, John Hunter !

 On Tue, Jul 23, 2002 at 09:12:05AM -0500, John Hunter wrote:

> If you want a book with a long shelf life, many including myself,
> recommend Python Essential Reference by David Beazley.

I agree with that.


Best regards,

-- 
DIG (Dmitri I GOULIAEV)



From cliechti at gmx.net  Sat Jul 27 13:46:19 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 27 Jul 2002 19:46:19 +0200
Subject: distutils gcc unix
References: <3D3FFB03.9090402@ims.u-tokyo.ac.jp>  <3D4263E7.3000107@ims.u-tokyo.ac.jp>  <3D42D972.2060607@ims.u-tokyo.ac.jp>
Message-ID: 

Michiel Jan Laurens de Hoon  wrote in
news:3D42D972.2060607 at ims.u-tokyo.ac.jp: 

> Sorry ... it seems that distutils ignores the CC environment variable 
> (see below). This was done on cygwin.

there is a note somewhere in the docs that you can use --compiler=mingw32 
(which works with gcc/cygwin) the doc also says how to use the borland 
compiler.
i always have trouble to find the respecive note, but i _know_ it's 
somewhere in the docs that get installed with python. :-(

> On Unix, the CC variable was
> also ignored using setenv CC gcc, and also with set CC=gcc. Here
> distutils defaulted to the standard cc compiler. I am guessing that it
> took the compiler name from the Makefile in /lib/python2.2/config.
> Any ideas?
> Thanks a lot for your help.
> 
> --Michiel.
> 
> $ export CC=bcc32
> mdehoon at GINSENG ~/Software/Cluster
> $ echo $CC
> bcc32
> mdehoon at GINSENG ~/Software/Cluster
> $ bcc32
> Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
> mdehoon at GINSENG ~/Software/Cluster
> $ python setup.py build
> running build
> running build_py
> creating build
> creating build/lib.cygwin-1.3.12-i686-2.2
> creating build/lib.cygwin-1.3.12-i686-2.2/Pycluster
> copying Pycluster/__init__.py ->
> build/lib.cygwin-1.3.12-i686-2.2/Pycluster running build_ext
> building 'Pycluster.cluster' extension
> creating build/temp.cygwin-1.3.12-i686-2.2
> gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DUSE_DL_IMPORT 
> -Iranlib/src -I/usr/include/python2.2 -c cluster.c -o 
> build/temp.cygwin-1.3.12-i686-2.2/cluster.o
> gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DUSE_DL_IMPORT 
> -Iranlib/src -I/usr/include/python2.2 -c clustermodule.c -o 
> build/temp.cygwin-1.3.12-i686-2.2/clustermodule.o
> ... and so on
> 
> 
> Martin v. Loewis wrote:
> 
>> Michiel Jan Laurens de Hoon  writes:
>> 
>> 
>>>Thanks for your reply. I am having some difficulties setting the CC
>>>environment variable, probably due to some peculiarities of our Unix
>>>system. But if I solve that and set CC=gcc, would distutils know
>>>about it? 
>>>
>> 
>> Yes, they use the compiler identified by this variable.
>> 
>> 
>>>I would think that distutils would choose the compiler options for
>>>the regular cc compiler, but substitute gcc for CC when the actual
>>>compilation starts, thus ending up with the wrong compiler
>>>options. Or am I missing something here? Does distutils check for
>>>the CC environment variable?
>>>
>> 
>> Yes, it does. As for the options: For most purposes, the options of
>> cc and gcc are identical. In the few places where they differ,
>> distutils know about the differences.
>> 
>> Regards,
>> Martin
>> 
>> 
> 
> 



-- 
Chris 



From jocdeveloper at hotmail.com  Tue Jul 30 10:30:43 2002
From: jocdeveloper at hotmail.com (joc)
Date: Tue, 30 Jul 2002 15:30:43 +0100
Subject: wxPython and Py2exe probs
Message-ID: 

I have 2 questions regarding wxPython and Py2exe

1. When I try to compile a python script with Py2exe I get the following
warnings:-

    The following modules were not found: ( I have bunched them to be easier
to read)

    cmndlgsc, imagec, clip_dndc, windows3c, filesysc, eventsc, windows2c,
    controlsc, misc2c, controls2c, os.path, stattoolc, windowsc, mdic, gdic,
    sizersc, printfwc, streamsc, framesc, miscc

The exe file runs OK but another script where I try the same just quits out.
Both
scripts run fine with python. (the other script generates more warnings
because it
is a lot bigger).

Is my version of python (2.2 on win XP) not set up correctly?
I have tried using 'python setup.py py2exe --includes imagec' but that
didn't
help as py2exe complains that there is no module named that.

2. I cannot read the error messages because wxPython redirects them to a
window, which shuts before I can read any output if the program quits.
Is there a way to get wxWindows to stop this behaviour and to have my print
statements and error messages output to standard out?

TIA

Joc




From spam at ingoblank.com  Mon Jul  8 21:30:26 2002
From: spam at ingoblank.com (Ingo Blank)
Date: Tue, 9 Jul 2002 03:30:26 +0200
Subject: Generic vector aggregates
Message-ID: 

Hi,

I want to implement a generic vector aggregate function for dyadic operators
like this:

## -- dyadic operators (primitives)

def add(a,b):
 return a + b

def  mul(a,b):
 return a * b

def inc(a,b):
 return a + 1

## -- generic aggregate

def aggregate(f,v,start=0):
 a = start
 for x in v:
  a = apply(f,(a,x))
 return a

## -- 2nd order callers

def sum(v):
 return aggregate(add,v,0)

def prod(v):
 return aggregate(mul,v,1)

def count(v):
 return aggregate(inc,v,0)

... and so on...

Q:  How can I refer to the built in arithmetic operators "+","*" etc.
    This would save the additional dispatching step, without the need to
call
    "add","mul" etc.

Thanks


--ingo
voy NG arktb QBG qr [ rot13 ]

PGP PublicKey
http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x18B44974





From fakeaddress at nowhere.org  Thu Jul  4 21:56:00 2002
From: fakeaddress at nowhere.org (Bryan Olson)
Date: Fri, 05 Jul 2002 01:56:00 GMT
Subject: sending a file through sockets
References: 
Message-ID: <3D24FCC7.50604@nowhere.org>

brueckd at tbye.com wrote:

 > Guyon Mor?e wrote:
 >>so the trick is to convert a file to a string representation right?

 > Um... you *could* do that, but it wouldn't actually help at all. The
 > contents of the file already are in a string representation because 
Python
 > strings can contain anything, including binary characters. The 
easiest way
 > to send a file is to simply read the data from the file and send it out
 > the socket,

Right.

 > but to send the length of the file first so the receiving end
 > knows if and when it got the whole thing.

That's not really needed.  Just  call shutdown(1) when finished writing.
The receiver can detect the end when recv() returns zero bytes without
error, which only happens on clean shutdown.  The socket will also
select() as readable just before the zero-byte recv().

The only snag is if a local error causes the sender to close the socket
before sending all the data.  Note that in the code, you don't actually
check that you've received as much data as expected.  The code uses the
size to know when to stop reading, and the "if not data: break" will do
that anyway.


 > If you need too much more
 > functionality than this it might be easier to just use one of the 
standard
 > file transfer protocols, e.g. FTP.

Good advice.  For most applications, I'd recommend the HTTP family.


 > Anyway, here's some sample code, but if
 > you're not already familiar with sockets then you should spend a little
 > time experimenting with them.

Did you test this?  The Python library uses the empty string for
INADDR_ANY, which is fine for bind(), but I don't think it's legal for
connect().

I understand it's a basic demo, but I'll note that any real application
requires some time-out discipline to avoid very long hangs.  Also on
most Unix systems we'd need to watch out for signals that force system
calls to return.


--Bryan


 > The sending side listens for incoming connections and sends out the 
file.
 > The receiving side connects to the "server" and writes the file to disk.
 >
 > Common code:
 > import struct
 > PORT = 5555
 > FILENAME = 'foo.bin'
 > HDR = '!I'
 > HDR_SZ = struct.calcsize(HDR)
 >
 > Sending side:
 > import os
 > from socket import *
 > s = socket(AF_INET,SOCK_STREAM)
 > s.bind(('',PORT))
 > s.listen(1)
 > while 1:
 >   q,v = s.accept()
 >   q.sendall(struct.pack(HDR, os.path.getsize(FILENAME)))
 >   f = open(FILENAME,'rb')
 >   while 1:
 >     data = f.read(4096)
 >     if not data: break
 >     q.sendall(data)
 >   q.close()
 >
 > Receiving side:
 > from socket import *
 > f = open(FILENAME, 'wb')
 > s = socket(AF_INET, SOCK_STREAM)
 > s.connect(('', PORT))
 > size = s.recv(HDR_SZ)
 > size = struct.unpack(HDR, size)
 > while size > 0:
 >   data = s.recv(4096)
 >   if not data: break
 >   size -= len(data)
 >   f.write(data)
 > s.close()






From skip at pobox.com  Wed Jul 31 17:13:19 2002
From: skip at pobox.com (Skip Montanaro)
Date: Wed, 31 Jul 2002 16:13:19 -0500
Subject: a soft real-time system using python
In-Reply-To: <200207311646.MAA07767@test-area.com>
References: 
        <20020731145848.GC1800@unpythonic.net>
        <200207311646.MAA07767@test-area.com>
Message-ID: <15688.21231.166476.583264@localhost.localdomain>

    anton> For further information, we're already having a certain problem
    anton> where python threads seem to drastically decrease performance in
    anton> the middle of the program for around a second. 

Do you have pymalloc enabled?  If not, does your platform malloc attempt to
coalesce blocks on the free list?  Python makes lots of malloc/realloc/free
calls, so maybe your malloc implementation is going nuts.

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html



From eugene1977 at hotmail.com  Tue Jul 16 12:41:18 2002
From: eugene1977 at hotmail.com (a64bs4$1oo$1@newsreader.mailgate.org)
Date: Tue, 16 Jul 2002 12:41:18 -0400
Subject: there's no DefaultHandler
Message-ID: 

hi. i'm trying to run my first python program
i'm using python 2.2

[eugene at eugene python]$ python firstxml.py
Traceback (most recent call last):
  File "firstxml.py", line 6, in ?
    class FindIssue(xml.sax.DefaultHandler):
AttributeError: 'module' object has no attribute 'DefaultHandler'



#!/usr/bin/python

from xml.sax import saxutils
import xml

class FindIssue(xml.sax.DefaultHandler):
    def __init__(self, title, number):
        self.search_title, self.search_number = title, number



def startElement(self, name, attrs):
    # If it's not a comic element, ignore it
    if name != 'comic': return

    # Look for the title and number attributes (see text)
    title = attrs.get('title', None)
    number = attrs.get('number', None)
    if (title == self.search_title and 
        number == self.search_number):
        print title, '#' + str(number), 'found'


from xml.sax import make_parser
from xml.sax.handler import feature_namespaces

if __name__ == '__main__':
    # Create a parser
    parser = make_parser()

    # Tell the parser we are not interested in XML namespaces
    parser.setFeature(feature_namespaces, 0)

    # Create the handler
    dh = FindIssue('Sandman', '62')

    # Tell the parser to use our handler
    parser.setContentHandler(dh)

    # Parse the input
    parser.parse("samplexml")



if i change DefaultHandler to handler
i get this error

[eugene at eugene python]$ python firstxml.py
Traceback (most recent call last):
  File "firstxml.py", line 35, in ?
    dh = FindIssue('Sandman', '62')
TypeError: 'module' object is not callable


thank you


From cliechti at gmx.net  Sat Jul 20 19:11:27 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 21 Jul 2002 01:11:27 +0200
Subject: Need some help please
References: <2j2hju8c1btu76tu896cuc9qg6oeep9uoi@4ax.com>
Message-ID: 

Arneau Starl  wrote in 
news:2j2hju8c1btu76tu896cuc9qg6oeep9uoi at 4ax.com:
...
> I cannot figure out a way to do the password
> without Expect (which I cannot install on that machine).  Is there a
> way around this?

you could modify /etc/passwd and /etc/shadow with your script. there is the 
"crypt" module in the stdlib to encode passwords and return a string which 
you can use.
i'm sure thats not the recomended way to do it. maybe someone else comes up 
with a better solution.

chris


-- 
Chris 



From rs at onsitetech.com  Mon Jul  8 14:43:49 2002
From: rs at onsitetech.com (Robb Shecter)
Date: 08 Jul 2002 18:43:49 GMT
Subject: Why self?
References:     
Message-ID: <3D29DD1A.6040209@onsitetech.com>

Richard Barrett wrote:

 >>  I wrote:
 >>  ...[I hate doing this:]...
>>
>>     self.__velocity = self.__factor1 * self.__factor2
>>
> 
> And now you are going to tell which language (compiled or scripting, 
> functional or procedural, or whatever) with OO capability is more 
> productive, from the standpoint of tested lines of code per day, as 
> Python ...
> 

I don't understand what you're asking.  Python is very productive 
overall - I just recommended it as our client app development language. 
  Doesn't mean, though, that there are some parts that are less than 
optimal.

Robb



From maxm at mxm.dk  Tue Jul 30 06:07:17 2002
From: maxm at mxm.dk (Max M)
Date: Tue, 30 Jul 2002 12:07:17 +0200
Subject: pretty basic: get variable name from list of strings?
References:  
Message-ID: <3D466555.1060408@mxm.dk>

Terry Reedy wrote:


> g = globals() #
> for i in range(len(horses)):
>    g['horse_'+str(i)] = horses[i]
> 
> However, I strongly question whether you *really* want to do that.
> Accessing a list of names such as horses thru an index is much easier
> that thru a dict keyed with sequential strings.  Cluttering globals is
> also a bad idea, and above will not work with locals().


Not using a dicts and trying to get variables from generated variable 
names can give all kind of funny side effects.

What if somebody passes a list like:

horses = ['str', 'int', 'float', 'dict', 'repr'] # etc ...

This will certainly cause unintended behaviour.

regards Max M



From gollem at chatway.nl  Tue Jul  2 19:22:48 2002
From: gollem at chatway.nl (gollem)
Date: Tue, 02 Jul 2002 23:22:48 GMT
Subject: creating a file from python
Message-ID: 

I want to create a file from inside a running python script.
I can do that using commands and touch but it won't work if the intended
name of the file is the value of a python variable. The file is created as
the variable name instead of the variable value.
I think I need to use a shell (bash) variable to do it but then the question
becomes how do I create that? thnx




From guillaume.sauzon at caramail.com  Fri Jul 19 09:21:57 2002
From: guillaume.sauzon at caramail.com (Guillaume SAUZON)
Date: 19 Jul 2002 06:21:57 -0700
Subject: Specifying linker and compiler in distutils
Message-ID: <3b13b89e.0207190521.7a3c66db@posting.google.com>

I have the same problem. I try to use gcc instead of the default cc on
my sun machine and distutils doesn't want to know anything. I've tried
something like:

import distutils.sysconfig

old_init_posix = distutils.sysconfig._init_posix

def _init_posix():
    old_init_posix()
    distutils.sysconfig._config_vars['LDSHARED'] = 'gcc -shared'
distutils.sysconfig._init_posix = _init_posix

but it doesn't work !!

Anyone has an idea ?


From maxm at mxm.dk  Mon Jul  1 05:21:01 2002
From: maxm at mxm.dk (Max M)
Date: Mon, 01 Jul 2002 11:21:01 +0200
Subject: Europython pictures
References: <9ZUT8.21128$l6.4303892@newsfep2-win.server.ntli.net>
Message-ID: <3D201EFD.70408@mxm.dk>

Duncan Grisby wrote:

> I took lots of pictures at the Europython conference last week. If
> you're interested in seeing the action, take a look at
> 
>   http://www.grisby.org/Photos/085/


And for those of us who had to stay at home, let those reports come 
rolling in.

regards Max M



From huaiyu at gauss.almadan.ibm.com  Thu Jul 25 13:10:38 2002
From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu)
Date: Thu, 25 Jul 2002 17:10:38 +0000 (UTC)
Subject: Callable modules?
References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <3D3E9BCF.90806@mxm.dk>   
Message-ID: 

Alex Martelli  wrote:
>I don't think we're really communicating.

That is probably true.  I'm thinking about usage situations where you want
to pass callable objects around as if they are functions and objects at the
same time.

>> 
>> If you take b as the object, you need to use explict call.  If you take
>
>Right!  Explicit is better than implicit.  If __call__ didn't
>exist, and by universal convention an instance's "primary method
>if any" was named call, this would be exactly as expected.
>
>> b.call as object, you can't do other things to the object.  Callable
>
>Bound methods currently are not allowed to have arbitrary
>rebindable attributes, while objects of other types can.  But
>that's just how things stand today.  Not long ago, functions
>were not allowed to have arbitrary rebindable attributes
>either -- when that was added, it made a miniscule difference
>to Python usage, possibilities, and convenience, simply because
>the use cases are SO very rare.  If rebinding attributes of
>callables on the fly was deemed important, it would be child's
>play to add that to bound methods too, of course -- might be
>even simpler than for functions, since there would be no need
>to invent a dict for the purpose.

That would be just a change of convention from __call__ to primary.

>Do you REALLY think that having b.call.x = 23 become convenient
>shorthand for b.call.im_self.x = 23 would make a DEEP difference
>to Python?  I see it as trivial enough to not be worth the
>bother -- not a frequent need, and all that.  

Well, it may be easy in some sense, but it certainly is not rare.  Here's a
typical example.  Suppose we have some functionals:

def integration(func, lower, upper): ...
def optimize(func, start): ...

Usually the actual functions have some parameters that may be changed.  With
__call__, we can have the following applications

def app(f):
    p = 1
    for i in range(20):
        p = optimize(f, p)
        f.dothings()
f = Callable()
app(f)

Without __call__, we can either use the same f, with

def app1(f):
    p = 1
    for i in range(20):
        p = optimize(f.call, p)
        f.dothings()

or use f.call, with

def app2(f):
    p = 1
    for i in range(20):
        p = optimize(f, p)
        f.im_self.dothings()

It is true that neither is significantly more difficult.  But having to keep
track of the distinction between f and f.call in applications where they act
naturally as functions is, IMHO, unnecessary burden.  Having to choose
between app1 and app2 (and for app1 having to determine the name of primary
method) before hand also makes the design brittle.

In my experience most functions fall into one of three categories:

- simple functions: sin, sqrt ...
- higher order functions: map, filter, integration
- application specific functions: callable objects with attributes
- application specific higher order functions: using callable objects

In my applications the last two categories are by far the most numerous.  So
this situation is quite common.  I still remember how much trouble I had
years ago with fortran's named common blocks for simulating parameterized
functions so that integration can work on them.  Of course that might just
be my style that relies on using many higher order functions.

Huaiyu


From petrk at pochtamt.ru  Tue Jul 23 04:15:19 2002
From: petrk at pochtamt.ru (Petr Klyushkin)
Date: 23 Jul 2002 12:15:19 +0400
Subject: threads and Tkinter
Message-ID: 

Hello again!

I have one more question about Tkinter. This time it is related with
threads.  I have a program which uses Tkinter as its GUI toolkit.  It
runs a separate "worker" thread for doing some time-consuming
operation.  Sometimes worker thread has to update GUI.

For now I've solved this problem with pipes.  Worker thread writes
data to pipe and GUI thread waits for it with Tkinter's
createfilehandler() and draws them on screen.  This solution seems to
me to be rather cumbersome.  Moreover, it doesn't work on Windows,
because it supports select() only on sockets.

I want to update GUI directly from worker thread, and this requires
Tkinter to be thread-safe.  I have tcl/tk 8.3.4 and Python 2.2 with
tkinter all compiled with thread support.  I've seen sources of
_tkinter and as far as I can understand, it uses a lock to block calls
to Tkinter.  Does it mean that I can fearlessly do Tkinter calls in
both threads and Tkinter will do proper blocking for me?

I'm sorry if this explanation seems to you rather confusing, English
isn't my native language...


-- 
                                                             C'ya, Peter.
       --=[petrk at pochtamt.ru]=--=[http://petrk.pochtamt.ru]=--
        --=[ICQ 89449080]=--=[Jabber dassburger at jabber.ru]=--


From gerhard.haering at gmx.de  Mon Jul 22 02:48:42 2002
From: gerhard.haering at gmx.de (Gerhard Haering)
Date: Mon, 22 Jul 2002 08:48:42 +0200
Subject: openning links from python?
In-Reply-To: 
References: 
Message-ID: <20020722064842.GA16659@gargamel.hqd-internal>

* akhar  [2002-07-22 01:21 -0500]:
> is it possible to have a url load inside the OSes preferred browser?

Yes. Check out the webbrowser module :-)

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




From pinard at iro.umontreal.ca  Tue Jul  9 18:46:52 2002
From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard)
Date: 09 Jul 2002 18:46:52 -0400
Subject: Converting a hex string to a number
In-Reply-To: <3d2b3c2f.3993392@news.dsl.pipex.com>
References: <0017278C.C22236@smiths-aerospace.com>
	
	<3d2b3c2f.3993392@news.dsl.pipex.com>
Message-ID: 

[Simon Foster]

> >> eval!
> >Overkill.  Unsafe.  Ugly.  Lame.

> What do you mean by unsafe?

I agree that `eval' is a bit less safe, in that it could be abused more
easily by people running your programs, if you do not fully trust these
.people, like it especially occurs for your Web scripts, say! :-) You ought
to take extra-precautions for having better control over `eval' arguments,
making sure that no part is never blindly derived from sources which are
external to your program, like files or environment variables.

`eval' is also tinily slower, and has other problems: for example, the
compiler will refuse that you nest scopes having free variables, whenever
you use `eval'.  You see: even the compiler is a bit suspicious about it!

Best is to avoid `eval', `exec', `execfile' and `input' whenever you can.
In really many cases, you will discover that you can easily and elegantly
go without them, after only a few minutes of thinking.  You can also
ask for help on this mailing list if you find more difficult cases.

Oh, undoubtedly and indeed, there are legitimate cases for using `eval'
and friends.  Of course.  But deep down, these cases are infrequent.

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




From florian.eggenberger at o-x.ch  Tue Jul 16 11:02:08 2002
From: florian.eggenberger at o-x.ch (Florian Eggenberger)
Date: Tue, 16 Jul 2002 17:02:08 +0200
Subject: how i use =?ISO-8859-1?Q?=27=E3=27_in_python=3F=3F=3F?=
References: 
Message-ID: <3D343570.7000202@o-x.ch>

jubafre at zipmail.com.br wrote:
> i?m brazilian, and in my laguage(Portguese) there are many other caracters
> how ?, ?, ? and a string in python doesn?t support this
> how i can use??? have a import module for this???
> 
> BRASILEIROS DA LISTA COMO VCS CONSEGUEM USAR ACENTO NO PYTHON??
> 
> for exmple:
> s='?'
> doesn?t work?why??
> 
> 
> Juliano Freitas
> www.gebrasil.hpg.com.br
> 
> 
> 
> ------------------------------------------
> Use o melhor sistema de busca da Internet
> Radar UOL - http://www.radaruol.com.br
> 
> 
> 
> 
> 

It's the same problem in german.
i think it is not possible in the IDLE.
i used hexcodes in the string to "solve" the problem.

example:
'\xE4\xF6\xFC\xC4\xD6\xDC]'
-> ??????

not very good but it works for me.



From davidccarson at hotmail.com  Tue Jul 23 23:46:17 2002
From: davidccarson at hotmail.com (David Carson)
Date: 23 Jul 2002 20:46:17 -0700
Subject: os.getlogin()  raises OSError (errno 25)
Message-ID: <12257ec4.0207231946.583a2e93@posting.google.com>

Could someone please explain why the following runs fine if I type the
input and end stdin with ctrl-D, but bombs when I pipe stdin to it.

=== eg.py ===
#!/usr/bin/env python

import os, sys

tag = sys.stdin.read().strip()
loginName = os.getlogin()
print loginName, tag
=== end ===

Run without pipe, typing input and ctrl-D, looks like:
> eg.py
hello
^D
dcarson hello
>
>


Run by piping my input to the script, I get:
> echo hello | eg.py 
Traceback (most recent call last):
  File "./eg.py", line 7, in ?
    loginName = os.getlogin()
OSError: [Errno 25] Inappropriate ioctl for device
>
>

Environment:
python 2.2
mandrake Linux 8.2

Thanks in advance,
David


From stefnin.nospam at yahoo.fr  Fri Jul  5 04:09:12 2002
From: stefnin.nospam at yahoo.fr (Stephane Ninin)
Date: 05 Jul 2002 08:09:12 GMT
Subject: multiple inheritance & __init__
References:  <3D24F36B.3010307@something.invalid>
Message-ID: 

Greg Ewing  a tapote dans 
news:3D24F36B.3010307 at something.invalid:

> 
> If the classes Observer and Tkinter.Listbox don't
> know anything about each other, then the order
> shouldn't matter.
> 
> It would only matter if, for example, Observer
> expected to be mixed in with a Tkinter widget
> and required the widget to be initialised first.
> If there are no such dependencies, the order is
> up to you.
> 


  Thanks.


-- 
  Stephane Ninin
stefnin.nospam at yahoo.fr
Les cons, ca ose tout... C'est meme a ca qu'on les reconnait.


From jknapka at earthlink.net  Wed Jul  3 00:50:48 2002
From: jknapka at earthlink.net (Joseph A Knapka)
Date: Wed, 03 Jul 2002 04:50:48 GMT
Subject: curses-based menu module?
References: <3D218499.38153895@anansispaceworks.com> 
Message-ID: <3D228233.18C77DE6@earthlink.net>

Skip Montanaro wrote:
> 
>     Terry> Curses itself seems really easy to use, but is kind of a
>     Terry> low-level interface.  Clearly, I will be well-served to make a
>     Terry> higher-level interface for creating and using menus.  But I have
>     Terry> a couple of questions:
> 
>     Terry> Am I reinventing the wheel? Is there already a high-level
>     Terry> interface available (this seems rather likely, though I haven't
>     Terry> found one).
> 
> Dunno, but the first place I'd look is anygui:
> 
>     http://anygui.sourceforge.net/
> 
> Checking the platforms page:
> 
>     http://anygui.sourceforge.net/platforms.php
> 
> suggests that curses is a working platform.

It was, in version 0.1. It's not working in 0.2 yet.
Very little is working in 0.2 so far, due to major
architectural changes. (Changes for the better, I
might add.)

Anygui 0.1 did not even attempt to support menus of the
drop-down cascading variety, so the curses binding
didn't support menus, although it did support all the
other Anygui widgets, including radio buttons, listboxes,
and checkboxes. You might be able to put together
frames supporting all the menu-like functionality
you need using those other widgets.

I am in the process of hacking together a curses binding
for Anygui 0.2, which should include menus. It's slow,
though, because I don't have a lot of time to give to
it just now.

If someone else produces a menuing system for curses
under Python, I'd love to steal it.

-- Joe


From roy at panix.com  Mon Jul  8 09:15:24 2002
From: roy at panix.com (Roy Smith)
Date: Mon, 08 Jul 2002 09:15:24 -0400
Subject: How to organize test cases with PyUnit
References:  <3D2898DC.B59538B1@engcorp.com>    <3D290992.A9AD9AD9@engcorp.com>  <3D290EE0.C9A97B1E@engcorp.com>
Message-ID: 

Peter Hansen  wrote:
> Is it really important the order the tests are run in? 

I'm not sure, but it certainly *feels* like it should be important ;-)

Well, here's an example.  I've got a parser which returns a dictionary 
of dictionaries.  My setUp() method put this in self.tables, then I've 
got:

    def test101 (self):
        'parse() returns a dictionary'
        self.assertEqual (type (self.tables), DictType)

    def test102 (self):
        'parse() returns a dictionary of dictionaries'
        for table in self.tables.values():
            self.assertEqual (type (table), DictType)

I guess the tests could be run in either order, but it seems better to 
do the top-level test first because that mimics how I think about the 
problem.  If you were to come to me and say, "I've got this complicated 
data structure which I think may be corrupted, can you help me figure 
out what i did wrong?", I'd probably start at the top and work my way 
down.

>From the point of view of "it's done when it passes all the tests", then 
yes, I agree with you that the order doesn't matter.  But as a 
diagnostic tool, it seems like order might be important.


From ls2312 at netcom.com  Tue Jul  9 19:53:33 2002
From: ls2312 at netcom.com (Lowel Stern)
Date: Tue, 09 Jul 2002 16:53:33 -0700
Subject: php function "addslashes" / "removeslashes" in python 
Message-ID: 

Does anyone know if this exists already?

Lowel



From LogiplexSoftware at earthlink.net  Thu Jul 18 17:50:29 2002
From: LogiplexSoftware at earthlink.net (Cliff Wells)
Date: 18 Jul 2002 14:50:29 -0700
Subject: Tkinter vs. wxPython
In-Reply-To: <0C7CA8D8DF75494EB09AB6016990107F016F60C6@NOXMAIL.noetixad.com>
References: <0C7CA8D8DF75494EB09AB6016990107F016F60C6@NOXMAIL.noetixad.com>
Message-ID: <1027029029.1661.89.camel@software1.logiplex.internal>

On Thu, 2002-07-18 at 14:19, Gabe Newcomb wrote:
> Ack!
> 	I've been trying to get into wxPython, but I'm finding the lack
> of documentation difficult. There's some, and I'm very grateful for
> everybody who's contributed it, but I'm somebody who really likes having
> a decent reference and more examples.

The wxPython docs are indeed terse.  However, used in combination with
the wxPython demo, they should be adequate (there's also a wxPython
mailing list and a wiki with example code to draw from - see
http://www.wxpython.org). 

> My question is this: is there any compelling reason I shouldn't just go
> with Tkinter instead? I work (for now) exclusively on Win32 boxes, by
> the way.

Tkinter has the advantage of running out-of-the-box with Python.  It's
also been around a while and is very stable.  However, it also looks
like a misfit on whatever platform you are using it on (except perhaps
CDE/Motif).  wxPython has the advantages of a native look-and-feel (it
uses the platform's underlying widget set rather than creating its own)
and a richer widget set.  That said, it also has a higher learning
curve.  However, Tkinter's simplicity can become a liability when you
get into more complex applications.

IMHO with wxPython you pay the price early (the learning curve) whereas
with Tkinter you pay the price later (working around a somewhat
simplistic toolkit).

Undoubtedly others will have different opinions, but that's my $0.02
worth.

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





From fredrik at pythonware.com  Thu Jul  4 11:26:01 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Thu, 04 Jul 2002 15:26:01 GMT
Subject: Full-screen display in Tkinter
References: <21298535.0207040554.6caeed01@posting.google.com>
Message-ID: 

Svein Brekke wrote:
> I am building a slide show application with Tkinter, and need
> to create a full-screen window, i.e. supressing title bar
> and start menu etc.

root = Tk()

# make it cover the entire screen
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))






From miracle at paradise.net.nz  Sun Jul 21 17:31:25 2002
From: miracle at paradise.net.nz (Matthew Sherborne)
Date: Mon, 22 Jul 2002 09:31:25 +1200
Subject: COM server events
Message-ID: <3D3B282D.6060601@paradise.net.nz>

Anyone know how I can write a COM server that serves events? I think 
what I need is "connection points" ?

Matthew



From altis at semi-retired.com  Fri Jul 19 02:19:54 2002
From: altis at semi-retired.com (Kevin Altis)
Date: Thu, 18 Jul 2002 23:19:54 -0700
Subject: Tkinter vs. wxPython
References:  
Message-ID: <09OZ8.376$rb.152305@news.uswest.net>

"Darrell"  wrote in message
news:qBLZ8.168518$GY.55207952 at twister.nyroc.rr.com...
> I'm not a GUI expert...
> But today I needed to do a quick image viewer tool. This is what I found.
>
> Tkinter makes smaller exe's
>
> PMW which wraps Tkinter seems impossible to wrap as an exe.
>
> AFIK wxPython wants to display images from BMP's. They dont look very
good.
> They were slow and crashed. My images are 40+ meg.

What do you mean wants to display images from BMPs? Could it be you are
confusing the wxBitmap class with BMPs? wxPython supports most popular image
formats (here's an incomplete list of extensions): BMP, GIF, JPG/JPEG, PCX,
PNG, PNM, TIF/TIFF, XBM, and XPM. Note that wxPython can't write GIFs due to
licensing restrictions but it can read GIFs.

The pictureViewer sample that comes with PythonCard can open all of these.

> Tkinter has some nice Photo image stuff. Although I haven't figured out
how
> most of it works.

Another possibility is to convert PIL images to wxPython wxImage or wxBitmap
classes. That gives you the best of both worlds. PIL has some built-in image
manipulation that isn't available in wxPython without using some additional
libraries or coding up the image processing yourself. It is also possible to
convert between NumPy arrays and wxPython wxImage or wxBitmap classes.

ka




From ods at fep.ru  Fri Jul 12 11:07:47 2002
From: ods at fep.ru (Denis S. Otkidach)
Date: Fri, 12 Jul 2002 19:07:47 +0400 (MSD)
Subject: Converting 2 bytes string into INT
In-Reply-To: 
Message-ID: 

On Fri, 12 Jul 2002, DeDa wrote:

D> Hi to all, I'm a newbie of Python and I already have a big
D> problem. I read 2
D> bytes from files and I like to convert them into an integer.
D> How can I do
D> it?

struct.unpack(), see
http://www.python.org/doc/current/lib/module-struct.html

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]
http://diveinto.python.ru/ [ru]





From hjwidmaier at web.de  Fri Jul 19 03:20:38 2002
From: hjwidmaier at web.de (Hans-Joachim Widmaier)
Date: 19 Jul 2002 00:20:38 -0700
Subject: Percent sign in format string?
References: 
Message-ID: <6e990e29.0207182320.1cd8cd26@posting.google.com>

"Mark McEahern"  wrote in message news:...
> print "%d%%" % 98
> 
> in other words, % is an escape character that lets you print %.



% is a format character that does not consume an argument but produces
a percent sign. This can easily be shown:


print "And I thought '%10%' was just a %s sign when in fact it's " \
      "whitespace as well!" % "percent"



Hans-Joachim


From brueckd at tbye.com  Thu Jul 18 14:37:32 2002
From: brueckd at tbye.com (brueckd at tbye.com)
Date: Thu, 18 Jul 2002 11:37:32 -0700 (PDT)
Subject: asyncore: limiting number of simultaneous connections?
In-Reply-To: 
Message-ID: 

On Wed, 17 Jul 2002, Jason R.Mastaler wrote:

> I'm building a server based on asynchat/asyncore.  The
> documentation for these modules is sketchy at best, and I couldn't
> find an answer to this after browsing through the code.
> 
> Is there an easy way to limit the number of simultaneous connections
> to such a server?  My preliminary tests indicate that it will happily
> accept as many connections as the host system will allow, which is not
> good.  I'd like to be able to specify a ceiling on this.

You should be able to just implement your own readable method in the
listening socket, e.g.  (untested and assumes your listening socket is
derived from asnychat.async_chat):

def readable(self):
  if not self.AllowedToAcceptMoreConnections(): # You implement this
    return 0
  return asynchat.async_chat.readable(self)

For other reasons I used a different approach in one program: have the
accepting socket be on another thread, and it controlled access that way
(when it was ok it have another connection it would accept it and add it
to asyncore with:

asynchat.async_chat.__init__(self, conn)

Also, you can check len(asyncore.socket_map) to see how many sockets it is 
currently handling.

HTH,
Dave





From jgoerzen at complete.org  Wed Jul  3 08:52:32 2002
From: jgoerzen at complete.org (John Goerzen)
Date: Wed, 3 Jul 2002 12:52:32 +0000 (UTC)
Subject: Thread safetyness in Python
Message-ID: 

Hi,

I have some questions about what is thread-safe in Python.  Can someone tell
me whether each of the following are thread-safe:

1. a = a + 1
2. a = a + 2
3. list.append(x)
4. list.remove(x)
5. del(list[0])

Here's why I'm asking:

1. In C, a++ would be atomic because CPUs have an atomic increment
operation, in most cases.  In Python, it might be the case that if two
threads hit this code at the same time, a would only be incremented once
because both threads would read a, add 1, and store the same result back. 
So one might need a lock here.

2. This operation is not possible with just the increment operator.

3. If this is not thread-safe and two threads try to do it simultaneously,
it might be the case that each thread adds a new list[5] instead of one
adding list[5] and the other list[6].

4. If this is not thread-safe, both threads might remove the same item,
rather than one thread removing it and the other raising an exception.

5. If not thread-safe, both threads might remove the same item, rather than
one thread removing the first item and the next, the second.

Thanks,
John

-- 
John Goerzen     GPG: 0x8A1D9A1F    www.complete.org


From erict at millfilm.co.uk  Thu Jul 25 05:09:34 2002
From: erict at millfilm.co.uk (Eric Texier)
Date: Thu, 25 Jul 2002 10:09:34 +0100
Subject: Base classes or global functions
References:  <3D3F37E0.2000209@onsitetech.com>
Message-ID: <3D3FC04E.EA6916B6@millfilm.co.uk>

In case of scenari #3, I like personnally the use of staticmethod

class utilHelper:
    ''' some initialization code and variable can happen here when the module
        is loaded
    '''
    def somefunction(params):
       ....

    somefunction = staticmethod(somefunction)




Robb Shecter wrote:

> Stephen Boulet wrote:
> > I have two classes, Class1 and Class2. Class1 contains a list of Class2
> > objects, but no inheritance is involved
> >
> > Both classes use some functions I wrote. What's the best way of making the
> > functions available to the classes?
> >
>
> Good questions.  To answer it, we'd have to know what the functions do -
> what information they manipulate.  Depending on your answer, any of the
> following scenarios are possible:
>
> 1. The functions become methods of Class1.
> 2. The functions become methods of Class2.
> 3. The functions become methods of a new, as yet unwritten class.
> 3a. This new class would be used by Class1 and Class2
> 3b. This new class would be subclassed by either Class1 or Class2.
>
> Robb



From aleax at aleax.it  Tue Jul  9 01:45:10 2002
From: aleax at aleax.it (Alex Martelli)
Date: Tue, 09 Jul 2002 05:45:10 GMT
Subject: j2ee vs. python (and what our evil competitors are saying about  python)
References: <96c7f32.0207081518.52ea644a@posting.google.com> <3D2A27DA.16E95379@earthlink.net>
Message-ID: 

Joseph A Knapka wrote:
        ...
>> ?         No automatic garbage collection.
> 
> A damned lie, as casual perusal of the Python documentation
> would reveal. Your major weapon against this competitor might
> be simply that they lie to their customers!

Yes, there are by far enough outright lies in this document that
you should be able to just point out a few of them and totally
destroy their credibility -- no need to get into anything arguable.
Besides the ones noted as such by Joseph, here's a few more:

>> ?         Limited documentation- only two English language books exist
>> which provide tutorials or a library reference for Python.

Another ridiculous lie -- *dozens* of English language books about
Python, and MOST provide tutorials, in addition to the many found
on the net.  The demand for duplicates of the reference materials
supplied with Python is obviously lower than that for tutorials, but
even in that field there's quite a bit of overlap.

>> ?         Lacks basic tools such as integrated source level debuggers.
> 
> That's not entirely true. There's IDLE and Pythonwin,

Those are two free ones, but don't forget the impressive array of
commercial products, too -- Archaeopteryx's Wing, PythonWorks,
ActiveState's Komodo and Visual Python, Blackadder... i.e.,
another total lie.  You wouldn't be happening to be competing
against a WorldCom subsidiary, would you?

>> ?         No packaging methods for software distribution.
> 
> distutils

Yep -- yet one more outright, bare-faced lie.


Alex



From fredrik at pythonware.com  Thu Jul  4 11:25:01 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Thu, 04 Jul 2002 15:25:01 GMT
Subject: TkInter and pygame?
References: <3D2462A6.B1BB696D@ipm.fhg.de>
Message-ID: 

Markus von Ehr wrote:

> is there a possibility to mix TkInter windows with
> pygame sprites for example?  (in one application)

if pygame allows you to draw in an arbitrary window, you can
use Tkinter's winfo_id() method to get a window handle, and
pass that on to pygame.

tke tkinter3000 framework can make it a bit easier to keep track
of resize and expose events:

    http://effbot.org/zone/tkinter3000-embed.htm






From tdelaney at avaya.com  Sun Jul 21 20:01:41 2002
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Mon, 22 Jul 2002 10:01:41 +1000
Subject: A better self
Message-ID: 

> From: Alex Martelli [mailto:aleax at aleax.it]
> 
> The point is that SelferMeta.__new__ gets to look at all of
> class Myself's dictionary *and tamper with it as needed* before
> delegating the rest to class type.  Specifically, it would get
> to look at the various methods, already compiled down to
> bytecode... and change the bytecode as needed, i.e., each
> of the various LOAD_GLOBAL, STORE_FAST, LOAD_FAST, would be
> checked to see if the name it refers to is in __slots__, and,
> if so, transformed into LOAD_FAST+LOAD_ATTR, or LOAD_FAST+
> STORE_ATTR.  Of course, all the arguments of the various
> JUMP_* operators would have to be adjusted as the code's

Wouldn't work in Jython ... (when Jython gets to 2.2 ...).

Tim Delaney




From yduppen at xs4all.nl  Fri Jul 26 10:46:32 2002
From: yduppen at xs4all.nl (Yigal Duppen)
Date: Fri, 26 Jul 2002 16:46:32 +0200
Subject: Challenge/Response authentication
References: <05a2ku0canlcg4a3t3cuck7q9cqlrntu46@4ax.com>
Message-ID: <3d41652d$0$12276$e4fe514c@dreader4.news.xs4all.nl>

> As I understand it, challenge/response works thus:

>From the top of my head, I can't really help.
But when you're in doubt, always consult Bruce Schneier's "Applied 
Cryptography". 

YDD
-- 
.sigmentation Fault


From aleax at aleax.it  Fri Jul 12 05:24:02 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 12 Jul 2002 09:24:02 GMT
Subject: writing output to file
References:  <3D2E041A.9080704@earthlink.net>
Message-ID: 

Hans Nowak wrote:
        ...
>> I would appreciate if someone would help me out.
> 
> Redirect sys.stdout:
> 
> oldstdout = sys.stdout
> sys.stdout = open("some file", "w") # or any file(-like) object
> 
> # your code here; print statements should be redirected
> 
> # clean up
> sys.stdout = oldstdout

"Yes, but" -- this is very fragile code: any exception from the
part "your code here", and you're left with sys.stdout pointing
who knows where.  A more robust approach:


oldstdout = sys.stdout
newstdout = open("whatever", "w")
sys.stdout = newstdout

try:
    # your code here
finally:
    # GUARANTEED cleanup
    sys.stdout = oldstdout
    newstdout.close()


This kind of task is exactly what try/finally is for: ENSURE that
cleanup code runs, no matter whether a certain piece of code
terminates normally or by propagating exceptions.

Singling out newstdout here may be overkill, but I'd fear
exceptions from the close method in the case of file-like
objects, thus the braces-and-belt approach.  An exception
in a finally cause is not the end of the world, but I feel
safer knowing that I HAVE restored sys.stdout anyway, just
in case such an exception DOES arise:-).


Alex



From tim.one at comcast.net  Thu Jul 11 05:47:22 2002
From: tim.one at comcast.net (Tim Peters)
Date: Thu, 11 Jul 2002 05:47:22 -0400
Subject: Python in the enterprise: Pros and cons
In-Reply-To: <200207110952.21663.b.maryniuk@forbis.lt>
Message-ID: 

[builder]
> Python has many fans in the open source community, but is it ready for
> the enterprise? 

[Bo M. Maryniuck]
> What the buzzword "the enterprise" is (as other buzzwords, aka 
> XML, Java etc)?

It's an especially annoying American buzzword for "business use, as opposed to consumer, research, or educational use".  Your enterprise-ready software is primed to take on the challenge of synergizing mission-critical business logic in empowering ways.  IOW, it computes the sales tax right more often than not .

to-the-next-level-going-forward-ly y'rs  - tim





From pan-newsreader at thomas-guettler.de  Wed Jul 24 12:16:43 2002
From: pan-newsreader at thomas-guettler.de (Thomas Guettler)
Date: Wed, 24 Jul 2002 18:16:43 +0200
Subject: Geek-Ware in Germany
Message-ID: 

Hi!

Does some know where I can get python geek ware (t-shirts, hats)
in germany?

 thomas


From jtorborg at fnal.gov  Mon Jul 22 16:24:14 2002
From: jtorborg at fnal.gov (Julie Torborg)
Date: 22 Jul 2002 13:24:14 -0700
Subject: Tkinter: Relative positioning of Toplevels
Message-ID: <3e382ec4.0207221224.1b8d49a0@posting.google.com>

Hello.

I was wondering if anyone can tell me how to position a toplevel
relative to another widget.

Basically, I want to end up with something that behaves like a
pull-down menu, except that you can't select anything--it just
displays information. I'm not clever enough to hack the OptionMenu
class, so I've been trying to use a button/toplevel combination.  I
want the toplevel to appear "anchored" to the button.  The problem is,
I can't get the toplevel to show up anywhere near the button. I use

self.x=nb.winfo_geometry()

to get the position of the button relative to it's parent, but when I
do:

self.tl.geometry(self.x)

it draws the toplevel with these coordinates relative to the screen.
I'm trying to write this as a class that doesn't care what frame it's
embedded in, so it's impractical for me to try to recursively locate
all the upstream windows.

My code is below.  Thanks for any advice.

Julie

class eachModule:
    def __init__(self, pf):
        self.pf=pf       
        nb=Button(self.pf, text="Popup")
        nb.bind("", self.pr)
        nb.bind("", self.rel)
        nb.pack()
        self.pf.update_idletasks()
        self.x=nb.winfo_geometry()
    
    def pr(self, event):
        self.tl=Toplevel(self.pf)
        self.tl.overrideredirect(1)
        self.tl.geometry(self.x)
        label=Label(self.tl, text="info up")
        label.pack()

    def rel(self, event):
        self.tl.destroy()


if __name__=="__main__":

    def die():
        root.quit()
        root.destroy()
        
    root=Tk()

    em=eachModule(root)
    
    eb=Button(root, text="Exit", command=die) 
    eb.pack()
    root.mainloop()


From tim.one at comcast.net  Fri Jul 12 21:47:17 2002
From: tim.one at comcast.net (Tim Peters)
Date: Fri, 12 Jul 2002 21:47:17 -0400
Subject: switch recipe?
In-Reply-To: 
Message-ID: 

[Tim]
> So my candidate for simplification is:
>
> def make_switch(*args):
>     """Generate the elements in args repeatedly."""
>     if not args:
>         raise TypeError("at least one argument required")
>     while True:
>         for a in args:
>             yield a
>
> I'd lose the "if not args:" block, though; if the arglist is
> empty, it will simply terminate without yielding anything, and that's
> what I expect the empty case to do.

[Mark McEahern]
> If you leave the while True, then it won't raise StopIteration
> when you call it without arguments.

So true -- and even if you change it to "while 1" .

> The simple fix is to replace that with while args.

Yes, that's nice!

> Here's the result of my latest tinkering.  For what it's worth, I think I
> prefer raising the error in the generator when args is not specified
> rather than waiting until next() is called the first time--on the
> principle that raising the error earlier is better.

Then that's where we differ:  I don't consider an empty sequence to be "an
error" in any sense of the word.  For the same reason, range(10, 10) doesn't
complain in Python, or string[i:i], etc -- doing nothing gracefully is
important because there's sometimes nothing that needs be done .





From aahz at pythoncraft.com  Thu Jul 11 14:35:40 2002
From: aahz at pythoncraft.com (Aahz)
Date: 11 Jul 2002 14:35:40 -0400
Subject: Q: What does "Sparse is better than dense" mean? (Python Zen)
References: <33803989.0207110328.5ef01f1e@posting.google.com>
Message-ID: 

In article <33803989.0207110328.5ef01f1e at posting.google.com>,
Miki Tebeka  wrote:
>
>Although it's in the Humor section I take the Python Zen
>(http://www.python.org/doc/Humor.html#zen) quite seriously.
>However I can understand what does “Sparse is better than
>dense” means.

Here's a better example than the one Peter gave:

    if i>0: return sqrt(i)
    elif i==0: return 0
    else: return 1j * sqrt(-i)

versus

    if i>0:
        return sqrt(i)
    elif i==0:
        return 0
    else:
        return 1j * sqrt(-i)

To rephrase the dictum another way, "Don't try to stick too much code on
one line."
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From shagshag13 at yahoo.fr  Tue Jul  9 09:46:17 2002
From: shagshag13 at yahoo.fr (Shagshag13)
Date: Tue, 9 Jul 2002 15:46:17 +0200
Subject: Splitting a string every 'n'
References: 
Message-ID: 

 a ?crit dans le message de news: mailman.1026219434.22644.python-list at python.org...
>
> What is the idiomatic way to split a string into a list
> containing 'n' character substrings?  I normally do
> something like:
>
> while strng:
>     substring = strng[:n]
>     strng = strng[n:]
>     
>
> But the performance of this is hopeless for very long strings!
> Presumable because there's too much list reallocation?  Can't Python
> just optimise this by shuffling the start of the list forward?
>
> Any better ideas, short of manually indexing through?  Is there
> something like:
>
> for substring in strng.nsplit():
>     
>
>

(i'm replying but as i'm still a newbie i don't know if it's a good idea - but just trying and hope that gurus will correct)

x = []
i0 = 0
for i in range(n,len(strng) + n,n):
    x.append(strng[i0:i])
    i0 = i
map(, x)

s13.




From eric.brunel at pragmadev.com  Mon Jul  1 08:58:35 2002
From: eric.brunel at pragmadev.com (Eric Brunel)
Date: Mon, 1 Jul 2002 12:58:35 +0000
Subject: WindowsError in time.sleep !?!??!!
References:   
Message-ID: 

Thomas Heller wrote:
> This sounds like some C code (in an extension?)is setting
> an error, and failes to check for NULL afterwards.
> If you insert something like this before your "if v == '':" line
>   try: 1/0
>   except: pass
> and the problem goes away, it seems to be the cause for it.

This was it! Thank you very much: we'd never figured out this one by 
ourselves...
-- 
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com


From achim.domma at syynx.de  Fri Jul  5 13:51:26 2002
From: achim.domma at syynx.de (Achim Domma)
Date: Fri, 5 Jul 2002 19:51:26 +0200
Subject: adding methods on the fly
References: 
Message-ID: 

"Renzo Tomaselli"  wrote in message
news:ag4gib$m5t$1 at news.flashnet.it...
>     after a long and unsuccessful search about extending C++ classes by
> Python methods, I came up to the point where a couple of basic questions
> should be answered:

Have looked at boost.python (www.boost.org) ?

Achim




From roy at panix.com  Sun Jul  7 14:52:00 2002
From: roy at panix.com (Roy Smith)
Date: Sun, 07 Jul 2002 14:52:00 -0400
Subject: How to organize test cases with PyUnit
Message-ID: 

I'm looking at using unittest for a new project.  This would be my first 
use of unittest, although I've rolled my own test suites a few times.  
How do people usually organize the test cases for a module?  Offhand, I 
can think of a few ways to do it.

I could put all the test-case code in the same .py file as the module.  
This seems the least complicated, but perhaps also the least efficient 
since it's a lot more code to parse when the module is imported.  
Possibly isolate the test cases with a __name__ == "__main__" 
conditional?

I could put the test cases for a module in another file in the same 
directory, or possibly put all the test cases for all my modules in a 
"test" subdirectory.  This answers the efficiency question above, but 
seems like it's begging to have the two files get out of sync.  Also, 
does the test case file import the module being tested?  Is there a 
common higher-level file that imports both?

I realize none of these are absolutely critical issues, but I'd be 
interested to hear how othe people have done it.

BTW, I started out with the test cases in a "test" subdirectory, and ran 
into a slight uglyness.  My initial idea was to just have module-test.py 
do an "import ../module", until I discovered that gives you a syntax 
error.  I can get around it with:

import sys
sys.path.insert (1, '..')
import module

but that seems clumsy.  Is there a cleaner way to do that?


From aleax at aleax.it  Tue Jul  9 10:50:35 2002
From: aleax at aleax.it (Alex Martelli)
Date: Tue, 09 Jul 2002 14:50:35 GMT
Subject: sorting many arrays from one...
References:    
Message-ID: <%KCW8.60416$vm5.2194409@news2.tin.it>

Shagshag13 wrote:

> 
> "Duncan Booth" 
> Alex Martelli 
> 
> thanks to you two !
> 
> so if i want to do this in a generic function, i should use something like
> :
> 
> def sortManyFromOne(driven, compare = None, *others):
> 
>  aux = zip(driven, *others)
>  if compare is None:
>   aux.sort()
>  else:
>   aux.sort(compare)
>  driven, *others = map(list, zip(*aux))
> 
> but this last line don't work and i don't know how to fix it... unless i
> replace it by :
> 
> return map(list, zip(*aux))

Better -- let your caller do the unpacking as needed.


> is it a good idea if we consider that my "driven" and "others" could
> contain more than 300,000 elements each ? (i'm thinking of using
> array.array instead of list)

Then ABSOLUTELY forget the idea of passing a compare function to aux.sort!!!
This would drag the sorting down to a HORRIBLE crawl.  COnsider (python 
2.2.1, -O, on 1.4 GHz Athlon with DDR RAM to burn):

>>> import random
>>> k3 = range(300000)
>>> random.shuffle(k3)
>>> xx = k3[:]
>>> a=time.clock(); xx(300000).sort(); b=time.clock(); print b-a
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'list' object is not callable
>>> a=time.clock(); xx.sort(); b=time.clock(); print b-a
0.81
>>> xx = k3[:]
>>> def f(a,b): return cmp(a,b)
...
>>> a=time.clock(); xx.sort(f); b=time.clock(); print b-a
10.97
>>>

even for this super-simplified case where the sequence to sort is so
clean and the comparison function does nothing more than delegate to
the same cmp that would be used anyway, you pay well more than an
order of magnitude for the privilege of passing a compare function
to the sort method!!!

Don't do it.  Use D-S-U, as AMPLY explained in the searching and
sorting chapter of the Python Cookbook (which I'm told you can
order already, though physically I think it's going to be launched
at OSCON).  I.e., if your calling code needs flexibility, let
that flexibility be obtained by passing a suitably modified version
of the 'driven' array, NOT with a comparison-function for sort.

This is one of the top few crucial performance tips in Python:

1. do NOT put together a big string by concatenating many small
   ones with + or += -- prepare a list and ''.join it when done

2. do NOT do lots of O(N) searches and anywhere-but-the-end
   insertions and deletions in lists -- consider dictionaries

3. do NOT pass a comparison function to .sort for lists of any
   substantial size -- use decorate/sort/undecorate (DSU)

4. there is no point 4 (well, there ARE many other small
   issues, but none as frequent and important as the first 3)


Alex



From pyth at devel.trillke.net  Thu Jul 25 06:57:37 2002
From: pyth at devel.trillke.net (holger krekel)
Date: Thu, 25 Jul 2002 12:57:37 +0200
Subject: Callable modules?
In-Reply-To: ; from fperez528@yahoo.com on Wed, Jul 24, 2002 at 06:12:46PM -0600
References: <7xznwk1hfy.fsf@ruckus.brouhaha.com>  <7xr8hwnu3s.fsf@ruckus.brouhaha.com>  
Message-ID: <20020725125737.L10625@prim.han.de>

Fernando Perez wrote:
> holger krekel wrote:
> 
> > from somemodule.someclass import filter1
> 
> What about:
> 
> #somemodule.py
> def filter1(self,args):
>   ...
> 
> def filter2(self,args):
>   ...
> 
> class someclass:
>   ...
> 
> someclass.filter1 = filter1
> someclass.filter2 = filter2
> ...
> 
> # end somemodule.py
> 
> I know there's still one little layer of redundant typing, but it only has to 
> be done in the module which defines your class, not by the users. So you do 
> it once and you are done.

Yes. I'd even prefer automating this somewhat more (via a loop over
the filter function in which 'setattr(someclass,name,obj)' is performed.

But still i don't see any reason, why 

    from somemodule.someclass import somenames

should not work. 

> ps. I guess you lose safety checks on what 'self' is when you invoke them as 
> standalones, ...

but you gain flexibility :-)

    holger



From uwe.schmitt at procoders.net  Mon Jul 29 04:56:58 2002
From: uwe.schmitt at procoders.net (Uwe Schmitt)
Date: 29 Jul 2002 08:56:58 GMT
Subject: announcement
References: 
Message-ID: 

Uwe Schmitt  wrote:

I fixed an error concerning running the program on linux.
Thanks to Gerhard Haering. 
Download of the correct version at http://ziarc.procoders.net.

Greetings Uwe.

-- 
Dr. rer. nat. Uwe Schmitt    python, php, c++, codes, tips, tutorials at
uwe.schmitt at procoders.net    http://www.procoders.net


From mgilfix at eecs.tufts.edu  Mon Jul 29 10:48:16 2002
From: mgilfix at eecs.tufts.edu (Michael Gilfix)
Date: Mon, 29 Jul 2002 10:48:16 -0400
Subject: DIV and MOD
In-Reply-To: ; from jdhunter@ace.bsd.uchicago.edu on Mon, Jul 29, 2002 at 09:32:20AM -0500
References: <5.1.1.6.0.20020729112008.009fa0c0@imap.datacraft.com.br> 
Message-ID: <20020729104816.F15737@eecs.tufts.edu>

  Yes, but no need to worry until 3.x. And with 3.x, many changes will
be expected anyway :)

                 -- Mike

On Mon, Jul 29 @ 09:32, John Hunter wrote:
> Note that in future pythons, The / operator will no longer be integer
> (floor) division.  See http://www.python.org/peps/pep-0238.html.

-- 
Michael Gilfix
mgilfix at eecs.tufts.edu

For my gpg public key:
http://www.eecs.tufts.edu/~mgilfix/contact.html



From Bart.Bartels at vu.edu.au  Wed Jul 10 03:11:29 2002
From: Bart.Bartels at vu.edu.au (Bart Bartels)
Date: Wed, 10 Jul 2002 17:11:29 +1000
Subject: Lunar lander example
References: 
Message-ID: <3D2BDE21.A2805D71@vu.edu.au>

Tell us when & where you put it.  My son is interested in gaming and
programming (he is 16) and this would (maybe) a good start

Bart

- Remember the Prince and Petronius Arbiter -

Michael Bauers wrote:
> 
> I wrote a simple Lunar Lander program in Python, and I thought it
> demonstrated a lot of basic Python features.
> 
> I was wondering if there was a place for example programs for new Pythoneers
> to look at?


From loewis at informatik.hu-berlin.de  Wed Jul 31 08:30:27 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=)
Date: 31 Jul 2002 14:30:27 +0200
Subject: global interpreter lock not working as it should
References:  
Message-ID: 

anton wilson  writes:

> Maybe I am not being clear enough. I am concerned with a multi-threaded 
> program that does not do any form of blocking on a Linux/Unix box. I DO 
> expect a thread to block on the GIL every 10 byte codes. 

That expectation is wrong. The thread will release the GIL every 10
byte codes. Whether that results in blocking is the operating system's
choice.

> However, I have proved with my results that this does NOT
> happen. Any thread that is completely CPU bound will never give up
> the CPU for as long as
> 1) it can run
> 2) it has work to do

I believe this is not true. The system will schedule a different
thread eventually, atleast on all systems I could try.


> The great majority of the time, my print statement will be printed, meaning 
> the GIL was not released.

But sometimes, it was released? Then everything is working as designed.

> > Lo and behold, each thread is getting execution time, and nearly equal
> > execution time at that!
> 
> 
> There are several reasons why your program seems to work.
> The first obvious reason is that the main thread sleeps. 

So what? Does that make the claim false that all other threads get equal time?

> This proves that the GIL does not block very often, and definitely not every 
> 10 byte codes. Think about this for a while.

Nobody said there will be thread switch every 10 byte code
instructions. In fact, doing that will be very expensive.

> Here, you will notice that there are constant changes. The GIL releasing is 
> working as intended.

No, it's not. The intention of the GIL is different.

> This brings me to the second reason that your program seems to work.
> The Linux OS gives threads time-slices and when these time-slices are used up 
> every 150 or so milliseconds, the process is forcibly removed from the CPU.
> I presume that the reason your program seems to work is that in the time 
> between when a thread releases the GIL and a thread tries to reaquire the 
> GIL, it is forcibly removed from the CPU, and the other thread can now run. 

Indeed, and that is the intention of the GIL: When the
system-allocated slice has expired, a thread switch should occur. For
that to happen, the GIL must be, and is, released.

> Because the thread is never forced by the OS to relinquish the CPU, the 
> thread will never ever lose the GIL. If the GIL was actually working corectly 
> and blocking, the second thread would not retain the CPU past 10 byte codes.

It would not be correct if the GIL was blocking.

> So, the GIL does not blcok as intended, and this probably needs to be looked 
> into.

It does not always block, and this is as intended.

Regards,
Martin


From paddy3118 at tiscali.co.uk  Tue Jul  9 16:50:17 2002
From: paddy3118 at tiscali.co.uk (Paddy)
Date: Tue, 09 Jul 2002 21:50:17 +0100
Subject: HTML to PDF converter?
References: 
Message-ID: <3D2B4C89.5040604@tiscali.co.uk>

Try a google search for HTMLDOC from Easy Software.

I use it on Win XP .

Cheers, Paddy.


Lance Ellinghaus wrote:

> Does anyone know of a HTML to PDF converter that is written in Python?
> 
> Thank you,
> 
> Lance Ellinghaus
> 
> 
> =====
> --
> Lance Ellinghaus
> 
> __________________________________________________
> Do You Yahoo!?
> Sign up for SBC Yahoo! Dial - First Month Free
> http://sbc.yahoo.com
> 
> 
> 




From phr-n2002b at NOSPAMnightsong.com  Mon Jul  8 02:29:28 2002
From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin)
Date: 07 Jul 2002 23:29:28 -0700
Subject: structs in python
References: <20020706231200.A25295@arizona.localdomain> 
Message-ID: <7xbs9i91h3.fsf@ruckus.brouhaha.com>

list-python at ccraig.org (Christopher A. Craig) writes:
> Why don't you just use a dict?  
> 
> >>> p = {'x'=10, 'y'=11, 'color'=blue}
> >>> print p['x']
> 10

Typing p['x'] is more cumbersome than typing p.x and doesn't convey
the same type of meaning.  p.x sounds more like it refers to a fixed
slot in a structure.


From opengeometry at NOSPAM.yahoo.ca  Tue Jul  9 18:31:10 2002
From: opengeometry at NOSPAM.yahoo.ca (William Park)
Date: 9 Jul 2002 22:31:10 GMT
Subject: How to grab a part of web page?
References: 
Message-ID: 

A  wrote:
> Hi,
> Is it possible to download only a part of web page?
> Say I need to find out an information about a customer that starts 
> at 1500 byte position and ends at 2000 byte position. If the whole 
> page has about 100 kb it seems to me waste of time to load all the 
> page.
> What is the best, yet easy, solution?
> Is it possible to use httplib or necessary socket module?
> Thank you for help.
> Ladislav

I think it's possible.  When I use 'wget -c' to download HTML, sometimes I
see it start from an offset, rather than from the beginning.

-- 
William Park, Open Geometry Consulting, 
8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin


From spam at ob_scure.dk  Tue Jul 30 15:04:19 2002
From: spam at ob_scure.dk (Thomas Jensen)
Date: Tue, 30 Jul 2002 21:04:19 +0200
Subject: Using += in a loop
References:   <3d46d722.18669034@netnews.worldnet.att.net>
Message-ID: <3D46E333.4010407@ob_scure.dk>

Bill Dandreta wrote:
> Hi Alex,
> 
> On Sat, 27 Jul 2002 20:42:03 GMT, Alex Martelli 
> wrote:
> 
>>As a nice plus, it's also *WAY, WAY* faster.  A loop with += takes
>>O(N squared) time, joiner.join takes O(N) time, where N is the

[snip]

> I am using the following code structure in some very long (10's of
> thousands of iterations) loops.
> 
> Is there a more efficient way that doesn't use +=?
> 
> Would s5 = '%s,"%s"' % (s5,x[1]) be better?

Probably not (it would still have the O(N squared) charactaristics).
Instead try:

   s5_list = []
   for ...:
     s5_list.append(',"%s"' % x[1])

   s5 = ''.join(s5_list)

-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)



From johnmc at velseis.com.au  Thu Jul 11 01:41:37 2002
From: johnmc at velseis.com.au (John McMonagle)
Date: 10 Jul 2002 22:41:37 -0700
Subject: Pmw.Counter and Pmw.ScrolledCanvas questions
Message-ID: <18692175.0207102141.1d5279c1@posting.google.com>

My first question is to do with Pmw.Counter.  I am creating a
Pmw.Counter like so (see below code sample):

from Tkinter import *
import Pmw
r = Tk()

c = Pmw.Counter(r, labelpos=W, labelmargin=5, label_text='Two\nLines',
label_justify=LEFT, buttonaspect=1.2)
c.pack()
 

Because the label spans two text lines, the entryfield is also
expanded to this height.

Is it possible to set the height of the entry field so as to only
appear as a single line ?  Another way to say it is can the frame
component height and position be changed within the hull component ?

I have tried c.configure(frame_height=10) but the megawidget is just
redrawn the same.  I suspect the frame component is being expanded to
the height of the hull component.

My second question is to do with Pmw.ScrolledCanvas.  In my
application, I have a zoom drag feature.  The user can drag an area in
the canvas window using button-3-press-motion-release to define an
area to zoom.  I am able to do the zooming ok but how do you set where
the horizontal and vertical scrollbars are postioned.  I wish the user
to see at the top left of the scrolled canvas window the point at
which they started the drag.  I guess it's just for convenience sake
so the user does not have to scroll through to their desired point
after the zoom.


From aleax at aleax.it  Mon Jul  8 08:27:56 2002
From: aleax at aleax.it (Alex Martelli)
Date: Mon, 08 Jul 2002 12:27:56 GMT
Subject: PKSC1
References: 
Message-ID: 

Bo M. Maryniuck wrote:

> Hi all.
> 
> Somebody heard something about PKSC1 for Python? Very shortly: this is a
> signature operation stuff for banking.

Assuming you mean PKCS1 (as per RFC 2437), pisces supports it, see:

http://www.cnri.reston.va.us/software/pisces/manual/module-pisces.pkcs1.html


Alex



From yduppen at xs4all.nl  Tue Jul 30 15:12:32 2002
From: yduppen at xs4all.nl (Yigal Duppen)
Date: Tue, 30 Jul 2002 21:12:32 +0200
Subject: Using += in a loop
References:   <3d46d722.18669034@netnews.worldnet.att.net>
Message-ID: <3d46e4d4$0$94903$e4fe514c@dreader3.news.xs4all.nl>

> I am using the following code structure in some very long (10's of
> thousands of iterations) loops.
> Is there a more efficient way that doesn't use +=?

> Would s5 = '%s,"%s"' % (s5,x[1]) be better?
> 
> t = ()
> s5 = ''
> for i in range(0,5):
>   q = breaks[brk][i]
>   x = mkup(cost*q,list*q)
>   if x[0]: t+=(x[0]/q,)
>   else: t+=(0,)
>   if x[1]: s5+=',"'+x[1]+'"'
>   else: s5+=',"-"'
> t += (0,0)
> s5 += ',"-","-"'

Without exactly understanding what it does, here are some tips:

1) make t a list; this allows you to use 'append'. This is much faster since 
append works on an existing list.  +=  creates a new tuple 
every time.  +=  is quite efficient as well

2) make s a list as well, append all the strings you need, and join them in 
the end.


Something like this should be faster:

t_list = []
s5_list = []
for i in range(0, 5):
        q = breaks[break][i]
        x = mkup(cost * q, list * q)
        if x[0]:
                t_list.append(x[0]/q)
        else:
                t_list.append(0)
        
        if x[1]:
                s5_list += [ ',"' , x[1] , '"']
        else:
                s5_list.append(',"-"')
t_list += (0, 0)
s5_list.append(',"-","-"')

# and convert both lists to the desired types
t = tuple(t_list)
s5 = "".join(s5_list)


No clue how much faster; that's what profile is for.

YDD
-- 
.sigmentation fault


From fredrik at pythonware.com  Sun Jul 21 08:00:12 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sun, 21 Jul 2002 12:00:12 GMT
Subject: __del__ in classes derived from Tkinter classes
References:   
Message-ID: 

Petr Klyushkin wrote:

> So, when will Python object be destroyed?  Suppose, I have
> following code:
>
> def f():
>   test2 = Test()
> f()
>
> When will test2 (Python object! not a Tk widget it represents)
> be destroyed?

maybe when the function returns.  maybe somewhat later.
maybe when the interpreter exits.  possibly never at all.

>  Fredrik> (and using __del__ is usually bad style even outside
>  Fredrik> Tkinter, but that's another story).
>
> Why?

you don't know when they're called, you don't know if they're
called, and you don't know in what state the system is when
they are called.

for more info, search google for "finalizers are bad", or variations
thereof.






From steve.coates at virgin.net  Wed Jul 10 17:33:02 2002
From: steve.coates at virgin.net (Steve Coates)
Date: Wed, 10 Jul 2002 22:33:02 +0100
Subject: List assignment, unexpected result
References: 
Message-ID: 

Thanks for the help. I think my favourite solution was

grid = [['.' * 4] for i in range(4)]

but I'll need to read up on the syntax. I haven't seen this
use of a for loop before.

Steve Coates




From michael.grabietz at img-online.de  Sun Jul 21 14:45:52 2002
From: michael.grabietz at img-online.de (Michael Grabietz)
Date: Sun, 21 Jul 2002 20:45:52 +0200
Subject: Calling a python function with a list as the input argument from C
Message-ID: <3D3B0160.9090800@img-online.de>

Hello,

I tried the example given in the Python documentation calling Python 
from C. In this example the input argument of the python function is a 
tuple. See the code below which works fine.


----------------------------------------------------------------
Calling Python function with pArgs as tuple:  That works fine !
--------------------------------------------

     Py_Initialize();                      // Init Python Interpreter
     pName = PyString_FromString(ModuleName);
     pModule = PyImport_Import(pName);       // Import module
     pDict = PyModule_GetDict(pModule);
     pFunc = PyDict_GetItemString(pDict, FunctionName);
     pArgs = PyTuple_New(inp_vec_n);
     for (i = 0; i < inp_vec_n; ++i) {
          pValue = PyFloat_FromDouble( inp_vec[i] );
          PyTuple_SetItem(pArgs, i, pValue);         }

     pValue = PyObject_CallObject(pFunc, pArgs); // Calling Python
----------------------------------------------------------------


----------------------------------------------------------------
Calling Python function with pArgs as a list:  That fails !
---------------------------------------------

Now something I do not understand. I want to call a python function with 
a list as an input argument. I modified the code above to the following.

     Py_Initialize();
     pName = PyString_FromString(ModuleName);
     pModule = PyImport_Import(pName);
     pDict = PyModule_GetDict(pModule);
     pFunc = PyDict_GetItemString(pDict, FunctionName);
//    pArgs = PyTuple_New(inp_vec_n);
     pArgs = PyList_New(inp_vec_n);
     for (i = 0; i < inp_vec_n; ++i) {
          pValue = PyFloat_FromDouble( inp_vec[i] );
//         PyTuple_SetItem(pArgs, i, pValue);
          PyList_SetItem(pArgs, i, pValue);     }

//    pValue = PyObject_CallObject(pFunc, pArgs);
     pValue = PyObject_CallObject(pFunc, pArgs); // Now calling with List
----------------------------------------------------------------


I suppose using 'PyObject_CallObject' is not the right choice. I read 
already in the doc that it expects pArgs as atuple. But what do I have 
to use if I need to pass a list. Further I want to extent it to feed a 
python function with a vector from NumPy as an input argument. Is that 
possible or do I have to stay with tuples ?


Thanks for your efforts and help,

Michael



From jonathan at onegoodidea.com  Wed Jul 31 07:56:02 2002
From: jonathan at onegoodidea.com (Jonathan Hogg)
Date: Wed, 31 Jul 2002 12:56:02 +0100
Subject: beginner's question
References: <66o19.694966$352.150300@sccrnsc02>  
Message-ID: 

On 31/7/2002 7:33, in article CwL19.194575$Wt3.153780 at rwcrnsc53, "jano"
 wrote:

> Hmm, thanks for your help.  I did as you suggested.  I do have 2 versions
> installed, but verified that it was running the correct version (1 is 2.1
> under cygwin, and the other is 2.2 under win2k), and it was running 2.1 as
> is correct.  And checking sys.path shows that the directory that contains Ft
> (/usr/lib/python2.1/site-packages) is in the path.  Any other suggestions?

Hmmm... It really looks like it's running the wrong one.

I'd find the script that's failing and run it explicitly with the right
Python. So something along the lines of:

-----
% cd path/to/test/script
% which python
/usr/bin/python
% python
Python 2.1 (etc etc etc)
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path 
['/usr/local/lib/python2.1', '/usr/lib/python2.1/site-packages']
>>> import Ft
>>> Ft.__file__
'/usr/lib/python2.1/site-packages/Ft/__init__.pyc'
>>> ^D
% python test.py
....
-----

Try this out and cut-n-paste us the results.

Jonathan



From martin at v.loewis.de  Tue Jul  9 03:08:58 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 09 Jul 2002 09:08:58 +0200
Subject: Unicode utf-8 doesn't do back-and-forth?
References:  
Message-ID: 

sjmachin at lexicon.net (John Machin) writes:

> 4 more bits? It needs 21 bits to encode the 2**20 possible
> surrogate-described characters plus the basic 64K characters.
> assert 21 - 16 == 5

Not really. This makes a total of 2**20+2**16 = 1114112
characters. Now, math.log(1114112)/math.log(2) is 20.087462841250343,
so it is rather 4.09 additional bits.

Regards,
Martin



From never at mind.info  Fri Jul 19 07:31:54 2002
From: never at mind.info (G. Willoughby)
Date: Fri, 19 Jul 2002 12:31:54 +0100
Subject: Calling Fredrik Lundh, (dare i ask) Guido, all other Guru's, could this be a bug?
References:  
Message-ID: 

with this code:

from Tkinter import *
class mainApplication:
 def __init__(self, master):
  self.menubar = Menu(master)
  self.filemenu = Menu(self.menubar, tearoff=0)
  self.filemenu.add_command(label="Exit", command=master.quit)
  self.menubar.add_cascade(label="File", menu=self.filemenu)
  master.config(menu=self.menubar)
root=Tk()
app=mainApplication(root)
root.mainloop()

 i get this error when i choose 'Exit' from the 'File' menu!   :(

'The instruction at "0x00d5a0a3" referenced memory at "0x00000008". The
memory could not be "read".'

as you can see no third party imports are made. Another question, how do i
go about getting a debug version of python to run this in on WinXP?

--G. Willoughby





From shagshag13 at yahoo.fr  Fri Jul  5 04:24:07 2002
From: shagshag13 at yahoo.fr (Shagshag13)
Date: Fri, 5 Jul 2002 10:24:07 +0200
Subject: Memory ?
References:  <3D2551B7.30206@mxm.dk>
Message-ID: 

"Max M"  a ?crit dans le message de news: 3D2551B7.30206 at mxm.dk...
> Shagshag13 wrote:
> > Hello,
> >
> > i'm still looking for a way to check which are the best ways to save memory because i work on many GB with float, etc. so is
there a
> > way to check how many bytes needs an object, a tuple, a list, a dict of objects and so on ? (something like itemsize for array -
in
> > fact array should be great if they weren't boxed)
>
>
> With no kind of authority I would guess that Numpy is what you need.
>
> http://sourceforge.net/projects/numpy
>
> regards Max M

Thanks ! But i already look at it, and it looks like it's only for boxed array (or do i miss something ?)... mine aren't (might be
between <5 and anything > 300,000 - can't guess upper bound) and they don't all contain floats, but also chars.

And i would like to know how to check for size of var.

s13.




From mgerrans at mindspring.com  Wed Jul 10 01:55:44 2002
From: mgerrans at mindspring.com (Matt Gerrans)
Date: Tue, 9 Jul 2002 22:55:44 -0700
Subject: j2ee vs. python (and what our evil competitors are saying about python)
References:  <96c7f32.0207091153.7b2484be@posting.google.com>
Message-ID: 

> There are two basically, one is clockware and the other is timewizard.
> I don't like to give them publicity at all, even bad publicity.

Okay!   Now we can call up their sales people and ask them why they haven't
implemented their technology in Python.   Are their developers masochistic
or something?




From Ch_Bennemann at web.de  Fri Jul 19 03:49:51 2002
From: Ch_Bennemann at web.de (Christoph Bennemann)
Date: 19 Jul 2002 00:49:51 -0700
Subject: C-API question: Memory returned by PyString_AsString
Message-ID: <2379a09f.0207182349.58a98350@posting.google.com>

Hello,

functions like PyString_AsString return a pointer to a character
vector. Is this memory specially allocated when I call this function
(which implies I have to take care of it in my program) or is this
merely a pointer to a character vector stored by the Python
interpreter (implying that I should not free the memory). I assume
that the later is correct, but would like to have a definitive answer.

Thanks in advance,

Christoph

Dr. Christoph Bennemann
d-fine Gmbh
Germany


From fredrik at pythonware.com  Wed Jul 24 14:11:27 2002
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Wed, 24 Jul 2002 18:11:27 GMT
Subject: xml processing : too slow...
References:     
Message-ID: 

"Shagshag13"

> * check well formedness
> * process each line which are like this:
>  1 2 3
> -> to have:
> ['', '', '1', '2', '', '', '3', '', '']

from xml.parsers import expat
parser = expat.ParserCreate(None, None)

import re
p = re.compile("<[^>]*>|\d+")

for line in file:
    # check wellformedness
    parser.Parse(line, 0)
    # split into parts
    print p.findall()

# check for trailing junk
parser.Parse("", 1)






From aleax at aleax.it  Wed Jul 24 03:48:47 2002
From: aleax at aleax.it (Alex Martelli)
Date: Wed, 24 Jul 2002 07:48:47 GMT
Subject: Python Cookbook (was Re: good books)
References:  <3D3DD5B4.5080507@aon.at>
Message-ID: 

Gregor Lingl wrote:
        ...
> Percy Tambunan schrieb:
>> what is a good book in python, If i can only afford to buy just one book?
        ...
> ... or perhaps we should stick with online ressources until we
> can see what martellibot will be giving to us

Thanks!  I think you might like to have a look at what martellibot
HAS given to you together with David Ascher, Guido van Rossum, Tim
Peters, Fred Drake, Mark Lutz, Greg Wilson, Donn Cave, Aaron Watters,
Fredrik Lundh, Andy McKay, Paul Prescod, Jeremy Hylton, Mark Hammond,
Paul Dubois, David Beazley AND another 100+ contributors (sorry folks
if I'm not listing you all...!!!) in the Python Cookbook, which I
believe has already been officially launched at OSCON.


The above list meets the order in which we all are first met in the
book, by the way.  I and David are on the cover, Guido wrote a
Foreword, and each of these 3 plus all of the others above wrote
a chapter-introduction each.  The 100+ authors wrote recipes which
David and I, with some help from chapter intros' authors, selected
and edited and completed with recipes addressing some issues that
had not been covered in online submissions.


Have a look at the sample online chapter:

http://www.oreilly.com/catalog/pythoncook/chapter/ch01.pdf

(780KB).  Just 17 recipes, and somewhat of a mixed bag since
Chapter 1 is where we put idioms &c that didn't really fit in
other, more task-focused chapters, but still interesting, I think.


This is really the book the Python community wrote.  And the Python
community comprises an awful LOT of very bright people.  I hope I
and David were up to the anything-but-easy task of keeping the many
individual "voices" distinct and recognizable, while editing and
smoothing things enough to make the book just as readable, and at
least as useful, as if it had a single author rather than many
dozens of them.  I think we made it, but, it's YOUR opinion that
counts, of course, not mine -- so, have a look, and let us know!


Alex



From paul at svensson.org  Sun Jul 14 05:36:47 2002
From: paul at svensson.org (Paul Svensson)
Date: Sun, 14 Jul 2002 09:36:47 +0000 (UTC)
Subject: No, loop-and-a-half! (Re: REPEAT... UNTIL ?)
References:  <3D2487CB.9000102@gmx.de> <3D24FAC5.3050406@something.invalid> 
Message-ID: 

bellman at lysator.liu.se (Thomas Bellman) writes:

>Greg Ewing  wrote:
>
>> On the other hand, a situation that *is* very common is
>> a loop-and-a-half, with the exit condition in the middle.
>> So far, I've never seen *any* really good loop-and-a-half
>> structure in any language, and I think Python has a chance
>> to be truly innovative here.
>
>As others have already said, iterators can sometimes alleviate
>this problem.
>
>And there is *one* language where I think the structure for
>loop-and-a-half *is* good: Forth.  The syntax goes something
>like

 (---)

Bourne Shell also has

        while
                foo
                bar
                gazonk ?
        do
                gurka
        done

>I *would* have liked that to be
>
>    repeat:
>       part_1()
>    while test_1():
>       part_2()
>    while test_2():
>       part_3()
>    while test_3():
>       part_4()
>
>in Python, but that is unfortunately not compatible with the
>current Python syntax. :-(

The problem is that there's no indication where the repeat: block ends.
If we should invent new syntax, I would limit it to the loop-and-a-half,
and keep "break" for multiple exit loops.

    repeat:
        part_1()
    while test_1():
        part_2()

This is unambigous to the compiler, but not could be confusing to humans,
specially if part_1() is large.  Adding more new keywords makes it clearer:

    repeat:
        part_1()
    until not test_1():
        part_2()

Or, inspired by Bourne, with no new keywordss at all (and even more cryptic):

    while:
        part_1()
        test_1():
            part_2()

I don't see anything like this happening anytime soon.

        /Paul


From skip at pobox.com  Fri Jul 26 21:02:22 2002
From: skip at pobox.com (Skip Montanaro)
Date: Fri, 26 Jul 2002 20:02:22 -0500
Subject: Two RE proposals
In-Reply-To: 
References: <15681.49362.442164.660697@12-248-11-90.client.attbi.com>
        
Message-ID: <15681.61726.4250.930338@12-248-11-90.client.attbi.com>

    >> How about
    >> 
    >> word = r"\w*"
    >> punct = r"[,.;?]"
    >> wordpunct = re.compile(r"%(word)s%(punct)s" % locals())
    >> 
    >> which you can do today?  (I'd also argue that a word would be "\w+".)

    David> I considered something like this, but it's too verbose, not to
    David> mention confusing - what's inherently wrong with my idea? 

Nothing I suppose, except someone has to write the code to implement it,
while the proposal I put forth exists today.  As for verbosity, "!"
saves precisely one character over "%(word)s".  I'll grant you the "%
locals()" adds a few more characters, but it's a constant factor.

I don't understand how a basic facility of the language that has been around
for God knows how long could be more confusing than writing regular
expressions. 

    David> I am not familiar with the idiom of "locals()".)

>From the online help:

    Help on built-in function locals:

    locals(...)
        locals() -> dictionary

        Return the dictionary containing the current scope's local variables.

    >> The * doesn't (and shouldn't) operate over grouping parens.  You're
    >> asking it to supply you with a variable number of groups, which it
    >> can't do.

    David> You're right - it doesn't operate over grouping parens, but why
    David> _shouldn't_ it? IIRC, _some_ regex pacakges could do this...

How about using non-grouping parens:

    >>> pat = re.compile(r"((?:a|b)*)")
    >>> pat.match("ababaaaabccdabab")
    <_sre.SRE_Match object at 0x40348ea0>
    >>> _.group(1)
    'ababaaaab'

Skip



From martin at v.loewis.de  Tue Jul 30 02:32:22 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 30 Jul 2002 08:32:22 +0200
Subject: global interpreter lock not working as it should
In-Reply-To: <200207292348.TAA31011@test-area.com>
References: 
	
	<200207292348.TAA31011@test-area.com>
Message-ID: 

anton wilson  writes:

> The reason your code works is because you explicitly give up the CPU
> with the sleep calls. If you remove both time.sleep calls the results will 
> look like:

I see. Now, I take the modified script

import threading, time

def func1():
    for i in range(10):
        for k in range(10):
            pass
        print "FUNC1"

def func2():
    for i in range(10):
        for k in range(10):
            pass
        print "FUNC2"

t = threading.Thread(target=func1)
t.start()
func2()

This has no explicitly-blocking calls, and prints

FUNC2
FUNC2
FUNC1
FUNC2
FUNC1
FUNC2
FUNC1
FUNC2
FUNC1
FUNC2
FUNC2
FUNC2
FUNC2
FUNC2
FUNC1
FUNC1
FUNC1
FUNC1
FUNC1
FUNC1

So I still can't see your problem.

Regards,
Martin



From K.Rdt at TU-Berlin.DE  Wed Jul  3 14:16:26 2002
From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt)
Date: Wed, 03 Jul 2002 20:16:26 +0200
Subject: HT clear some wxPython fram?
In-Reply-To: <20020703110607.00c02458.logiplexsoftware@earthlink.net>
Message-ID: <461DRL43N61JI74JFGC71HG43FEJG.3d233f7a@FRITZweb>

Am 03.07.02 20:06:07, schrieb Cliff Wells :

>On Wed, 03 Jul 2002 19:39:04 +0200
>Klaus Reinhardt wrote:
>
>> >> HOW I CAN CLEAR SOME FRAME?
>What do you want to clear from the frame?  You've put nothing into it.  I think
>you are confusing the stdout window with the frame.  If you notice, when you
>run your program, two windows open.  The first one with the title "Close me" is
>the frame.  The second window titled "wxPython stdout/stderr" is not the frame.
> I could be wrong, but I don't think there's any way to control the
>stdout/stderr window.  It's mostly for debugging purposes.
>
>What you will want to do instead is something more like this:

---------------------------------------------------------------------
Hi
I will try this (here cut).
BUT: 

Aktive Verbindungen

  Proto  Lokale Adresse         Remote-Adresse            Status
  TCP    0.0.0.0:1117           0.0.0.0:0              LISTENING
  TCP    127.0.0.1:4711         0.0.0.0:0              LISTENING
  TCP    217.81.119.164:1117    130.149.5.227:22       ESTABLISHED

This is shown in the "wxPython stdout/stderr"-frame.
(I'm a completely newby to python and OOP)

 
		K at Rdt
---------------------------------------------------------------------







From jonathan at onegoodidea.com  Sun Jul 21 13:24:06 2002
From: jonathan at onegoodidea.com (Jonathan Hogg)
Date: Sun, 21 Jul 2002 18:24:06 +0100
Subject: memory freeing
References: 
Message-ID: 

On 21/7/2002 17:08, in article
ced73313.0207210808.23b585b9 at posting.google.com, "Peter Saffrey"
 wrote:

> I set up a loop to assign "None" values into all the reachable_from
> hashes, but the memory displayed by my system monitor (gkrellm) does
> not seem to indicate that I've gained any memory. Do I need to do
> anything more specific to order Python to return this memory to me?
> Obviously many of the routes have shared parts, but I use the
> concatenate (+) operator when building the lists, and I thought this
> generated new list copies. Apart from anything else, each hash and the
> pointers to the lists of lists should be separate objects, and just
> removing these ought to give me a few megabytes, but I don't seem to
> be getting any at all.

Assuming the objects really are being deallocated (a good way to test this
with a recent Python with garbage collection is:

>>> import gc
>>> len( gc.get_objects() )
1223
>>> foo = [(x,y) for x in range(100) for y in range(100)]
>>> len( gc.get_objects() )
11224
>>> del foo
>>> len( gc.get_objects() )
1223
>>> 

which shows the number of allocated container objects) then the answer is
probably that your particular combination of pymalloc/malloc/sbrk/whatever
is not necessarily returning the memory to the OS.

This doesn't mean that it's not been deallocated. There's a whole
complicated hierarchy of memory allocation mechanisms in play (object
freelists, pymalloc, malloc, etc.) and the memory might not have bubbled all
the way back. You'll likely find that it has been returned to your Python
program so you can allocate more stuff without increasing the process VM
size any further.

Since the memory is no longer being actively used the VM system will slowly
reclaim it (by paging it out as it ages).

You can test this hypothesis by allocating big lumps of objects at the
Python prompt then del'ing them and watching the process memory stats. On my
machine, for instance, I get behaviour like so (with Python 2.3 from CVS on
Mac OS X):

>>> 
# RSIZE=1.63M, VSIZE=5.38M
>>> foo = [(x,y) for x in range(1000) for y in range(1000)]
# RSIZE=50.8M, VSIZE=58.5M
>>> del foo
# RSIZE=50.7M, VSIZE=54.7M
>>> bar = [(x,y) for x in range(1000) for y in range(1000)]
# RSIZE=50.8M, VSIZE=58.5M
>>> del bar
# RSIZE=50.7M, VSIZE=54.6M
>>> # leave Python in the background for a while doing nothing much
# RSIZE=692K, VSIZE=54.8M

which is pretty normal.

Jonathan



From shagshag13 at yahoo.fr  Fri Jul 26 07:42:14 2002
From: shagshag13 at yahoo.fr (Shagshag13)
Date: Fri, 26 Jul 2002 13:42:14 +0200
Subject: extract elements of n char from a list
Message-ID: 

hello,

i want to efficiently extract elements of n char from a list :

n = 2
l = ['this', 'is', 'an', 'example']
nl = []
for i in l:
    if len(i) == n:
        nl.append(i)

nl = ['is', 'an']

but i think that some clever guru could use a map() / reduce() or something like that to speed up the process (which is what i
really need...)

thanks for your help,

s13.




From jepler at unpythonic.net  Thu Jul 18 16:45:30 2002
From: jepler at unpythonic.net (Jeff Epler)
Date: Thu, 18 Jul 2002 15:45:30 -0500
Subject: Exploit for a security hole in the pickle module for Python versions <= 2.1.x
In-Reply-To: 
References:  
Message-ID: <20020718204529.GB8162@unpythonic.net>

On Thu, Jul 18, 2002 at 09:07:53PM +0200, Dieter Maurer wrote:
> Jeff Epler  writes on Wed, 17 Jul 2002 07:47:14 -0500:
> > Exploit for a security hole in the pickle module for Python versions <= 2.1.x
> Thank you for the precise problem statement!
> > ...
> > Because a "class constructor" is
> > simply a callable object,
> > a pickle can be written that names any function
> > and gives it arbitrary arguments.
> But this need not be the case!
> 
>    A "class constructor" is quite a special "function".
>    Its "type" is "ClassType" (at least until Python 2.2).

This test would "work" against the exploit I posted.  However, this test
is not implemented in any version of Python.  Furthermore, there are
classes which are unsafe to instantiate.  For instance, popen2.Popen3
is as dangerous a constructor as os.system is a function.

>>> type(popen2.Popen3)


That's the reason the "safe for unpickling" requirement was added.

Jeff




From jb at cascade-sys.com  Tue Jul  9 23:57:30 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Tue, 09 Jul 2002 20:57:30 -0700
Subject: COCOMO - appropriate for languages like Python?
References: <15655.16377.250899.348691@localhost.localdomain>  <7934d084.0207091746.3ec0f89a@posting.google.com>
Message-ID: <3D2BB0AA.B2DDF1A1@cascade-sys.com>

Andrae Muys wrote:

> "James J. Besemer"  wrote in message news:...
> > From a management standpoint, your strategy should be to always strive to hire
> > the very best people and to break projects into moderate sized, easily handled
> > chunks.
> >
> > From a schedule estimation standpoint, LOC (however you choose to count them)
> > appears to be a pretty good estimator to use for a fixed staff and fixed project
> > sizes.  How the prediction varies as you change staff or project sizes is
> > something you'll have to measure or guess at yourself.  At least COCOMO research
> > gives you some idea how the curves are shaped.
> >
>
> Do you have any references where I could follow up on this myself?

The quoted exerpts above are merely my humble opinions, based on many many years of software development and software
development management.

If you google.search( COCOMO ) you get lots of references to past and ongoing work.

If you amazon.books.search( COCOMO ) I see there's now a COCOMO II.

This looks like a substantial update to Boehm's seminal Blue book on Software Engineering Economics.

Either of the above are good as any starting point.

Regards

--jb


--
James J. Besemer  503-280-0838 voice
http://cascade-sys.com  503-280-0375 fax
mailto:jb at cascade-sys.com






From anthony at interlink.com.au  Mon Jul  8 20:20:44 2002
From: anthony at interlink.com.au (Anthony Baxter)
Date: Tue, 09 Jul 2002 10:20:44 +1000
Subject: j2ee vs. python (and what our evil competitors are saying about python) 
In-Reply-To: <1026171328.15295.2.camel@jwilhelm.ofsloans.com> 
Message-ID: <200207090020.g690Kmj04506@localhost.localdomain>

On the plus side, if these people are your competitors, they're obviously
so completely stupid that you should be able to easily put them away.

I think you need to name and shame these morons. 

Some fun can be had tearing them apart - ah hell with it, it's fun.


> Summary
> Python is often used as pseudocode to conduct rapid development. 

Yep, pseudocode is all it is. Man, I'm glad I've got that 12K or so
lines of pseudocode to rewrite in a Real Man's Language. 

> Its
> major users are web sites that do not reuse code and often conduct
> “throw away” development to meet internet development time
> tables. 

What a complete and utter load of shite.

> It is a very new language and has very little support compared
> to the Java development community. 

Erm. Python 1.0 release date? Java 1.0 release date?

> It is also not J2EE compliant.

Shock. Horror. It is also not:

Visual Basic.
Fire retardent.
A small fluffy bunny.

> Platform Drawbacks
> As a new relatively untested development platform in the licensed
> software community, Python has certain deficiencies with which all
> users and developers should be aware.

Unlike, say, Java. Sorry, _which_ JVM were you using? Oh, that feature
only works on a different JVM.

Or C++. Man, I _hate_ it how every time I move to a new platform, I
don't have to spend days fighting compilers, or fscking around with
header file. It means I get to do productive work.

>  Issues and concerns 
 
> ?         No integrated GUI (Graphic user interface) support.

Yeah. Where's my AWT in python, dammit! I _demand_ a crappy windowing
toolkit that makes all my applications go slow.

> ?         No compiler to the native code.

And?

> ?         No automatic garbage collection.

2.0. So it's only over a year out of date.


> ?         Does not have vast number of libraries as that of Java,
> Perl, C++; etc.

And, unlike Perl it doesn't have a vast number of multiple
implementations of every single possible interesting library. 
Worse yet, python actually ships with libraries that are debugged
with test cases and documentation. And sometimes you can even 
use a library without having to download 14 other different packages
and the latest minor point release of the core language.

> ?         Since Python is an interpreted language, it requires
> frequent run-time checks and thus does not provide the speed,
> performance and efficiency of compiled languages like Java, Perl and
> C++, which is a major issue.

I think the inclusion of 'Perl' here says a large amount about the 
clue level of the author of this piece.

> ?         Python does not provide multiple ways to perform tasks as do
> most other languages.

You know, you're right! I _demand_ Guido add 14 new ways to spell

if option1 or option2: 
   do_stuff()
   do_stuff2()

preferably using some form of obscure punctuation based source code markup
to denote structure. Of course, to prove what l33t c0derZ we all are, the
markup should work most of the time even if you get it subtly wrong.

> ?         It takes a lot of time for Python to adjust to the
> indentation style of the structuring code.

Hours, at least.

Compared to the days required to adjust to the mind-warping horror of a 
new C++ compiler release.

> ?         Since Python is relatively a new language, there are only a
> few resources available for information on its latest developments.

*snicker* 

> ?         Limited documentation- only two English language books exist
> which provide tutorials or a library reference for Python.

First website I tried (barnes&noble)

Computers: Programming Languages: Python
Below are 1 - 25 of the 27 titles sorted in bestselling order.

> ?         The language is restricted to fewer code modules.

I don't even know what this means.

> ?         Lacks native threading capabilities.

Threading support first appeared in 0.9.7, around late 1992. The 
threading support of python uses the OS, rather than trying to implement
it's own. This means you can actually port python to new platforms without
having to sacrifice a child to an elder god to get threading to work.

> ?         Lacks basic tools such as integrated source level debuggers.

Again, complete nonsense, as there's several of these.

> ?         No packaging methods for software distribution.

Woo. Greg Ward's going to be upset that all that time he spent on distutils
obviously didn't produce anything. Or, more seriously, see every release
since 1.6.

> ?         Lacks tools to solve typographical and type mismatch classes
> of errors.

pychecker. or write a decent test suite. Oops, sorry, this breaks the 
whole "it compiled, didn't it - ship!" mindset.

> ?         Python cannot write docstrings in C++.

Again, I don't know what this means.

> ?         Python is difficult to read.

????? This is probably my favourite one of the lot. Obviously this person
finds C++, Java and Perl to be the peak of readability. I assume they'd
also be right in with the APL crowd.

> ?         Dynamic loading is not available on all systems, requiring
> that a developer use static loading.

Java is not available on all systems at all, requiring that a developer
use a better language.

> Application Areas
> ?         Prototyping and development
> ?         Platform independent graphic user interface applications
> ?         Internet scripting/applications
> ?         Automated test harnesses
> ?         System administration applications
> ?         Shell scripting/OS Scripting
> ?         Text processing
> ?         Database Interfaces
> ?         Application Extensions
> ?         Distributed Programming

So what's this list? a bunch of features of python?


> Python users
> ?         Yahoo
> ?         Infoseek

mm. that'd be the only people to use it, too. no-one else does, ever.
Those wacky """web sites that do not reuse code and often conduct
"throw away" development to meet internet development time tables."""

Anthony




From tim.one at comcast.net  Tue Jul 30 16:59:28 2002
From: tim.one at comcast.net (Tim Peters)
Date: Tue, 30 Jul 2002 16:59:28 -0400
Subject: global interpreter lock not working as it should
In-Reply-To: <200207301708.NAA03182@test-area.com>
Message-ID: 

[anton wilson]
> ...
> What's the purpose of releasing an reaquiring the lock if no
> other threads can run?

They can, as other responses have amply demonstrated.  Whether they *will*
is up to the platform thread package, which was presumably designed to pass
out timeslices in a way maximally efficient for it.  It's not Python's job
to force thread switches against the better judgment of the thread facility
authors; you can do that yourself if you think it's required, e.g. via
time.sleep(0.001).

A peculiar thing here is that "the Python lock" is an abstraction.  You said
you were running on Linux, and "the Python lock" isn't a lock there.  In
Pythons released to date, a Python lock under pthreads is a combination of a
phtreads mutex never held across more than a few C instructions, and a
pthreads condition variable.  When "the lock" is released, a condvar signal
is done to notify some other thread that it can grab the lock.  This happens
before the relinquishing thread tries to reacquire the lock.  So the
implementation of condition variables on your box apparently decides not to
take action on a signal at once, dallying until the original thread has
already reacquired "the lock".  That's fine -- it's allowed to do that, and
it surely has its own performance reasons for doing so.

If you try the current CVS version of Python, the implementation of "the
lock" on Linux has changed to use POSIX semaphores instead.  They may or may
not act more like you hope -- I don't know (haven't tried it).  It seems
possible that they might, since semaphores came out of the POSIX realtime
extensions, where people feel much freer to make unreasonable 
demands.

> ...
> I have a feeling that there is a hidden race condition between when the
> thread wakes up the other thread and tries to reaquire the lock.

"The race" would be in the platform implementation of pthread_cond_signal(),
but I expect that's working the way its author intended.




From karaatanasov at hotmail.com  Fri Jul 19 17:06:17 2002
From: karaatanasov at hotmail.com (Kiril Karaatanasov)
Date: 19 Jul 2002 14:06:17 -0700
Subject: Recursion
References: 	<20020719083105.5c01b6a4.christophe.delord@free.fr>	<71a1c515.0207190408.ee0e943@posting.google.com> <20020719165614.77b721d9.christophe.delord@free.fr>
Message-ID: <71a1c515.0207191306.655f94b8@posting.google.com>

> bits = lambda x,f=lambda y,g:(y>1 and g(y>>1,g) or "")+"01"[y&1]:f(x,f)

Right that is awesome in some peculiar and hard to understand way. But
Python is so much better then perl in one thing making readable code,
sure one can obscure it, but really there is no need to.

I also do admit that most french people (programmers) I know are quite
smart indeed.


From remi at cherrypy.org  Wed Jul 17 05:40:13 2002
From: remi at cherrypy.org (Remi Delon)
Date: 17 Jul 2002 02:40:13 -0700
Subject: ANN: CherryPy-0.3 released
Message-ID: <585c0de9.0207170140.19f43f71@posting.google.com>

We're pleased to announce the release of CherryPy-0.3.

This release doesn't add any new feature, but the documentation and
the demo have been greatly improved:
- CherryPy Standard Library documentation is now available
- A new demo entry has been added: it illustrates how to use OOP to
develop a web site with CherryPy


------------------------------------------
About CherryPy:

CherryPy is a Python-based tool for developing dynamic websites. It
uses many powerful concepts together, which makes it unique in its
approach to website development.
CherryPy sits between an application server and a compiler. You write
source files, compile them with CherryPy and CherryPy generates an
executable containing everything to run the website (including an HTTP
server).

CherryPy has been used in production for more than 6 months are we are
now releasing it to the public, under the GPL license.
Key properties/features of CherryPy are: 
   - Based exclusively on Python (runs everywhere Python runs) 
   - Delivers fast, robust, and scalable websites 
   - Uses OOP as well as AOP (Aspect Oriented Programming) concepts to
develop websites
   - True separation of content and presentation 
   - Simple but powerful templating language 
   - Powerful standard libraries to make your life easy

Other properties/features are: 
   - Can be linked to many databases (Oracle, Sybase, MySql,
PostgreSql, ...)
   - Can run behind another webserver (Apache, ...) 
   - Easy clustering and load-balancing set up for high-traffic
websites

Remi.

http://www.cherrypy.org


From CousinStanley at HotMail.com  Sat Jul 13 12:44:10 2002
From: CousinStanley at HotMail.com (Cousin Stanley)
Date: Sat, 13 Jul 2002 09:44:10 -0700
Subject: pyCard_turtleTimes
References:   
Message-ID: 

Kevin ... 

Thanks for the reply ... 

Your suggestion to turn off  Auto-Refresh  made a  HUGE  difference 
and it would probably help others to include that suggestion in the sample docs ... 

You might reconsider giving the  turtle  samples a bit of a higher profile 
since  turtle-izing  is such a  SIMPLE  method for plotting and should be
especially attractive to novice programmers ... 

Cousin Stanley



From wurmy at earthlink.net  Wed Jul 31 18:18:26 2002
From: wurmy at earthlink.net (Hans Nowak)
Date: Wed, 31 Jul 2002 22:18:26 GMT
Subject: re.search question
References: <3mmgkucn8ga1klgrchkmfifkig9i1r4sse@4ax.com>
Message-ID: <3D486229.1080702@earthlink.net>

michaelian ennis wrote:

> How would I tell python to give me all the text in a string which
> falls between  the first instance of "!" alone on a line and the first
> instance of "end" alone on a line inclusively?
> 
> 
> lines=
> junk 
> !
> important stuff
> end
> more junk
> 
> 
> to 
> 
> cleaned_lines=
> !
> important stuff
> end

 >>> s = """\
junk
!
important stuff
end
more junk
"""
 >>>
 >>> import re
 >>> re_spam = re.compile("^!$(.*?)^end$", re.DOTALL|re.MULTILINE)
 >>> m = re_spam.search(s)
 >>> m
<_sre.SRE_Match object at 0x00770FB8>
 >>> m.group(1)
'\nimportant stuff\n'

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/



From phr-n2002b at NOSPAMnightsong.com  Sun Jul  7 00:39:37 2002
From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin)
Date: 06 Jul 2002 21:39:37 -0700
Subject: Using Python for processing of large datasets (convincing managment)
References: <3D27152C.8020108@obscure.dk.X>
Message-ID: <7x4rfcf8xi.fsf@ruckus.brouhaha.com>

Depending on what kind of computation you're doing on that dataset,
Python may not give you the speed you need.  It has big advantages over
C/C++ for development speed and program maintainability, but the ugly
truth is that the interpreter is pretty slow.

You may be best off with a hybrid approach, writing the control
structure of your program in Python but the inner computational loops
in C, called through the Python-to-C API or through SWIG.  These have
a bit more learning curve than programming in pure Python, but will
let you get at the performance of C code when you need it.


From andreas at kostyrka.priv.at  Wed Jul 24 10:41:18 2002
From: andreas at kostyrka.priv.at (Andreas Kostyrka)
Date: 24 Jul 2002 16:41:18 +0200
Subject: get a list printed in hexadecimal notation
In-Reply-To: 
References: 
	 
	  
	
Message-ID: <1027422480.4164.58.camel@vaio2>

Am Fre, 2002-07-19 um 08.19 schrieb Oliver Eichler:
> Bengt Richter wrote:
> 
> >  >>> l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)
> >          ^                                   ^^^^^                   ^
> >  >>> print  [isinstance(x,int) and hex(x) or x for x in l]
> >  ['spam', '0xa', '0xf', 'more spam', ['nested', 65535, 'spam'], 'spam',
> >  ['0xff']
> 
> I never do such complicated things at home ;) But you are right for more 
> complex lists the one liner won't fit.
Well it's not efficient, but:
hexlist=lambda l: [(isinstance(y,list) and hexlist(y)) or y for y in
[isinstance(x,int) and hex(x) or x for x in l]]
l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)
print hexlist(l)

gives:
['spam', '0xa', '0xf', 'more spam', ['nested', '0xffff', 'spam'],
'spam', '0xff']

Andreas




From lac at strakt.com  Wed Jul 10 11:15:58 2002
From: lac at strakt.com (Laura Creighton)
Date: Wed, 10 Jul 2002 17:15:58 +0200
Subject: j2ee vs. python (and what our evil competitors are saying about python) 
In-Reply-To: Message from Michael Chermside  
   of "Wed, 10 Jul 2002 10:47:07 EDT." <3D2C48EB.3060301@destiny.com> 
References: <3D2C48EB.3060301@destiny.com> 
Message-ID: <200207101515.g6AFFwci021767@ratthing-b246.strakt.com>

> This is a cryptographically signed message in MIME format.
> 
> --------------ms020109020808020407080404
> Content-Type: text/plain; charset=us-ascii; format=flowed
> Content-Transfer-Encoding: 7bit
> 
> curt finch writes:
> > Our rebuttal (based on some of your comments) is here:
> >  
> > http://www.journyx.com/pdf/PythonAtAGlance.pdf
> 
> Great job, actually -- that's nicely written. I'd like to echo Terry 
> Reedy's suggestion that you (if willing) release this for general use i
> n 
> Python advocacy.
> 
> While I'm at it, is there anyone willing to donate web and/or wiki spac
> e 
> for Python advocacy? As far as I can tell, "Starship Python" is no 
> longer taking new members, and I have some advocacy materials I am 
> collecting and trying to post. I just need a place to host it (and of 
> course lots more well-written content like curt finch's).
> 
> -- Michael Chermside
> 

Stephan Diebel is at www.pythonology.com.  The Python Business
Forum intends to cross-reference this and include some of its
own material.  The PBF Build-Our-Website sig is chaired by Itamar
Shtull-Trauring itamar at zoteca.com.  Contact him if you would
like to help.

Laura Creighton




From nhodgson at bigpond.net.au  Sat Jul 13 18:41:26 2002
From: nhodgson at bigpond.net.au (Neil Hodgson)
Date: Sat, 13 Jul 2002 22:41:26 GMT
Subject: pyCard_turtleTimes
References:   
Message-ID: 

Cousin Stanley:

>                                             AR                  AR
NO AR
>                                             Neil                Stan
Stan
>    ChaosScript2and3 ......  157  ............. 1306  ........ 18
>    hopalong ......................  554  .............   893  ........  46
>    madness ......................  482  .............  2771  ........  53

My results with auto-refresh off are 4, 10.3, and 11.4 so about 4 times
faster than your machine.

> and re-inforce my thoughts that I  STILL  need to go to the 'puter store
...

   I'd expect a cheap current computer to be 2-3 times faster than mine and
a good current computer 5 or 6 times faster.

> I don't consider these applications central to my efficiency,
> but perhaps a glimpse into the performance of the PythonCard samples
> and Python itself and am quite relieved that turning off the Auto-Refresh
> option made a  HUGE  difference ...

   I'd like to see a compromise between auto-refresh and no auto-refresh
with a refresh done every half second or 100 drawing operations so you could
see the developing picture but not cause the drawing to take much longer.
Had a quick look in the code but could not see how to do that.

> ...
> since  turtle-izing  is such a  SIMPLE  method for plotting and should be
> especially attractive to novice programmers ...

   I used to be fascinated by this sort of thing when I was starting out.

   Neil





From rajarshi at presidency.com  Thu Jul 18 17:13:33 2002
From: rajarshi at presidency.com (Rajarshi Guha)
Date: Thu, 18 Jul 2002 17:13:33 -0400
Subject: replacing a part of a string using a regexp
References:  
Message-ID: 

On Thu, 18 Jul 2002 17:11:15 -0400, Fredrik Lundh wrote:

> Rajarshi Guha wrote:
> 
>> a line contains:
>>
>> 
>>
>> And I want to replace the url and make the line:
>>
>> 
>>
>> Using re.sub I can substitute the whole string bewteen quotes, but the
>> substituion needs to use the string that is *found* in the quotes.
>>
>> How can I access the matched portion in a re.sub() expression?
> 
> (if you don't read the documentation, how come you always find the right
> module/function to use? ;-)

I did read the docs, but its been a hectic day and my brain seems to have
slowed down :(


From utopico at utobox.dhs.org  Sun Jul  7 09:14:30 2002
From: utopico at utobox.dhs.org (Jardar)
Date: 7 Jul 2002 06:14:30 -0700
Subject: Embeding python i C++
Message-ID: 

I have just started looking at using python as a scriptinglanguage. I
have successfully created extensions to the python interpretter so
there is noe problem calling C++ functionality from python (used SWIG
for creating wrappers). I have also sucessfully called a python
function from C++. The problems starts when I want to pass a C++
object to a python function. Passing simple strings og intergers are
easy, but I can find out how to pass whole objects. Can anybody help
me out here.

Thanks in advance

Jardar


From raimo-news at mail.com  Wed Jul 31 19:00:11 2002
From: raimo-news at mail.com (Raimo Tuisku)
Date: Thu, 01 Aug 2002 02:00:11 +0300
Subject: Python and Sockets,
References: <3D486809.6F2DC882@nospam.com>
Message-ID: 

On Thu, 01 Aug 2002 01:43:21 +0300, John J Breen wrote:

> to the sockets to be able to listen/send at any time. I cant have a loop
...
> Im not sure what that is... Does anyone have any suggestions for such a
> problem?

Hmm, I used threads for this and they have worked since that. But I am no
100 % sure if that is the best solution for this. I also used
select.select function which tells wheter the socket is
readable/writable/erroneous or not so the thread may be interrupted in
any time(recv function is quite hard to interrupt if it doesn't receive
anything).

-- 
Raimo Tuisku


From b.maryniuk at forbis.lt  Tue Jul  9 03:55:44 2002
From: b.maryniuk at forbis.lt (Bo M. Maryniuck)
Date: Tue, 9 Jul 2002 09:55:44 +0200
Subject: j2ee vs. python (and what our evil competitors are saying about python)
In-Reply-To: <96c7f32.0207081518.52ea644a@posting.google.com>
References: <96c7f32.0207081518.52ea644a@posting.google.com>
Message-ID: <200207090955.45000.b.maryniuk@forbis.lt>

On Tuesday 09 July 2002 01:18, curt finch wrote:
> Our free web timesheet app is written totally in Python.
> One of our competitors is saying the following
> things about python to our customers.  Help me make them look stupid.
> Please?

Do not make them look stupid -- that is not nesessary. ;-)
What I would like to forward is a letter to me from ESR, when I had same war 
Zope / Python vs. Java / JSP and I think this completely will help you here:

----------  Forwarded Message  ----------

Subject: Re: Stupid wars
Date: Sat, 1 Jun 2002 22:45:26 -0400
From: Eric S Raymond 

Java isn't bad.  What I would point out is that if you develop with a closed-
source language, you are likely to have problems with:

(a) subtle bugs in the libraries and tools, which without source access
    you cannot fix.

(b) inadequate documentation of edge conditions, which without source
    access you cannot supplement by looking at what is actually going on.

(c) security; you don't know what code is in there, and cannoy audit for
 bugs. --
                Eric S. Raymond

-- 
Sincerely yours, Bogdan M. Maryniuck

"I would rather spend 10 hours reading someone else's source code than
10 minutes listening to Musak waiting for technical support which isn't."
(By Dr. Greg Wettstein, Roger Maris Cancer Center)





From gerhard.haering at gmx.de  Tue Jul 23 18:36:11 2002
From: gerhard.haering at gmx.de (Gerhard Haering)
Date: Wed, 24 Jul 2002 00:36:11 +0200
Subject: NEWBIE: for statement in "dive into python" gives syntax error.
In-Reply-To: 
References:  <3D3DB42D.3080404@earthlink.net>   
Message-ID: <20020723223611.GA6395@gargamel.hqd-internal>

* Mack  [2002-07-24 00:27 +0200]:
> I just did a cp /usr/bin/python2 /usr/bin/python.

I've heard that doing so will break Redhat's sysadmin tools.

> I can always revert if somethings wrong.

You should probably do that. And use the "python2" command to access the 2.2
Python.

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



From aleax at aleax.it  Fri Jul 26 03:34:02 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 26 Jul 2002 07:34:02 GMT
Subject: how to count lines in a file ?
References:  <7aU%8.139472$vm5.4528856@news2.tin.it>  <1027656130.63094@yasure>
Message-ID: 

Donn Cave wrote:
        ...
> the garbage collection changes to the C Python that we use have not
> compromised its reference count driven behavior at all.

Not yet.  If one day a smart non-RC collector shows the potential
for, e.g., 20% or 25% speedup, though, what then?


> You're just looking at the other Python there, Jython.  Its object
> lifetime policy is Java's, and that doesn't support timely finalization.
> There's your spanner.

"Timely finalization" plays very badly with efficient garbage
collection.  You can count on a good GC system to NOT guarantee
"timely finalization", more or less.

One thought I've toyed with, at times, is to have the optional
ability to mark a few objects as _requiring_ stricter finalization
semantics than the run-of-the-mill kinds of objects.  E.g., files
could be marked that way.  References to such special objects would
then also have to be special and require the typical RC overhead
when manipulated.  Cycles involving such objects would still be
a bother, of course.  Alternatively, all references to such objects
could be special kinds of weak references EXCEPT one reference
held in the creation frame -- the object would then, differently
from all others, be owned by one specific primary reference and
finalized (with all other references to it, being weak, becoming
invalid) when that one specific primary reference goes away.

Semantics could be per-object rather than per-type, e.g.:

        local(open('foo','w')).write('hi!\n')

would not INSTANTLY close foo, but it WOULD close it as part
of the cleanup for the current frame thanks to the hypothetical
local() builtin.  The .write() call would in this case be
happening on a kind of weak proxy for the file object.

When I get to this point in my musings I typically tend to
get lost wondering how to UN-localize such an object so that
after the fact it's possible to get a more persistent reference
to it, etc, etc.  But maybe even the simplest kind of 'local()'
could already have some usefulness, perhaps enough to make it
worth experimenting with.


Alex



From akineko at pacbell.net  Tue Jul  2 15:14:30 2002
From: akineko at pacbell.net (Aki Niimura)
Date: 2 Jul 2002 12:14:30 -0700
Subject: A problem with urllib
References:  <3D1FD7A1.F265FC8E@engcorp.com>  <3D2163E3.3050605@nowhere.org>
Message-ID: 

Bryan Olson  wrote in message news:<3D2163E3.3050605 at nowhere.org>...
> I did some diagnosis, and the problem seems to be a Linksys bug.   The
> router insists on getting the entire request in a single read, rather
> than reading until the end of the headers (and content if present).  The
> URL library must be sending one line at a time or something like that.

I can imagine they assumed all headers are sent in a single packet.
Obviously it makes easier to program. But as you pointed out, that is
not a correct implementation. 

> The code below runs through two cases: the first retrieves the resource
> as it should, and the second triggers the router bug.  In the second
> case, the router returns an "HTTP/1.1 401 Authorization Required" error
> response, even though we send exactly the same request as in the first
> case.

Bryan, thank you for experimenting this. I run your demo script
in my environment, however, I got "HTTP/1.1 401 Authorization
Required"
in both cases. Bryan, if you have tested your script with Linksys DSL
router, could you provide me the type of router (mine is BEFSR41) and
the firmware version (mine is 1.42.7)?

I tried the script both from Solaris and from Windows, but I got the
same result.

Any further suggestions are also appreciated.

Best regards,
Aki Niimura


From claird at starbase.neosoft.com  Mon Jul 29 17:04:20 2002
From: claird at starbase.neosoft.com (Cameron Laird)
Date: 29 Jul 2002 16:04:20 -0500
Subject: Tkinter and Window's controls
References: <4378fa6f.0207291136.2d003a4d@posting.google.com>
Message-ID: 

In article <4378fa6f.0207291136.2d003a4d at posting.google.com>,
Marc  wrote:
>Hi,
>
>I am having trouble with the X button - exit button on upper right of
>the windows created by Tkinter. I was able to 'bind' to the 'Destroy'
>event, so I know when the window is going to be destroyed, and I can
>perform some cleanup
>
>What I want to do, is do the same thing I do on my menu exit button:
>throw up a pop-up and ask 'are you sure' yes-no....
>
>The destroy event that i bound to, comes after python has started to
>shut everything down - not first, like I expected. So my question is,
>how do I bind or have control over the X button?
			.
			.
			.
Look for WM_DELETE_WINDOW in .
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://starbase.neosoft.com/~claird/home.html


From opengeometry at NOSPAM.yahoo.ca  Wed Jul 10 01:36:26 2002
From: opengeometry at NOSPAM.yahoo.ca (William Park)
Date: 10 Jul 2002 05:36:26 GMT
Subject: Linux clock-setting script
References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com>  <7xu1nb59qu.fsf@ruckus.brouhaha.com>      
Message-ID: 

Chris Gonnerman  wrote:
>> I've seen it, but it's a tarball which you have to download and compile.
> 
> This is a problem?

Not really, but there are 2 other utilities in installation CD.

> 
>> Whereas, 'netdate', 'ntpdate', and 'telnet 13' are ready to run on all
>> Linux distribution.  I have DSL connection, so I run it once a day in
>> Crontab.  If you dialup, then you can run it from '/etc/ppp/ip-up'.
> 
> True.  chrony doesn't update the time by "lurches" though, but by "skew,"
> which is better in most cases.

I think all does "skewing" if time difference is small enough (I think
0.5s).

-- 
William Park, Open Geometry Consulting, 
8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin


From aleax at aleax.it  Sat Jul 13 12:22:20 2002
From: aleax at aleax.it (Alex Martelli)
Date: Sat, 13 Jul 2002 16:22:20 GMT
Subject: dir() shows strange behaviour with VPython
References: <3d2fe41e$0$25552$91cee783@newsreader02.highway.telekom.at>  <3d3048bc$0$21424$91cee783@newsreader02.highway.telekom.at>
Message-ID: <0tYX8.63209$Jj7.1649555@news1.tin.it>

Gregor Lingl wrote:

> What a surprise to come into contact with martellibot just
> after having read your interview on the Euro Python website.

Pleased to meet you!  I shouldn't be here (don't tell my
O'Reilly editor I'm writing on c.l.py when I should be
busy finishing the Nutshell book...), but...


> I'm working with Python 2.2.1 on a Windows2000 machine.

I have not tried VPython anywhere except on Linux, where
I just tried reproducing your problem -- as I said, it's
slightly different there.

> Curious if something similar would happen on my machine
> I just deinstalled Visual-2002-06-14 and replaced it by
> Visual-2002-07-07 and I obtain exactly the same results
> as before - the session remaining alive...
> 
> Let's see, if somebody else will give us more information
> on this ...

I think you should forward a copy of these exchanges (or
a pointer to them via google advanced group search) to
the VPython guys -- I'm sure they'll be able to debug and
fix the problem very simply, while it would take longer
for somebody utterly unfamiliar with VPython's internals,
such as yours truly...


Alex



From aleax at aleax.it  Sun Jul  7 11:24:44 2002
From: aleax at aleax.it (Alex Martelli)
Date: Sun, 07 Jul 2002 15:24:44 GMT
Subject: structs in python
References: 
Message-ID: <03ZV8.42192$Jj7.1159218@news1.tin.it>

Opus wrote:

> And the __slots__ way is strange if you are using the __variables in your
> class.
> 
> class thing(object):
>   __slots__ = ["_thing__var"]         # Huh???
>   def __init__(self,init):
>     self.__var = init

This is a bug in Python 2.2, already fixed in the Python 2.3 pre-alpha
that's currently in the CVS tree -- now, type.__new__ properly 'decorates'
(aka 'mangles') each slotname whose name starts with '__' (and does not
end with '__') so __slots__=['__var'] will work fine here.  Hopefully
this bug fix will be backported to 2.2.2 ...


Alex



From fperez528 at yahoo.com  Sun Jul 21 15:40:18 2002
From: fperez528 at yahoo.com (Fernando Perez)
Date: Sun, 21 Jul 2002 13:40:18 -0600
Subject: Renting CPU time for a Python script
References: <25c15ddd.0207190852.2aecc26c@posting.google.com>  <25c15ddd.0207201216.46eddd73@posting.google.com>
Message-ID: <3D3B0E22.200@yahoo.com>

> Thanks for your very informative post!  Unfortunately the bottleneck
> in my program lies with the PIL extension since I have to perform a
> lot of putpixel and getpixel operations, which are quite expensive in
> PIL.  In the future I would like to rewrite sections of the code in C,
> but I have to admit that dealing with LibTiff greatly exceeds my C
> programming abilities.  I really like your idea of building in
> restarting functionality, and I will add it when I get some free time.

It's hard to say without knowing the details of your problem, but I'm a 
bit surprised to hear that you're doing compute-intensive operations on 
an image format. So forgive me if I'm off-base, but I suspect your 
problem could be fixed by moving away from image formats to a numerical 
representation of your data. Convert your data to matrices, and then 
operate on them using either Numeric (fast) or with a few hand-written 
extensions using weave (possibly even faster, weave is at scipy.org).

As I said I could be wrong, but I'd be extremely surprised to find that 
the core of your problem needs to be done on the images as images and 
that it can't be expressed mathematically on the underlying matrices. 
Image formats are meant for human viewing, not for efficient numerical 
processing.

Good luck,

f.



From aleax at aleax.it  Mon Jul  8 18:11:58 2002
From: aleax at aleax.it (Alex Martelli)
Date: Mon, 08 Jul 2002 22:11:58 GMT
Subject: Properties - when and why
References: 
Message-ID: 

Arthur Siegel wrote:

> Alex writes -
> 
>>The obvious solution for this case is to keep your original
>>get_V method intact and to code V_homogeneous the simple way:
> 
>>def V_homogenous(self):
>>    V = self.V
>>   return array((V.x,V.y,V.z,1.))
> 
> Thanks for the reply, and sorry for the various careless idiocies in my
> post.

You're welcome, and, no problem.

> But your suggestion is exactly what I concluded to do in my own code
> until I thought I concluded - and this is the gist of my question - that
> even with the
> syntax you suggest I was making now 4 calls to the vector subtract
> calculation -
> one for V= self.V and one each time I called for an attribute of V.
> 
> If I am wrong there - my problem essentially goes away. I was doing it in

Yep, it goes away, because you're wrong.  Local variable V is bound
to the value returned by self.V and stays bound to that value -- no
further calls (it would require deep magic indeed to provoke such calls:-).

> a context of my code where there are many interrelationships and I may
> have misintepreted what I was seeing.
> 
> Are you in fact saying that your suggested solution avoids multiple calls
> to the calculation that determines the value of self.V?

Right.


Alex



From aaron at reportlab.com  Mon Jul  8 10:58:49 2002
From: aaron at reportlab.com (Aaron Watters)
Date: 8 Jul 2002 07:58:49 -0700
Subject: freeze path problem (on nt)
Message-ID: <9a6d7d9d.0207080658.3d8181d8@posting.google.com>

Hi guys.  I have the following problem.

I use tools/freeze to build a frozen exe (X.exe) for windows using vc++ 6.

If I run it on a machine without a python installation it runs fine.
But if I run it on a machine with python and a package called

    rlextra.rml2pdf

then the import

    from rlextra.rml2pdf import rml2pdf

imports the python module from the file system in preference to the
frozen pyc that is compiled into X.exe.  This is a problem, of course
if the version of rml2pdf on the file system differs from the one in X.exe.

It must have something to do with sys.path and/or those goofy *.pth files
right?

Anyway, how do I prevent X.exe from trying to import stuff from the
file system first before looking internally... anybody got a clue?

thx in advance

   =- Aaron Watters

===
JUVENILE COURT TO TRY SHOOTING SUSPECT
   -- from "real headlines" (that should work...)


From aahz at pythoncraft.com  Mon Jul 29 20:11:04 2002
From: aahz at pythoncraft.com (Aahz)
Date: 29 Jul 2002 20:11:04 -0400
Subject: global interpreter lock not working as it should
References: 
Message-ID: 

In article ,
anton wilson   wrote:
>
>I'm running linux 2.4.18 and 2.4.19 with Python 2.2 and the linuxthreads 
>library. 
>
>I'm having a problem where the interpreter in ceval.c does not let     
>threads run concurently. Any thread that holds the lock never gives    
>up the lock until it has run to completion. In addition to my program  
>printouts I've tested and found that as long as a thread needs to run, 
>it will always reaquire the GIL immediately after releasing it every   
>10 byte codes! Of course, if a thread never blocks on the GIL, no      
>other thread will ever run. And this is what is happening.             

If you're using pure Python code, yes this often happens, depending on
what OS you're using.  However, there's nothing wrong with it, either:
if you're writing threaded applications, you should be making zero
assumptions about the order in which threads execute unless you use
locks to force synchronization.

If you want threads to run concurrently, truly concurrently, you'll need
to make function calls to extensions that release the GIL.  That
basically means either I/O calls (and time.sleep() is an I/O call) or
extensions that you write yourself.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From nas at python.ca  Tue Jul 23 20:05:45 2002
From: nas at python.ca (Neil Schemenauer)
Date: Tue, 23 Jul 2002 17:05:45 -0700
Subject: Mastering Regular Expressions 2nd Ed.
In-Reply-To: <7xn0si9o2o.fsf@ruckus.brouhaha.com>; from phr-n2002b@NOSPAMnightsong.com on Tue, Jul 23, 2002 at 01:38:55PM -0700
References:  <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> <7xn0si9o2o.fsf@ruckus.brouhaha.com>
Message-ID: <20020723170545.A7945@glacier.arctrix.com>

Paul Rubin wrote:
> Argggh!  That sounds like regular expressions aren't really the best
> way to match RFC822 addresses.

Regular expressions work much better if you use them for lexical
analysis rather than for parsing.

  Neil



From joe.woodward at padtinc.com  Tue Jul  9 15:19:50 2002
From: joe.woodward at padtinc.com (Joe Woodward)
Date: 9 Jul 2002 12:19:50 -0700
Subject: File size error in os.stat with large files.
Message-ID: <28bbdc67.0207091119.6d9ecd48@posting.google.com>

Hi,
Does anyone know the file size limit that os.stat will handle
correctly?

I have a 4.2GB file that os.stat is reporting to be 164MB. Smaller
files seem to work just fine, but I have not played with it to find
out where the cut-off point is.

I am using Python 2.1 on Windows 2000.

Thank you,

Joe Woodward
Phoenix Analysis and Design Technologies
Tempe, AZ


From ellisjb at my-deja.com  Tue Jul  9 16:10:13 2002
From: ellisjb at my-deja.com (Jonathan Ellis)
Date: 9 Jul 2002 13:10:13 -0700
Subject: [OT] Corrections about Java
References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091137.11467.b.maryniuk@forbis.lt> <20020709094938.GA1489@lilith.my-fqdn.de> 
Message-ID: 

"Bo M. Maryniuck"  wrote in message news:...
> On Tuesday 09 July 2002 11:49, Gerhard H?ring wrote:
> > Works for me.
> I meant:
> some loop forewer {
>   try {
>      break;
>   } finally {
>   continue;
>   }
> }

that this loops infinitely would not be surprising to someone familiar
with how java try blocks work.

-Jonathan


From aleax at aleax.it  Tue Jul 16 04:50:47 2002
From: aleax at aleax.it (Alex Martelli)
Date: Tue, 16 Jul 2002 08:50:47 GMT
Subject: Webware 0.7/Singleton pattern
References: 
Message-ID: 

Michael Bub wrote:
        ...
> WebApp built with Webware 0.7 (using Python 2.2 on a FreeBSD4.4
> system), the second or third time the get_instance method is called,
> the one instance that was created by the singleton seems to be
> forgotten about (or rather, it seems as if the file that holds the
> class definition was imported and used for the very first time) and

You may be serving hits in different processes -- that depends in
part on how you're using Webware... it can be installed to work
on top of CGI, and CGI by definition uses a new process each time.

If you want to make SURE, use Borg augmented with saving and
retrieving of instance data (ideally on a decent underlying DB
so you need not worry about synchronization etc).


Alex



From jonathan at onegoodidea.com  Tue Jul 30 04:40:26 2002
From: jonathan at onegoodidea.com (Jonathan Hogg)
Date: Tue, 30 Jul 2002 09:40:26 +0100
Subject: PyXML-0.7.1, python-2.2.1, and Redhat 7.3
References:  <3D45E665.3C34CDF@alcyone.com> 
Message-ID: 

On 30/7/2002 9:36, in article B96C0EAF.EC64%jonathan at onegoodidea.com,
"Jonathan Hogg"  wrote:

> Is this some weird mismatch in expat module version?

Hate following up to myself, but try this:

>>> import pyexpat
>>> pyexpat.__version__
'2.67'
>>> pyexpat.ParserCreate( intern={} )

>>> 

and tell us what happens.

Jonathan



From t at chabry.caltech.edu  Tue Jul  2 13:21:30 2002
From: t at chabry.caltech.edu (Titus Brown)
Date: 2 Jul 2002 10:21:30 -0700
Subject: JARs + Jython classes
References: 
Message-ID: 

In article ,
Paul Brown  wrote:
>
>does anyone know the syntax for loading a jython class from a JAR, or even
>if this is POSSIBLE?

[ munch ]

Hi, Paul,

I have managed to distribute my Jython app, FamilyRelations, in JAR format.
It took me a while to figure it all out ;), so I'm not sure I remember all
the steps, but with recent versions of Jython you can just compile your
Jython files into a jar with the appropriate flags to jythonc:

        $(JYTHONC) --all -j package/FamilyRelations.jar start.py

There are various tricky rules for figuring out what JAR dependencies are
necessary when -- Jython doesn't always have simple rules for what interfaces
are compiled in or looked for -- so if you rely on lots of outside libraries,
you may have to fiddle.

Let me know if I can be of any help.  You can see all my source under the
ctb_devel branch of FamilyRelations/ at the FamilyJewels project on
SourceForge; the Makefile is set up to make the .jar version from the .py
files.

cheers,
--titus


From imbosol at vt.edu  Mon Jul 22 14:25:10 2002
From: imbosol at vt.edu (Carl Banks)
Date: Mon, 22 Jul 2002 14:25:10 -0400
Subject: Scope of instantiated class
References: <3D3ACCA6.7030002@lmco.com>
Message-ID: <6mihha.st.ln@grey.aerojockey.localdomain>

Jeff Layton wrote:
> Hello,
> 
>    If I instantiate a class in a function,
> leave the function via a return and then
> go back to the same function, will the
> instantiation of the class still be there
> or is it local to the function so it is
> "destroyed"? (Does this make any sense?)


It seems that you are asking whether the class will be recreated every
time you call the function.  The answer is yes, and classes created by
different calls to the function will be distinct classes.

However, it doesn't mean the class is "destroyed" when the function
exits.  The class will continue to exist after the function exits if
there are any references to the class that still exist.  For example,
if the function returns an instance of the nested class, then the
class will not be destroyed because the instance contains a reference
to the class.

But, even if the nested class still exists when you call the function
again, the function will construct a new and distinct class.


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


From doyle at acrossthebigpond.com  Sat Jul 20 20:14:41 2002
From: doyle at acrossthebigpond.com (Kevin Doyle)
Date: Sun, 21 Jul 2002 00:14:41 GMT
Subject: wxMDIChildFrame
Message-ID: 

Hi

I am new to wxPython and Linux, moving from MS.  I am using the latest
release of wx and Python 2.2.

I have created the main app as a wxMDIParentFrame.  When I call the MDI
child:

test = frmEmployee(self,-1,"Employee Form")
test.Show(true)


(Just a snip)
class frmEmployee(wxMDIChildFrame):   
    def __init__(self, parent, ID, title):
        wxMDIChildFrame.__init__(self, parent, ID, title,
           wxDefaultPosition, wxSize(400, 300), wxDEFAULT_FRAME_STYLE)


the child does not appear as a MDI Child.  As I create more instances of
the child a Tabbed interface is created....

How do I make the child appear as a MDI Child i.e. a frame with a title
bar etc...

Any help or pointers in teh right direction would be great.

One other question.  Should I use MDI at all?

Thanks

Kevin


From sneavreet+nospam at innocent.com  Sun Jul  7 06:57:41 2002
From: sneavreet+nospam at innocent.com (Anders Dahlberg)
Date: Sun, 7 Jul 2002 12:57:41 +0200
Subject: Using Python for processing of large datasets (convincing managment)
References: <3D27152C.8020108@obscure.dk.X>  <3D275E8A.3000003@ob_scure.dk>  <3D276B81.9090003@ob_scure.dk>  <3D281AE3.3070800@ob_scure.dk>
Message-ID: 

"Thomas Jensen"  wrote in message
news:3D281AE3.3070800 at ob_scure.dk...
> Anders Dahlberg wrote:
>
> [snip]
>
> > Why not consider using jython?
> > Same scripting as python, better scaling to multiple cpu's - seems
atleast
> > to me as an easier solution than xml-rpc?
>
> Does it also scale well to multiple machines?
> If so, do you have any links to information regarding this?

Considering it's compiling down to java-bytecode which are then run with a
java-vm - It should scale as well as any java solution (or atleast ~90%).
Links could be:

http://java.sun.com ;)
http://www.bea.com/products/weblogic/jrockit/index.shtml - very good server
vm. (optimised for intel)

Plus that all the j2ee servers are running on a java-vm, thus any scaling
information you can gather from them should probably apply to your case too?
IIRC though, all java-code running on the default sun jvm will take
advantage of additional cpu's if they are available - no extra coding should
be required (exception from that the code should be easy enough for the vm
to "parallellize" :)

disclaimer: This is just what I believe - if you want to base your case on
this I believe you should contact other companies using java with
multiple-cpus!

> > (maybe it's easier to sell the idea to your boss too, due to java-hype
and
> > all ;)
>
> That might be a point :-)
>
> --
> Best Regards
> Thomas Jensen
> (remove underscore in email address to mail me)
/Anders




From huaiyu at gauss.almadan.ibm.com  Wed Jul 10 14:25:54 2002
From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu)
Date: Wed, 10 Jul 2002 18:25:54 +0000 (UTC)
Subject: Why self?
References:  <090720021439257166%pecora@anvil.nrl.navy.mil> <7934d084.0207091739.4720aafc@posting.google.com>
Message-ID: 

Andrae Muys  wrote:
>"Louis M. Pecora"  wrote in message news:<090720021439257166%pecora at anvil.nrl.navy.mil>...
>> scientifc code and I just think
>> 
>> 
>>    self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries)
>> 
>> is a LOT uglier than
>> 
>>    y= x**2 * t/z + a * FFT(tseries)
>
>In fact the only reason I have followed this thread is because I found
>myself writing some similar code just the other day and came to the
>same conclusion.  Python loves namespaces right?  Now I haven't given
>much thought to it, but it occurs to me to ask why Python dosn't
>provide support for using namespaces, not just defining them?
>
>Compare the following:
>
>self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries)
>
>to:
>
>y= x**2 * t/z + a * FFT(tseries)
>
>to:
>
>with self:
>    y= x**2 * t/z + a * FFT(tseries)


The Pythonic way to use namespace is :-)

from self import x, y, z, a, tseries
y= x**2 * t/z + a * FFT(tseries)
to self export y  

Any change that persists beyond local namespace is mentioned explicitly.
Does it solve all the problems mentioned below?

>
>Issues that immediately occur to me are:
>
>1) Another keyword
>2) How do you reference variables that aren't in the specified
>namespace without a second keyword!
>3) Issue 2 becomes critical when you what to deal with temporary
>results that you definately want discarded along with the current
>local scope.  So maybe only rvalues are affected ie.
>
>with self:
>    self.y = x**2 * t/z + a * FFT(tseries)
>
>might be better, but then the inconsistency bites.
>
>Maybe this is a good idea?  More likely I'm about to learn which
>critical basic flaw I've missed.
>
>at-least-I-will-get-to-learn-something-ly yours
>
>Andrae Muys


From boud at valdyas.org  Sat Jul  6 15:25:28 2002
From: boud at valdyas.org (Boudewijn Rempt)
Date: Sat, 06 Jul 2002 21:25:28 +0200
Subject: Chinese language support of Python?
References: 
Message-ID: <3d27481f$0$12314$e4fe514c@dreader4.news.xs4all.nl>

Leon Wang wrote:

> How can enable Chinese language support of Python? In IDLE, even can
> not save the source file if contain any >128 ASCII code charactors. I
> want to set the Window title in Chinese, but the bit7 is masked by
> Tkinter:

> root.title('中文') # this is Chinese
>

Well, this isn't Chinese -- at least not when it arrived at my
server, but probably not even when it originated with you, because
I see your headers advertise ISO-8859-1 as the encoding. It's plain
string that contains an assortment of ampersands, hash marks, semicolons
and numbers in an order that hasn't much meaning.

If you use _real_ unicode -- for instance 
 root.title(u'\u028A\u0288') # no chinese, because of lacking fonts, but IPA
then everything works fine -- at least, with my window manager, on my OS.

-- 
Boudewijn Rempt | http://www.valdyas.org


From tim.one at comcast.net  Sun Jul  7 21:43:31 2002
From: tim.one at comcast.net (Tim Peters)
Date: Sun, 07 Jul 2002 21:43:31 -0400
Subject: `~/.pythonrc' `from __future__ import'
In-Reply-To: 
Message-ID: 

[Fran?ois Pinard]
> Hello, people.  Here is a strange problem with `from __future__ import',
> maybe you can help me understand it.  This is with Python 2.2.1.
>
> Given `export PYTHONSTARTUP=/home/pinard/etc/pythonrc', and that
> `pythonrc'
> file starting with:
>
> ---------------------------------------------------------------------->
> from __future__ import division
> print 3/4
> ----------------------------------------------------------------------<
>
> then I interactively get:
>
> ---------------------------------------------------------------------->
> 18:01 0 pinard at titan:~ $ python
> Python 2.2.1 (#1, Apr 29 2002, 14:27:21)
> [GCC 2.95.3 20010315 (SuSE)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 0.75
> >>> 3/4
> 0
> >>> from __future__ import division
> >>> 3/4
> 0.75
> ----------------------------------------------------------------------<
>
> I wonder why I have to re-execute `from __future__ import divsion'
> interactively before it works.

The PYTHONSTARTUP file acts as if executed via the execfile() function.
That implies it can leave behind visible bindings in the caller's globals,
and have other non-local side effects (such as importing other modules), but
like all exec and eval gimmicks, it executes in a code block distinct from
its caller's.  It's a separately compiled unit, and a future statement's
useful effects are limited to the compilation unit in which it appears.  In
effect, that means it only "works" for the code in the startup file itself.

Note that Python has no equivalent in this respect to what some shells call
a "source" command.

> How should I proceed to activate this option once and for all for
> interactive applications?

You can write an alias to start interactive sessions by passing -Qnew to
Python.  Then future division will be in effect globally (note:  that means
globally, including across all imported library modules, and some non-core
library modules may not yet work correctly when future division is in
effect; so -Qnew can't be recommended for general use, but is fine if
you're, umm, motivated ).






From wester at ilt.fhg.de  Tue Jul  9 09:47:39 2002
From: wester at ilt.fhg.de (Rolf Wester)
Date: Tue, 09 Jul 2002 15:47:39 +0200
Subject: Problems building a Python module
Message-ID: <3D2AE97B.4020908@ilt.fhg.de>

Hi,

I want to build a Python module from C-files. I made the wrapper file
using swig. During linking I get the following message:

/usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function 
`posix_tmpnam':
posixmodule.o(.text+0x3614): the use of `tmpnam_r' is dangerous, better 
use `mkstemp'
/usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function 
`posix_tempnam':
posixmodule.o(.text+0x3520): the use of `tempnam' is dangerous, better 
use `mkstemp'
/usr/lib/python2.2/config/libpython2.2.a(thread.o): In function 
`PyThread_start_new_thread':
thread.o(.text+0x7f): undefined reference to `pthread_sigmask'
thread.o(.text+0x98): undefined reference to `pthread_create'
thread.o(.text+0xa7): undefined reference to `pthread_sigmask'
thread.o(.text+0xbd): undefined reference to `pthread_detach'
/usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function 
`posix_openpty':
posixmodule.o(.text+0x1706): undefined reference to `openpty'
/usr/lib/python2.2/config/libpython2.2.a(posixmodule.o): In function 
`posix_forkpty':
posixmodule.o(.text+0x177c): undefined reference to `forkpty'
make: *** [opt] Fehler 1


I link against following libraries:

-lpython2.2 -lm -ldl

Can someone tell me what other libraries I have to link against? And
what means:

posixmodule.o(.text+0x3614): the use of `tmpnam_r' is dangerous, better 
use `mkstemp'

I would be very appreciatiev for any help.

Regards

Rolf



From imbosol at vt.edu  Wed Jul 10 03:42:41 2002
From: imbosol at vt.edu (Carl Banks)
Date: Wed, 10 Jul 2002 03:42:41 -0400
Subject: j2ee vs. python (and what our evil competitors are saying about python)
References:  <96c7f32.0207091153.7b2484be@posting.google.com>  
Message-ID: 

Alex Martelli wrote:
> Terry Reedy wrote:
>        ...
>> PS.  The notion that competitor would try to attack product by
>> attacking invisible-to-user implementation language strikes me as
>> bizarre.  Reeks of desperation.
> 
> It does in fact happen quite often -- a technology used in the
> making of a product is targeted for 'for' or 'against' marketing,
> rather than user-visible aspects of the product.

One word: Object Oriented.


-- 
CARL BANKS


From gerhard.haering at gmx.de  Thu Jul 18 08:18:22 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 18 Jul 2002 12:18:22 GMT
Subject: Pmw Inconsistencies -- Any ideas ??
References: 
Message-ID: 

Mike MacDonald wrote in comp.lang.python:
> I'm wanting to use Pmw for a small project.
> I notice that sometimes I can't initialise Pmw. [...]
> ##
> ##Error message:
> ##    Traceback (most recent call last):
> ##  File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 1, in ?
> ##    import Pmw
> ##  File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 11, in ?
> ##    root=Pmw.initialise()

You didn't call your script "Pmw" too, did you? Which Python version
is this?

Gerhard
-- 
mail:   gerhard  bigfoot  de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))


From whisper at oz.net  Thu Jul 25 13:44:05 2002
From: whisper at oz.net (David LeBlanc)
Date: Thu, 25 Jul 2002 10:44:05 -0700
Subject: Mastering Regular Expressions 2nd Ed.
In-Reply-To: 
Message-ID: 

> It's strange that while regular languages are a small subset of real,
> Turing-complete languages, it's very hard to read or write any
> non-trivial regexp. The syntax is straight out of computer science
> mathematical notation (with some extensions) and is not suitable for
> anything complex. It's bit like programming for the Turing machine. On
> the other hand, the syntax is compact and IS suitable for simple
> tasks.


> Kristian Ovaska 

I may be wrong about this, but I don't think regular expressions qualify as
turing complete. No branching for one thing...

Personally, I think RE's are great and ought to be fully integrated into
Python, along with a few improvements.

Dave LeBlanc
Seattle, WA USA




From donn at u.washington.edu  Tue Jul 30 13:08:09 2002
From: donn at u.washington.edu (Donn Cave)
Date: 30 Jul 2002 17:08:09 GMT
Subject: Finding count of currently open file descriptors.
References: <3D469D2F.6010003@truis.com>
Message-ID: 

Quoth Tim McNerney :
| How do I go about finding out the number of file descriptors currently 
| open in a program? I'm trying to track down a file descriptor leak which 
| may or may not be in library calls. Will I run into problems getting an 
| accurate count due to the possible delay between doing a close and GC?

No, you won't.  The classic technique for this is just to inventory
all possible file descriptors and see which ones are valid - might
sound like a lot of overhead, but it goes pretty fast.  In C, that is.
In Python, you might be able to work around the absence of getdtablesize(),
but this is the rare case where exceptions are not your friend, they'll
add significant overhead.  The number of calls (process file limit)
will be on the order of 64 to 256, depending on platform.

If you can jack in a module, try this - just call fd.count() around
the suspect code.

	Donn Cave, donn at u.washington.edu
----------------------------------------
/*
** NetBSD build:
** cc -c fdmodule.c -I/usr/local/include/python2.1
** ld -shared -o fdmodule.so fdmodule.o -lc
*/
#include 
#include 
#include 
#include 

static PyObject *
count(PyObject *module, PyObject *args)
{
    int maxfd, fd, vfd;
    maxfd = getdtablesize();
    for (fd = 0, vfd = 0; fd < maxfd; ++fd) {
        if (isatty(fd))
            ++vfd;  /* valid tty */
	else if (errno == ENOTTY)
            ++vfd;  /* not valid tty, but not EBADF */
    }
    return PyInt_FromLong(vfd);
}

static struct PyMethodDef fd_global_methods[] = {
    {"count", count, 1},
    {0, 0}		/* sentinel */
};

initfd()
{
    PyObject *module;
    PyObject *dict;

    module = Py_InitModule("fd", fd_global_methods);
    dict = PyModule_GetDict(module);
    return 1;
}


From unlearned at DELETETHIS.learn2think.org  Mon Jul 29 13:03:02 2002
From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell)
Date: Mon, 29 Jul 2002 11:03:02 -0600
Subject: Python design failures (was Re: Let's Talk About Lambda Functions!)
References:  <3d455445_9@news.newsgroups.com>  <3d457011_1@news.newsgroups.com>
Message-ID: <3d457545$1_3@hpb10302.boi.hp.com>

"JB"  wrote in message
news:3d457011_1 at news.newsgroups.com...
> Aahz wrote:
>
> > In article <3d455445_9 at news.newsgroups.com>, JB
> >  wrote:
> >>Tim Peters wrote:
> >>>
> >>> two language features are mentioned as being "failed
> >>> experiments" that only compatibility prevents throwing
> >>> away:
> >>>
> >>>     `back ticks`
> >>>     lambda
> >>
> >>(1) Why are back ticks a failure? I love them.
> >
> > If you're using backticks frequently, you're probably not
> > programming
> > Pythonically.  There's already repr() to produce the same
> > result as backticks, and backticks have the problem that
> > in many fonts they're nearly indistinguishable from single
> > quotes.
>
> I do not understand this. I use __repr__ *and* backticks.
> For example
>
> class AnyClass:
>   defr __repr__(self):
>     ...
>
> a = AnyClass()
> myfile.write(`a`)
>
> I use this construction rather frequently. What is wrong
> with it?
>
> --
> JB


repr() != __repr__()

`object` == repr(object), both of which will call object.__repr__, if it
exists.

I think that the general consensus is that repr(object) is much more
readable than the relatively obscure syntax `object`.  Also, as written
previously, the ` is easily confused with ' in many fonts.

--
Daniel Fackrell (unlearned at learn2think.org)
When we attempt the impossible, we can experience true growth.




From csposting at yahoo.com.au  Tue Jul 16 09:28:22 2002
From: csposting at yahoo.com.au (Patrick W)
Date: 16 Jul 2002 23:28:22 +1000
Subject: Iterator for Custom Sequence
References: <87u1mzq5xw.fsf@athens.localdomain> 
Message-ID: <87ptxnpzt5.fsf@athens.localdomain>

Jonathan Hogg  writes:

> I'm not sure why you've used a nested function. 

Relic of an early misunderstanding.

At first I thought __iter__ was supposed to *return* a generator, so I
made it a nested function and handed it to the caller. When that
didn't work, I made __iter__ *call* the nested generator. I should
then have realised that __iter__ could *be* the generator, but for
some reason I didn't.

(Instead I was off chasing red herrings, wondering whether the
generator ought to be a nested function, class method or free
function. Ridiculous in hindsight, but such is life).

> I would have written this simply as:
> 
>     class LinkedList:
>         ....
>         def __iter__(self):
>             node = self.head
>             while node.next is not None:
>                 yield node.data
>                 node = node.next
>         ....

That's lovely. Thanks.


From mdehoon at ims.u-tokyo.ac.jp  Tue Jul 23 01:11:44 2002
From: mdehoon at ims.u-tokyo.ac.jp (Michiel Jan Laurens de Hoon)
Date: Tue, 23 Jul 2002 14:11:44 +0900
Subject: distutils cygwin bdist_wininst
References: <3D3CD77B.1040102@ims.u-tokyo.ac.jp> 
Message-ID: <3D3CE590.9050305@ims.u-tokyo.ac.jp>

Thanks for your help. Unfortunately, if I try that, I get an error:

 > c:\\python22\\python setup.py --compiler=mingw32
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
    or: setup.py --help [cmd1 cmd2 ...]
    or: setup.py --help-commands
    or: setup.py cmd --help

error: option --compiler not recognized

I get the same error with both the win32 Python and the Cygwin Python.
My win32 Python is the latest version. Any idea what is going wrong? I 
attached my setup.py in case it is of any help.

Thanks again -- Michiel

setup.py:

#!/usr/bin/env python

from distutils.core import setup, Extension

setup(name="Cluster",
       version="1.01",
       description="The C Clustering Library",
       author="Michiel de Hoon",
       author_email="mdehoon at ims.u-tokyo.ac.jp",
      url="http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/software.html",
       packages = ['Pycluster'],
 
ext_modules=[Extension("Pycluster.cluster",["cluster.c","clustermodule.c",
"ranlib/src/ranlib.c","ranlib/src/com.c","ranlib/linpack/linpack.c"],include_dir
s=['ranlib/src'],extra_link_args=['-s'])]
       )


Gerhard H?ring wrote:


 > Michiel Jan Laurens de Hoon wrote in comp.lang.python:
 >
 >>Is it possible to create a Windows installer with distutils using the
 >>Cygwin/mingw gcc compiler?
 >>
 >
 > $ python setup.py --compiler=mingw32
 > $ python setup.py bdist_wininst
 >
 > 'python' must be the win32 Python, *not* the Cygwin Python.
 >
 > Gerhard
 >



From unlearned at DELETETHIS.learn2think.org  Tue Jul 30 13:02:26 2002
From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell)
Date: Tue, 30 Jul 2002 11:02:26 -0600
Subject: Let's Talk About Lambda Functions!
References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it>   <3D439089.3010305@nowhere.org>   <7Rc19.92310$724.23106@atlpnn01.usenetserver.com>  <3d46964b$1_2@hpb10302.boi.hp.com> 
Message-ID: <3d46c6a2$1_1@hpb10302.boi.hp.com>

"John Roth"  wrote in message
news:ukddqtelmp6eda at news.supernews.com...
>
> "Daniel Fackrell"  wrote in
> message news:3d46964b$1_2 at hpb10302.boi.hp.com...
> > "John Roth"  wrote in message
> > news:ukb31ell2rh643 at news.supernews.com...
> >
> > 
> >
> > >     for word in 'fee fie fo fum'.split():
> > >         Button(frame, command = def ():
> > >                 print word
> > >             )
> > >
> > > This isn't really the world's best example, because IMO, the
> > > lambda form is easier to read for something this small. However,
> > > it does give the guts of the idea:
> >
> > 
> >
> > > 2. The remainder of the syntax exactly models def, including
> > > statement indentation within the expression. Notice that the
> > > first statement in the anonamous function has to be indented
> > > two from the preceeding line, because the continuation of
> > > the expression has to still be indented from the line with the
> > > 'def', and dedented from the statements.
> >
> > IIRC, there's no such ting as "indenting two" in Python as the size of
> an
> > indentation is automatically detected as you go along, making the
> following
> > indentation style valid (although no one would ever want to do it):
> >
> > toplevel
> >  secondlevel
> >                 thirdlevel
> >  secondlevel
> >     thirdlevel
> >      fourthlevel
> >  secondlevel
> > toplevel
>
> The reason I say "indenting 2" is that you need two
> dedents to make it work: one to close the def, which does
> not have it's own indent, and one to finish off the expression
> in which the def is imbedded.
>
> Does this make it clearer?
>
> John Roth

Again, the problem is that Python must assume that when it sees code
indented further than the previous line, a single indent is intended.  It
has no way of knowing how many indents you mean unless something is actually
indented to each level along the way.

In addition to that, indentation is currently ignored inside (), {}, [],
strings, and on lines following an escaped newline.  Some of that could
change, perhaps, but it seems to me that it might break existing code.

I do see merit in this discussion, though, because I see class and def
statements as really being a shorthand for doing two things at once, namely
creating a function and then binding it to a name.

Admittedly, there are probably cases where the second part does not apply
all that well.  Perhaps a case where you want a list or dict of functions
would be one such case.  Binding to the name simply adds a step along the
way.  Passing a callable object as a parameter to another callable object
would probably be another such case.

The issue quickly becomes readability, though.  Would you want to be able to
do a complex multi-line def or class statement inside an assignment creating
a list, for example?  And how would you do that without indentation?

funcList = [ Insert idea here ]

lambda in its current form does okay in cases like this.  As an expression
it does not require indentation for anything, but it is also not allowed to
execute statements.

--
Daniel Fackrell (unlearned at learn2think.org)
When we attempt the impossible, we can experience true growth.




From bbrelin at yahoo.com  Fri Jul 19 10:29:56 2002
From: bbrelin at yahoo.com (Braun Brelin)
Date: 19 Jul 2002 07:29:56 -0700
Subject: ImportError: cannot import name pyexpat...What does this mean?
Message-ID: 

Hello all,

I'm running Zope 2.5.1 on a RedHat 7.3 Linux x86
machine.  I've downloaded and installed some Zope
products such as ParsedXML and XMLWidgets. 

I've installed them because I'm trying to 
install the Silvia document management product.

I've also downloaded and installed the PyXML Python
package using the 

"python setup.py build"
and
"python setup.py install" 

I also stopped and attempted to restart Zope.

I get the following errors:

2002-07-19T14:24:31 ERROR(200) Zope Could not import Products.Silva
Traceback (innermost last):
  File /opt/Zope-2.5.1-linux2-x86/lib/python/OFS/Application.py, line
531, in import_product
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/Silva/__init__.py,
line 1, in ?
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/Silva/Folder.py,
line 15, in ?
    (Object: aq_inner)
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/Silva/XMLImporter.py,
line 1, in ?
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/ParsedXML/ParsedXML.py,
line 96, in ?
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/ParsedXML/ManageableDOM.py,
line 99, in ?
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/ParsedXML/ExtraDOM.py,
line 92, in ?
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/ParsedXML/DOM/ExpatBuilder.py,
line 115, in ?
    (Object: Products.ParsedXML.DOM.XMLExtended)
ImportError: cannot import name pyexpat


------
2002-07-19T14:24:32 ERROR(200) Zope Could not import
Products.XMLWidgets
Traceback (innermost last):
  File /opt/Zope-2.5.1-linux2-x86/lib/python/OFS/Application.py, line
531, in import_product
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/XMLWidgets/__init__.py,
line 2, in ?
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/XMLWidgets/WidgetPathScheme.py,
line 2, in ?
    (Object: ElementIdPathScheme)
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/XMLWidgets/WidgetDOM.py,
line 7, in ?
ImportError: cannot import name ExtraDOM


------
2002-07-19T14:24:37 INFO(0) ZODB Opening database for mounting:
'142139120_1025192968.964287'
------
2002-07-19T14:24:37 INFO(0) ZODB Mounted database
'142139120_1025192968.964287' at /temp_folder
------
2002-07-19T14:24:38 ERROR(200) Zope Couldn't install ParsedXML
Traceback (innermost last):
  File /opt/Zope-2.5.1-linux2-x86/lib/python/OFS/Application.py, line
637, in install_product
    (Object: Zope)
    (Info: ParsedXML)
  File /opt/Zope-2.5.1-linux2-x86/lib/python/Products/ParsedXML/__init__.py,
line 92, in initialize
AttributeError: 'Products.ParsedXML.ParsedXML' module has no attribute
'ParsedXML'


I'm not a Zope or a Python expert.  Can someone
help me out here?  Is this just some sort of
shell environment issue?

Braun Brelin
bbrelin at yahoo.com


From phil at river-bank.demon.co.uk  Thu Jul 25 19:39:28 2002
From: phil at river-bank.demon.co.uk (Phil Thompson)
Date: Fri, 26 Jul 2002 00:39:28 +0100
Subject: Python, QT, PyQt in Windows
References: 
Message-ID: <3D408C30.2000308@river-bank.demon.co.uk>

Pablo wrote:

> Hi, there. 
> I am totally new in Python world(I started learning it from last
> weekend). I download the evaluation Python2.2 from Python.org. I
> download QT and PyQt, too. Now, my question is: how do I do Python
> program with QT or PyQt? In Python2.2, I have the IDLE, where I can do
> python program. But, in QT, the QT designer is for C++, in PyQt, there
> is no working environment at all. What do I need in order to take
> advantage of QT or PyQt when using Python?
> I saw a on-line book http://www.opendocs.org/pyqt/, but that is for
> Linux. I cannot follow the example in that book. Please, somebody who
> has the experience with Python, QT, PyQt in windows, tell me what I am
> supposed to do so that I can call the QT from Python.
> Thanks a lot.
> Pablo


I assume that you have downloaded the non-commercial edition of Qt for Windows.


The PyQt book isn't specifically for Linux - it applies equally to the 
Windows version.

Qt Designer generates GUI designs stored as XML .ui files. If you are 
programming in C++ then you use the uic program to generate C++ code 
that implements your GUI. PyQt includes the pyuic program that generates 
the corresponding Python code from the same .ui file.

PyQt includes eric, which does a similar job to IDLE, but requires Qt 
3.x - the non-commercial edition of Qt is based on Qt v2.x. An 
alternative is to buy the Personal Edition of BlackAdder from theKompany.

Phil




From K.Rdt at TU-Berlin.DE  Wed Jul  3 13:39:04 2002
From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt)
Date: Wed, 03 Jul 2002 19:39:04 +0200
Subject: HT clear some wxPython fram?
In-Reply-To: 
Message-ID: 

>> HOW I CAN CLEAR SOME FRAME?
---------------------------------------------------------------------
Hi

>My problem is, that the I want to monitor netstat; this 
>is in principle working (s.b.). But I don't want the scrolling
>frame for 2 reasons.
>  1.) ergonomic
>  2.) after a while of outputting the display
>       is stopping, I think for memory-reaons.

I can use Clear here:

class MyApp(wxApp):
	def OnInit(self):
		frame = MyFrame(self.stdioWin)
		frame.Show(TRUE)
		frame.Clear()    #### OK, but sensless
		self.SetTopWindow(frame)

But I want to clear the frame just bevor each new output
is given here:

class MyFrame(wxFrame):
..
	def OnTimer(self, evt):
		y=os.popen( 'netstat -a -n','r').read()
############# HERE 
		print "--------------------------------------------------------------"
		yy=y.splitlines()
		for i in yy: 
			if i[:5]=="  TCP":
				ry=string.split(i)
				print "%5s %22s %22s %22s" % (ry[0],ry[1],ry[2],ry[3])


		K at Rdt






From cliechti at gmx.net  Wed Jul 24 16:30:22 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 24 Jul 2002 22:30:22 +0200
Subject: embedded python question
References: <3D3E5A09.3020400@ntlworld.nospam.com> <0Xw%8.110704$Jj7.2636718@news1.tin.it> <3D3EA78E.50303@ntlworld.nospam.com>  <3D3EADD1.4020400@ntlworld.nospam.com>  <3D3EFC18.30705@ntlworld.nospam.com>
Message-ID: 

"Keith S."  wrote in 
news:3D3EFC18.30705 at ntlworld.nospam.com:

> Just wrote:
> 
>> Have a look at code.py in the std library.
> 
> Hmm, that looks interesting...
> 
> So in my C code I've something like:
> 
> char *code = "class Sout:\n"
>               "    def write(self, s):\n"
>               "        output(s)\n"
>               "\n"
>               "class Sin:\n"
>               "    def __init__(self, prompt):\n"
>               "        input(prompt)\n"

this class isn't what you want... you need to supply a callable either name 
that method __call__ and add a "return" of the result, or much simpler, 
leave it away and use your "input" directly below.

>               "\n"
>               "import sys\n"
>               "from code import *\n"
>               "from gld import *\n"

you're aware of side effects when using import "*"?

>               "sys.stdout = Sout()\n"
>               "sys.stdin = None\n"
>               "interact('---Starting Python---, Sin)\n"

if you pass a callable class it must be an instance, not a class object. 
but as said above, just use your "input" here.

> PyRun_SimpleString(code);
> 
> The input() C function returns Py_BuildValue("s", cmd ), where cmd
> is the cmd typed in the cmd line.
> 
> However this does not work... the output is something like:
> 
> ---Starting Python---
> >>>
> Traceback (most recent call last):
>    File "", line 15, in ?
>    File "C:\Python22\lib\code.py", line 307, in interact
> 
> console.interact(banner)
>    File "C:\Python22\lib\code.py", line 244, in interact
> 
> more = self.push(line)
>    File "C:\Python22\lib\code.py", line 265, in push
> 
> source = "\n".join(self.buffer)
> TypeError
>:
> sequence item 0: expected string, instance found
> 
> 
> Any clues on what's wrong here?
> 
> - Keith
> 
> 

chris
-- 
Chris 



From comcol at ukmail.com  Sat Jul  6 09:50:16 2002
From: comcol at ukmail.com (Comcol)
Date: 6 Jul 2002 06:50:16 -0700
Subject: sqlite-python-0.2.0.win32-py2.2.exe fails
Message-ID: <1b8c5fe1.0207060550.72952217@posting.google.com>

I tried to run
     sqlite-python-0.2.0.win32-py2.2.exe
on a Windows 95 machine, but it failed due to a page fault. *Sigh*

Any chance of getting one that works?

Also, I'm assuming that the file installs everything necessary to run
sqlite from python. I'm also assuming that the package is ready to go
"out of the box" - only installation being required. It would break my
heart to find out that I would actually have to (*try* to) compile
something, or install a whole bunch of other stuff (apart from Python,
of course) to get it to run. Am I right?


From pyth at devel.trillke.net  Wed Jul 24 17:41:49 2002
From: pyth at devel.trillke.net (holger krekel)
Date: Wed, 24 Jul 2002 23:41:49 +0200
Subject: How to get the method/function which called a function?
In-Reply-To: ; from cliechti@gmx.net on Wed, Jul 24, 2002 at 06:54:23PM +0200
References: <1027524712.2754.10.camel@taz.rv.dlevel.net>  
Message-ID: <20020724234149.I10625@prim.han.de>

Chris Liechti wrote:
> holger krekel  wrote in
> news:mailman.1027527338.25170.python-list at python.org: 
> 
> > Alessandro Iob wrote:
> >> def log(msg):
> >>      caller = GET_CALLER()
> >>      print repr(caller), msg
> >> 
> >> class A:
> >>      def t(self):
> >>           log('a message')
> >> 
> >> a = A()
> >> a.t() # prints " >> 0x805bb64>> a message"
> >> 
> >> How can I implement the "GET_CALLER()" function in "log()" ?
> > 
> > You can't.
> 
> sure you can get the name of the calling function. its printed when a 
> exception is thrown, isn't it? ;-)

oh, yes, you are right.  I probably was shortcircuiting on some 
other (only seemingly related) introspection problem.  Which
i can't even rememeber.  Maybe i need better introspection myself.

    holger



From bokr at oz.net  Wed Jul 24 21:09:35 2002
From: bokr at oz.net (Bengt Richter)
Date: 25 Jul 2002 01:09:35 GMT
Subject: get a list printed in hexadecimal notation
References:        
Message-ID: 

On 24 Jul 2002 16:41:18 +0200, Andreas Kostyrka  wrote:

>Am Fre, 2002-07-19 um 08.19 schrieb Oliver Eichler:
>> Bengt Richter wrote:
>> 
>> >  >>> l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)
>> >          ^                                   ^^^^^                   ^
>> >  >>> print  [isinstance(x,int) and hex(x) or x for x in l]
>> >  ['spam', '0xa', '0xf', 'more spam', ['nested', 65535, 'spam'], 'spam',
>> >  ['0xff']
>> 
>> I never do such complicated things at home ;) But you are right for more 
>> complex lists the one liner won't fit.
>Well it's not efficient, but:
>hexlist=lambda l: [(isinstance(y,list) and hexlist(y)) or y for y in
>[isinstance(x,int) and hex(x) or x for x in l]]
>l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)
>print hexlist(l)
>
>gives:
>['spam', '0xa', '0xf', 'more spam', ['nested', '0xffff', 'spam'],
>'spam', '0xff']
>
Cool, but did I miss something? why the two for's? E.g., (single line optional ;-)

 >>> hexlist=lambda l: [
 ...     (isinstance(y,list) and hexlist(y)) or
 ...     (isinstance(y,int) and hex(y)) or
 ...     y
 ...     for y in l]
 >>> l = ('spam',10,15,'more spam',['nested',65535,'spam'],'spam',255)
 >>> hexlist(l)
 ['spam', '0xa', '0xf', 'more spam', ['nested', '0xffff', 'spam'], 'spam', '0xff']

Regards,
Bengt Richter


From vvainio at tp.spt.fi  Thu Jul  4 10:04:43 2002
From: vvainio at tp.spt.fi (Ville Vainio)
Date: 4 Jul 2002 07:04:43 -0700
Subject: REPEAT... UNTIL ?
References:  
Message-ID: 

beej at piratehaven.org (Beej J?gensen) wrote in message news:...

> (The other side of the coin is that my only argument for more looping
> primitives is that while-1 loops are ugly-looking, and don't make for
> the most readable code.  Some people disagree or feel it's less
> important.  And personally I always feel like I'm undergoing some kind
> of algorithmic failure when I code one; like I must not be doing the
> Right Thing.  But in Python, it is.)

Strangely enough, while 1 - loop is quite often the most intuitive way
to do things, yet it's (implicitly) frowned upon in many programming
language cultures. The same applies to calling 'continue' instead of
elif. Flat is good. This seems to be mostly a documentation issue. It
would probably feel slightly less awkward if the keyword 'loop' was an
alias for 'while 1', but that will never happen.

-- Ville


From boud at valdyas.org  Fri Jul 26 08:09:34 2002
From: boud at valdyas.org (Boudewijn Rempt)
Date: Fri, 26 Jul 2002 14:09:34 +0200
Subject: Python, QT, PyQt in Windows
References:  <3d4115c6$0$31242$e4fe514c@dreader1.news.xs4all.nl>
Message-ID: <3d413c3d$0$94907$e4fe514c@dreader3.news.xs4all.nl>

Boudewijn Rempt wrote:

> Pablo wrote:
> 
>> Hi, there.
>> I am totally new in Python world(I started learning it from last
>> weekend). I download the evaluation Python2.2 from Python.org. I
>> download QT and PyQt, too. Now, my question is: how do I do Python
>> program with QT or PyQt? In Python2.2, I have the IDLE, where I can do
>> python program. But, in QT, the QT designer is for C++, in PyQt, there
>> is no working environment at all. What do I need in order to take
>> advantage of QT or PyQt when using Python?
> 
> 1. Windows
> 2. Python
> 3. qt non-commercial edition (download at trolltech)
> 4. PyQt binaries for windows (download at riverbank)
> 5. Any editor -- I'd advice Scintilla.
> 

Just to make sure, I just installed Windows 2000 on an old laptop,
and then started downloading and installing the above bit. From Python
to PyQt, the whole process took half an hour, and then the PyQt demo's
in my start menu ran without a hitch. It's really _easy_.

-- 
Boudewijn Rempt | http://www.valdyas.org


From markus.vonehr at ipm.fhg.de  Thu Jul  4 10:43:28 2002
From: markus.vonehr at ipm.fhg.de (Markus von Ehr)
Date: Thu, 04 Jul 2002 16:43:28 +0200
Subject: Full-screen display in Tkinter
References: <21298535.0207040554.6caeed01@posting.google.com>
Message-ID: <3D245F10.FDFE02DF@ipm.fhg.de>

root=Tk()
root.geometry(your_geometry)
root.overrideredirect(1)

your_geometry is:
"%dx%d%+d%+d" % (width, height, xoffset, yoffset)


Svein Brekke schrieb:

> I am building a slide show application with Tkinter, and need
> to create a full-screen window, i.e. supressing title bar
> and start menu etc.
>
> Is that supported in Tkinter?
> I work on Win2000 with python 2.2, but would like my code to
> be portable to other platforms.
>
> Any help or hints will be appreciated.
>
> Svein Brekke



From jc2astro at hotmail.com  Sun Jul 14 21:05:03 2002
From: jc2astro at hotmail.com (Jim Cerra)
Date: Sun, 14 Jul 2002 21:05:03 -0400
Subject: Q: Why does this work???
Message-ID: 

I'm very new to Python, and I've been examing a bit of code... I can't
figure out why the following doesn't produce an error:

# begin code
# ----------------------------

import string

# --- Global variables

total_hits   = 0
hits_by_page = {}  # maps document URL to hit count for that document

# --- Functions

def read_logfile(filename):
    inf = open(filename)

    line = inf.readline()
    while line != "":
        fields = string.split(line)
        process_request(fields[0], fields[3], fields[4], fields[5],
fields[6],
                        fields[7], fields[8], fields[9])

        line = inf.readline()

    inf.close()

def process_request(host, date, timezone, method, url, protocol, code,
bytes):
    global total_hits


    if code > "399": return # request was not successful, so don't count it

    total_hits = total_hits + 1

    url = string.split(url, "?")[0] # remove script arguments, if any

    if hits_by_page.has_key(url):
        hits_by_page[url] = hits_by_page[url] + 1
    else:
        hits_by_page[url] = 1

report_top = \
"""
Web server statistics

Web server statistics

> > > > I need a way to login to my router using a python script (automatic login). > I can't find a way to implement > this code in a script. I need help, or a site with an example.......:-(( Try something like: import urllib target = 'http://192.168.2.1:/login.htm' args = urllib.urlencode((('password','yourpass'), ('site, 'go'))) np = urllib.urlopen(target,args) etc. See the urllib docs for more info. From karaatanasov at hotmail.com Thu Jul 18 16:41:10 2002 From: karaatanasov at hotmail.com (Kiril Karaatanasov) Date: 18 Jul 2002 13:41:10 -0700 Subject: Python robot web client? References: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> Message-ID: <71a1c515.0207181241.56ea7903@posting.google.com> Have checked WebUnit ? May be it is going to do what you need. Or perhaps give some basis for your implementation http://sourceforge.net/projects/webunit From brueckd at tbye.com Tue Jul 30 15:39:16 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 30 Jul 2002 12:39:16 -0700 (PDT) Subject: global interpreter lock not working as it should In-Reply-To: <200207301708.NAA03182@test-area.com> Message-ID: On Tue, 30 Jul 2002, anton wilson wrote: > On Tuesday 30 July 2002 04:55 am, Martin v. L?wis wrote: > I would disagree. > In the Python documentation it states: > > "In order to support multi-threaded Python programs, the > interpreter regularly releases and reacquires the lock -- by default, every > ten bytecode instructions " > > What's the purpose of releasing an reaquiring the lock if no other threads > can run? Please consider that, because there's so many multithreaded Python programs that work quite well, it's rather unlikely that the threading implementation is outright broken. *Maybe* some improvement needs to be made, but from your posts it sounds more like you don't understand how things work at the C level, much less in Python. When the lock is released at the end of its regular interval, an *attempt* is made to reacquire it immediately, but there's no guarantee that the current thread will get it right away (and if another thread is already blocking on an attempt to get the lock then the other one will probably "win" most of the time anyway). > but the main problem is that the GIL is NOT implemented properly with > pthreads. That's an interesting perspective, except that there's a ton of multithreaded Python programs that work just fine. Granted, it is very common for the GIL to change hands due to blocking calls (I/O, sleep, etc.), but the put-it-up-for-grabs-every-10-instructions functionality works just fine too. Consider: import threading, time COUNT = 3 counters = [0] * COUNT def Worker(i): while 1: counters[i] += 1 for i in range(COUNT): threading.Thread(target=Worker, args=(i,)).start() while 1: time.sleep(1.0) print counters Here's some output: [162565, 176016, 165796] [329009, 327856, 333183] [497881, 496857, 498133] [665567, 679094, 643678] [810255, 845521, 811988] [968056, 1008142, 974790] Lo and behold, each thread is getting execution time, and nearly equal execution time at that! -Dave From hst at empolis.co.uk Wed Jul 17 08:57:51 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Wed, 17 Jul 2002 13:57:51 +0100 Subject: get a list printed in hexadecimal notation Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C8D@hendrix.empolisuk.com> Oliver Eichler wrote: > Sent: 17 July 2002 11:08 > To: python-list at python.org > Subject: get a list printed in hexadecimal notation > > > Hi > > Is it possible to print a mixed list with strings and numbers > and having the > numbers printed as hexadecimal notation? > > something like: > > >>>l = ('spam',10,15,'more spam') > >>>print l > ('spam',0xA,0xF,'more spam') > > or similar... > > The only way I could think of is to write my own print > function. Is there an > easy way? > > Oliver > print [type(x) == type(1) and hex(x) or x for x in l] Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From jolsen at mailme.dk Wed Jul 10 05:23:58 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 10 Jul 2002 02:23:58 -0700 Subject: Which OS? References: Message-ID: Gerhard H?ring wrote in message news:... > Tom Harris wrote in comp.lang.python: > > Greetings, > > > > How do I tell which OS is running from within Python? > > The usual answer is sys.platform, though I wish there was a better > one. Or for a second opinion: os.name Cheers Jesper From jepler at unpythonic.net Wed Jul 31 14:43:52 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 31 Jul 2002 13:43:52 -0500 Subject: a soft real-time system using pythonm In-Reply-To: <200207311632.MAA01291@test-area.com> References: <200207311359.JAA15020@test-area.com> <20020731145848.GC1800@unpythonic.net> <200207311632.MAA01291@test-area.com> Message-ID: <20020731184350.GB1413@unpythonic.net> On Wed, Jul 31, 2002 at 12:33:36PM -0400, anton wilson wrote: > O > > A realtime system places an upper bound on all operations, but the very > > nature of Python makes this impractical if not impossible. > > > > An interaction between Python's handling of the GIL and the platform's > > pthread library is going to be the least of your problems if you > > actually intend to deliver a system which gives realtime guarantees on > > Python programs. > > > > Jeff > > > If the soft-real-time system we use makes simple function calls and only uses > simple datatypes and possibly tuples, what are some of the potential pitfalls > we could run into? I understand the deallocation issue and the garbage > collection issue. (Does garbage collection have to be enabled?) Can we > somehow get an idea on the worse case time delays in python using only simple > function calls and assignments with small tuples and simple datatypes? I've already warned you of one. Python has two facilities for cleaning up objects which are no longer referenced: reference counting and cyclical garbage collection. Reference counting is the cause of unbounded delays for simple assignments, as in the second statement of x = [unique() for i in range(1000*1000)] x = 3 each unique() that was in x will be cleaned up by reference counting at the time of the second assignment. There's no easy way to place a limit on the size of containers. A similar problem rears its head with the similar x = [unique() for i in range(1000*1000)] x.append(x) # create circular reference x = 3 the need to free a million objects remains, but it will happen whenever garbage collection "feels like" it. The gc module provides some functions for modifying the behavior of the cyclic garbage collector. (This latter is handled by the CGC instead of refcounting because the refcount of x never actually falls to 0 -- it holds a reference to itself) Sorting is another lengthy operation. It usually takes around O(n lg n) operations to complete, where n is the length of the list being sorted. I don't see any attempt to periodically release/reacquire the GIL here. Of course, the comparison routines themselves may enter the bytecode loop, but if the contents are all hard-to-compare fundamental types this can still take quite awhile. One farily pathological object would be x = [ [[]] * 1000 + [random.random()] for i in range(1000)] (it takes ~4.5 seconds to sort this 1000-element list on my machine. Each element is made up of 1000 empty lists followed by a random float) Of course, even the lowly 64**64**64L can bring the interpreter to a standstill on a single bytecode. IMO, even "soft" realtime based on Python threads is not going to fly. These items are just off the top of my head, I'm sure there are more. And more still in any extension module you'd like to include. Jeff From dwelch91 at nospam.attbi.com Tue Jul 30 00:59:42 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Tue, 30 Jul 2002 04:59:42 GMT Subject: Win32 API question - Postmessage and Win2K lock window References: <4d3df955.0207291235.1a8916b@posting.google.com> Message-ID: <3D461D3B.6050609@nospam.attbi.com> Mark Erikson wrote: > Hey, folks. I've got a problem regarding the PyCwnd.PostMessage() > function behind the Windows 2000 lock window. I know this is more of > an API question than a Python question, but figured it was worth > asking here just in case. > > Basics of the issue: > I'm trying to automatically launch the Windows 2000 Defrag utility. > While any user can launch it, the defrag function can only be > activated by an administrator. By getting the window handle and > creating a PyCwnd from the handle, I can do PostMessage() to the > window and send WM_KEYUP and WM_KEYDOWN messages. When run as an > administrator, I can successfully simulate the keystrokes needed to > start the defragmentation. However, this needs to be run on other > users computers, most likely during lunch. So, I've been working with > Win2K's "runas" utility. It requires that a password actually be > typed in, though no input is visible. Again, I can use PostMessage to > send simulated keystrokes to the Command Prompt window, runas > completes successfully, Defrag launches, and everybody's happy. The > problem comes when I try to deal with people using the CTRL-ALT-DEL > "Lock Window" function, which absorbs any standard keyboard input > (which is why I'm using WM_KEYUP/DOWN instead of a more standard > SendKeys type deal). If I'm just running Defrag, I can still > successfully use PostMessage() and activate it. *IF*, on the other > hand, I launch Runas behind the lock window, *I cannot send the > keystrokes*. > > I've looked at everything from using pipes to replace stdin to using > other Runas-type utilities (SU, sfImpersonator, etc) to using > WriteConsole() to too much other stuff to remember. Nothing I've > experimented with has seemed to work. > > So... does anyone have any ideas? I just need to be able to simulate > keystrokes for a password to a Command Prompt window for which I have > a handle, BEHIND the Win2K lock window. I'm open to any suggestions, > including stuff that I've looked at already (since it's quite possible > I missed something). > > Thanks in advance! > > Mark Erikson > > markulus00 'at' yahoo 'dot' com I've tried automating things on Windows like this before with very mixed results. I would recommend trying to run the app with a command line or using a COM automation interface before attempting throwing keystrokes at it. A collegue has had quite a bit of luck using the Windows Scripting Host to do this sort of thing. Each of these (well, at least running the app with CreateProcess()) has a "place" to stick in security SIDs and DACLS and such that should let you get around the administrator requirement. I would hit MSDN with some searches and cross your fingers... Good luck, Don From garyr at fidalgo.net Tue Jul 2 22:05:42 2002 From: garyr at fidalgo.net (Gary Richardson) Date: Tue, 2 Jul 2002 19:05:42 -0700 Subject: newbie question on getting Blt to work with Pmw on Windows References: Message-ID: See Howard Lightstone's post of 5/28/02 "John Boik" wrote in message news:FTaU8.3411$Ze2.1481086991 at newssvr30.news.prodigy.com... > Hello. I have installed Python for windows (XP). I have also installed Pmw > and got it to work. I have also downloaded and used the self-installer for > Blt for windows. However, when I run the Pmw demos, it will not let me run > the Blt-associated ones. The Pmw demo program tells me that Blt is not > installed. Probably there is something I need to do to tell Python that it > is there, but I do not know what that would be. Do I need to use an import > statement in Python? And if so, what is the name of the modeule I am > importing (what file is it so I can find the path)? > > Thanks. John > > > From jerf at jerf.org Sat Jul 27 10:34:17 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 27 Jul 2002 14:34:17 GMT Subject: a little trap revealed (was Re: Let's Talk About Lambda Functions!) References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> Message-ID: On Sat, 27 Jul 2002 02:11:46 -0500, Alex Martelli wrote: > Jeremy Bowers wrote: > Not sure why you snipped the closure solution, which looks like > the obvious one to me once one has seen it: Oops, sorry, too late. I ended up scrolling over it. >> (And I'll still take the lambda form; the def statement feels wrong here.) > > Guess that's what wrong with having lambda in the language: without > adding any capability, it gives two ways to solve some problems, one > of which feels wrong to you, the other one of which IS wrong. Fair enough. > Because, you see, I put a little trap in this example... and it > seems to me that you fell right into it. Yes and no... I never wrote a lambda myself that had a print in it. I know you can't do that, and others had already commented on it. I almost always use a print function of my own devising, so I _can_ use print in a lambda. (That's not why I wrote that function though; I like emacs as my coding environment, but you get all the output and error tracebacks all at once, as a lump when you close the program, if it's a Tk program. I have a print function that can go over the network, or to console, or to nowhere at all.) > Use def and avoid all of this silly self-imposed useless work. I already don't use "print" so perhaps that part of the reason it doesn't bother me. (Note I'm not proposing this is a solution everyone should seek, just that it may explain my ambivilence on the issue.) From whisper at oz.net Thu Jul 18 20:08:37 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 18 Jul 2002 17:08:37 -0700 Subject: HTML DOM parser? In-Reply-To: <3D373D7C.2237E7A3@engcorp.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen > Sent: Thursday, July 18, 2002 15:13 > To: python-list at python.org > Subject: Re: HTML DOM parser? > > > Paul Rubin wrote: > > > > Anyone know of a Python-callable HTML DOM parser? I mean a serious > > one that tries to understand the crappy malformed out there in the > > real-world Web, the way a browser does. If it can interpret > > Javascript that's even better. This is for a consulting client, so a > > commercial library would be acceptable (though not preferred). > > How about automating IE using Python? > > from win32com.client import DispatchEx > > ie = DispatchEx('internetexplorer.application') > ie.visible = 1 > ie.navigate('http://www.nightsong.com') > dom = ie.document > > etc... > > Access to the DOM tree of the document might be too slow for your > needs, but if it's not, you definitely get a lot of bang for the buck... > > -Peter I put the above code into "ienavigate.py" and tried it and got: Traceback (most recent call last): File "ienavigate.py", line 6, in ? dom = ie.document File "J:\Python22\lib\site-packages\win32com\client\dynamic.py", line 448, in __getattr__ raise pythoncom.com_error, details pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None) Also got a browser window with a "403" error telling me I don't have permission to access index.html on www.nightsong.com. I would be interested in getting this working, so any help is appreciated. TIA, Dave LeBlanc Seattle, WA USA From sandeep182 at hotmail.com Mon Jul 8 10:53:42 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: 8 Jul 2002 07:53:42 -0700 Subject: Python 2.1 == Jython 2.1 != Python 2.2? Message-ID: Do Jython version numbers correspond to Python version numbers? Should I expect any Python 2.1 application to run in Jython 2.1? Should I expect Python 2.2 features in Jython 2.2? If so, is there an ETA on Jython 2.2? We are considering moving our application from Python 2.2 to Jython and the answers would help us decide. Thanks! Sandeep From vvainio at tp.spt.fi Thu Jul 4 10:04:43 2002 From: vvainio at tp.spt.fi (Ville Vainio) Date: 4 Jul 2002 07:04:43 -0700 Subject: REPEAT... UNTIL ? References: Message-ID: beej at piratehaven.org (Beej J?gensen) wrote in message news:... > (The other side of the coin is that my only argument for more looping > primitives is that while-1 loops are ugly-looking, and don't make for > the most readable code. Some people disagree or feel it's less > important. And personally I always feel like I'm undergoing some kind > of algorithmic failure when I code one; like I must not be doing the > Right Thing. But in Python, it is.) Strangely enough, while 1 - loop is quite often the most intuitive way to do things, yet it's (implicitly) frowned upon in many programming language cultures. The same applies to calling 'continue' instead of elif. Flat is good. This seems to be mostly a documentation issue. It would probably feel slightly less awkward if the keyword 'loop' was an alias for 'while 1', but that will never happen. -- Ville From chris.gonnerman at newcenturycomputers.net Tue Jul 9 01:16:02 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 9 Jul 2002 00:16:02 -0500 Subject: Help with Popen in 2.2 References: <3D2A3749.2BBA7545@engcorp.com> <9lgkiugo6994icr13cnud8hp7q8bjb6kdo@4ax.com> <3D2A57B9.8EDD2BF0@engcorp.com> <14rkiu8fnp8chiua156k2qm9r1s2vf5trs@4ax.com> Message-ID: <003a01c22707$bcbf4060$0101010a@local> ----- Original Message ----- From: "Lowel Stern" > On Mon, 08 Jul 2002 23:25:45 -0400, Peter Hansen > wrote: > > >Please post the code that generates this message. The code > >_can_ be fixed. > > > >-Peter > > > -------------------------------------- > import os > key = "%s %s" % ('"stern:STWA"',"1234") > print key > fp = os.popen('C:\python_scripts\prog %s') % (key) > --------------------------------------- Thar she blows. The line most likely should be: fp = os.popen('C:\python_scripts\prog %s' % key) Note that the parens after the function or method name bind "tighter" than the % operator. The call is made FIRST, then the % operation. It needs to be the other way. > fp = os.popen('C:\python_scripts\prog %s') % (key) > Traceback (most recent call last): > File "", line 1, in ? > fp = os.popen('C:\python_scripts\prog %s') % (key) > TypeError: unsupported operand type(s) for %: 'file' and 'str' > Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From leader730 at hotmail.com Fri Jul 12 01:52:42 2002 From: leader730 at hotmail.com (Joseph Youssef) Date: Fri, 12 Jul 2002 01:52:42 -0400 Subject: newbie question: getting rid of space in string :( Message-ID: Hello, I'm new to python and I'm writing a very small script which takes each letter of a string and adds text to it (I know this is not a good explanation but you'll understand below :) ) anyway, this is my current code: def textColor(string, color1, color2): color = color1 for a in string: print "<" +color+ ">" +a+ "", if color == color1: color = color2 else: color = color1 so when I run let's say textColor("testing","black","red") it returns: t e s t i n g now this works just fine exept that space in between each block of text, I can't get it to stick together, now I know this is a very easy question but I need some quick help thanks -- Too often we lose sight of life's simple pleasures. Remember when someone annoys you it takes 42 muscles in your face to frown, BUT, it only takes 4 muscles to extend your arm and bitch-slap that mother@#?!&! upside the head! -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfackrell at DELETETHIS.linuxmail.org Tue Jul 9 15:19:39 2002 From: dfackrell at DELETETHIS.linuxmail.org (Daniel Fackrell) Date: Tue, 9 Jul 2002 13:19:39 -0600 Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: <3d2b374d$1_2@hpb10302.boi.hp.com> "Charles Hixson" wrote in message news:agfb5204pg at enews3.newsguy.com... > Alex Martelli wrote: > > Robb Shecter wrote: > > > > > >>Brian Quinlan wrote: > >> > >>>... Actually, private instance > >>>variables are uncommon in general. > >> > >>Sounds like a difference in design philosophies. In my code, private > >>everything is the norm, with a very thin/small public API. > ... > > Alex > > > > If you are subclassing a class that someone else has written, you don't > want to accidentally redefine an internal name. Sorry. I can accept > that you should be able to explicitly access it, but to be able to > change it by accident is (would be?) a misfeature. > > I didn't believe that this happened in Python. It does, and it seems a > significant flaw. My understanding is that if you define a variable in > a class that subclasses another class, then unless you take definite > steps to cause things to happen otherwise, you are defining a new > variable that is local to the scope of the class that you are currently > defining, and will not impact routines that you call from parental > classes. Experiment shows that this isn't what happens. > from __future__ import nested_scopes > does not fix this problem, as I assumed that it would. > > Let's be explict: > from __future__ import nested_scopes > class A: > def ma(self): > print "ma, ma" > def pa(self): > self.ma() > class B(A): > def ma(): > print "hello, world" > tst = B() > tst.pa() > > Testing this produces the message, "hello, world" > This seems to be the wrong message. The version of pa that was called > was the version defined in class A, so the routine called should have > been the routine defined in class A. > > Or, to me more accurate, for libraries to have maximal portability, I > would want the message to have generated "ma, ma", and I had been > assuming that nested_scopes would result in that being the message that > was produced. > -- > -- Charles Hixson > Gnu software that is free, > The best is yet to be. You can get the behavior you wanted by defining A as: class A: def ma(self): print "ma, ma" pa=ma -- Daniel Fackrell (dfackrell at linuxmail.org) When we attempt the impossible, we can experience true growth. From jvb at hereinsa.net Mon Jul 15 13:42:39 2002 From: jvb at hereinsa.net (jvb) Date: Mon, 15 Jul 2002 19:42:39 +0200 Subject: Must Read !! Message-ID: A Fish Out Of Water (racism and other myths) "True wisdom is not manifested in trying to see resemblances in things that differ. But in discerning the real difference among those things that resemble one another" When did the responsibility for the evolution of African people (and other recently discovered primitive races) become the responsibility of the first world, and the 'Whites' in particular? They blame the whites for underdevelopment, but how much development did they manage before the colonists arrived? The development of the western infrastructure has taken place over thousands of years. They now expect this same infrastructure to be created and financed for them by the west- immediately! Anyone who knows of the disparity that existed when the first settlers landed in Africa, or other primitive areas, will realise that this disadvantage is not the result of colonization, or anything else, other than evolution. Their lack of progress or inventiveness since the dawn of mankind is proof enough of that. Everything they have has been handed to them on a plate by the white colonists, even the aircraft which they now fly around in to demand even more. We owe them nothing !! This stunted (by European standards) evolutionary path is now blamed on 'Whites', and a concerted attempt is being made to instill a guilt complex on the 'Whites', under the pretext that they would be on a par if it were not for colonization and slavery. When in truth, while left undisturbed by white colonists for millions of years, their rate of progress or change was insignificant. The wheel was unknown to them, they had no written language and processes which they stumbled across, such as ore extraction, were never refined or improved etc. etc?). In contrast, the Western World progressed in leaps and bounds. Their shelter construction techniques are even borrowed from the nest building methods of the local birds. They just do not have enquiring or inventive characteristics. Nor do they have an industrious or charitable bone in their bodies. The cradle of mankind is southern Africa, and it is no coincidence that the further away from it you move, the more progress took place. It is because the genetically and intellectually more advanced and hence more inventive, inquisitive, and industrious members of our ancestors explored and migrated, while the dormant ones remained where they were. If it were not for 'White' colonists they would still be ignorant of the technological and scientific achievements of the first world, which they now envy but fail to understand and are generally unable to achieve. Primitive instincts of reproduction, lack of sexual control, tolerance of violence, brutality, and self-interest, are natural for their position on the evolutionary curve. In the environment that would prevail in Africa, if it were not for Western influence/interference, they would be attributes essential to survival. Their evolutionary path has made them more adapted to survival and physical activities. The natural attrition from famine, plague etc. which nature uses to maintain a balance, has been disrupted by Western technology. (Without time for the natural evolutionary adjustment of the reproductive rate to take place.) It is by means of western medicine, agriculture, peacekeeping efforts, aid, etc. coupled with their inability to overcome primitive reproductive instincts, that they have multiplied to the point that the continent can no longer support their numbers. This is not to say that one evolutionary path is better than the other. However the path taken by the 'White', and Eastern, races has resulted in them developing an environment and culture tailored to their own development, and the African races, for theirs. Thousands of years of evolutionary progress and technological advancement was thrust on them in the blink of an eye, on the timeline of evolution. This has resulted in the 'Fish Out Of Water' syndrome, which we see today with respect to Africa, African people and other tribes of recently primitive origin, when trying to impersonate the western way of life. The more advanced along the evolutionary curve a race or tribe was when the western world arrived on their doorstep, the better they are able to assimilate into our environment and culture. It is also the reason that, as soon as the environment shifts/deteriorates back to what is more suitable to the skills, characteristics and morals of the indigenous people, the Whites/settlers become the 'Fish Out Of Water', are unable to survive, and generally migrate to environments more compatible with their cultural evolution and concept of morals and rights. This then results in a faster regression, (or is it just the return to normality and suitability for the indigenous people?). The difference between their concept of morals and ours is vast. We have western governments trying to force democracy on them, regardless of the fact that they do not understand the principle, as can be seen by the civil wars which erupt after every (usually rigged) election. Why would they embrace democracy? When historically their lives and cultures have been controlled by autocratic kings and chiefs- and still are, regardless of the veil of democracy put in place to appease the West. This superficial democracy is only tolerated because it is seen as a requirement to access the aid, wealth and trappings of the western cultures. When combined with the rampant bribery, corruption and incompetence of the elected officials (elected through intimidation and vote rigging, easily accomplished with this underlying structure) it is farcical. The quality of a democracy is proportional to the collective intelligence of the electorate. Democracy in Africa is the election of the incompetent and corrupt by the i gnorant and illiterate. We Prop up, enforce and subsidise systems, which are foreign to them-just because it offends our principles and morals. Recent tradition was/is such that if you wanted/needed something, which another chief/tribe had, you simply gathered your army and conducted a raid. The cattle, women, food, etc. were then yours. (These being the prized possessions of the evolutionary period - and generally still are) Selfishness, violence, theft (our definitions) etc. are not faults in their indigenous environment, but essential components of the survival skills that they have evolved in order to cope in this harsh and unforgiving environment, which existed when they were discovered by the western world. Why do we have more concern for their suffering than their own do? The images of starving or homeless children etc. are paraded as a means to access our generosity. While they themselves care little. There is always an abundance of money for arms etc. to ensure that they stay in power. Most of these children have been abandoned or orphaned as a result of their primitive characteristics (self-interest, violence, etc.). Any aid received is usually stolen, sold on the black market or misappropriated. They wail constantly about human rights, equality etc. when they themselves rule through brutality and intimidation and are so racist that it extends down to tribal intolerance. They do not share the generosity or charity of the ' Whites' especially in times of shortages (a permanent feature of Africa now, due to overpopulation). They have however become masters at the art of manipulating this failing of the 'Whites'. Making full use of our religious principles and the much-misunderstood notion of equality. Any notion of equality (of man or anything else in nature) other than in a religious context- is absurd. Not even identical twins are equal. If equality were a reality, then the process of natural selection would be nullified. And all evolution would end. Even more absurd is the misconception that this equality can be achieved through education. If education could override evolution, then anyone could be taught to be a DaVinci, Einstein, Johnson or Jordan etc. or one could teach a Zebra to be a Racehorse. Education Is No Substitute For Evolution!!!!!! The concept of (religious) equality has been subverted and distorted and used mainly by the communists to de-stabilize the colonies and mixed societies (so called freedom struggles etc.) so they themselves could gain a strategic advantage. This misconstrued version of equality was embraced by the ignorant, the gullible and the greedy. Another misconstrued and abused concept is 'Racism'. It is natural for groups, with similar cultures and interests, to have an affinity for each other and to congregate and associate along these lines. This occurs as much amongst a group of mixed nationality or mixed interest white group as it does amongst a mixed ethnic or white/ethnic group. However, when there happens when other races present it is no longer natural, but racist! Why are there no quotas, affirmative action etc. for other nationalities, races etc? Why only for blacks? A joke may be made about the Irish, Australian, French, etc. In fact anyone other than a black race or nationality- this is suddenly Racist! This is just another component of the concerted effort to instill a guilt complex on the Western/White races, to disguise the inability of the recently primitive races to cope in the western environment and to force us to alter our environment so that they can cope, or to give them the benefits regardless of whether they cope or contribute or not. Why is it acceptable to have Black unions, business associations etc, or for blacks to dominate certain sports such as basketball? (Rightly so, since they have the best attributes and skills for these activities- just as it is right for other groups with different attributes and skills to dominate the fields which suit them) They are suspiciously quiet about the teams not being representative of the USA etc. No quotas asked for here! Louis Farrakan is entitled to his opinion (ask any black) but a white person is not entitled to these same opinions. This would be racist. As soon as any similar situation is reversed then it is Racist!! What happened to OUR rights to freedom of association? Just as the disabled person requires a permit/sticker to get preferential parking, access etc. - So should anyone else, requiring preferential treatment in the modern western world, admit that they cannot cope with the normal western environment- And wear the badge of their disability!! If they were equal then this would not be necessary. At first, slavery/racism was to blame, for an inability to cope and/or achieve in the technologically advanced environment of the western world. When racism was abolished and they were granted 'equal access' or 'equal opportunity'-(the only right anyone should have)- and still could not cope, the cry changed to 'affirmative action'. Now, those that have equal access, affirmative action and education, and still fail to achieve, demand that they be given the qualifications/positions/benefits etc. regardless (Quota's etc.), or that the standards be revised/reduced- resorting to violence and arson etc. (instinct) to realize their absurd demands, or simply obtain credentials through fraudulent means. The proliferation of fraudulent degrees, driver's licenses and now even pilots licenses is ample proof. The Soccer World Cup bid by South Africa is another example of the strategy of using guilt to achieve their goals. With claims of 'it is our turn', 'racism', etc. and a total disregard for the technical quality of the other bids, they try to force acceptance of theirs. England lost out through a few hooligans- but the World is expected to ignore the violent, murderous anarchy and crime in Southern Africa. Even a halfwit can see where the projections of current trends of crime, violence, rape, aids, instability, etc. lead to in 2010. Only a fool would commit to an event of this scale, in the distant future of such an unstable, deteriorating and mismanaged environment. Just as after any other lost election, there in no acceptance of the process or outcome, nor any dignity in defeat. We should be grateful however, that they have not initiated an armed (freedom?) struggle against the world soccer body, Germany or NZ for that matter. The attacks on busses by the taxi associations (and on each other) are another example of African free enterprise. Who needs advertising or competition when you have got an AK47? The quality of government is a reflection of the collective intelligence of the electorate - Just a cursory look around Africa will explain what you are dealing with. After demanding freedom etc. They screw up their own country then flood illegally into other countries to screw them up as well. (usually Western countries run by the whites which they despise) I may have equal access and rights to the Arctic, but I will never be an Eskimo! If I should try, and not be able to cope with the demands of the arctic environment - do I have the right to demand that the environment be changed to compensate for my inabilities? Or that other competent Eskimos be excluded so that I may appear to be excelling. Then if this is not done- to claim that I am the victim of racism or otherwise disadvantaged. Should I contract AIDS through my inability to control my sexual urges, or I am a drug addict, do I then have the right to demand free medication and treatment. Paid for with our hard earned tax dollars. You do not catch Aids- You have to go out and get it!! What about those with other illnesses, which are not self inflicted- Will this benefit be extended to them as well or are they now happy to again blatantly discriminate, as long as it benefits them. Are the drug companies going to give the same consideration to all the ill people of the world, or do they consider the lives and health of non aids sufferers to be of lesser value. Aids is a self inflicted and self eradicating disease. Nature is cleansing the planet of deviants and evolutionary retards, and restoring the balance which we have disturbed. Just let it run its course. If I insisted on working in a nuclear physics research environment but understood little of nuclear physics- should I demand that they revise their entrance requirements or research only basic elements? Why then, when certain groups fail to score as high as other groups, on the tests designed to access suitability for the technological Western environment, such as IQ etc.- do they claim that these tests are racist and demand that they are revised. The same applies to Western educational institutions designed to prepare one for the demands of a technological age. The list of examples of these anomalies is endless, yet we accept them daily. It is amazing how frequently the term 'DEMAND' is used by groups that have contributed little to, or even hindered, the progress of Modern Civilization. Even more unbelievable is how willing we are to consent to such demands, no matter how ludicrous!! Thereby hindering our progress still further. Instead of moving forward with our own culture, our time and efforts are being consumed by efforts to alter our society/environment to accommodate those who are foreign to it and who do not contribute to it. Is this an attempt to slow down our progress, in the hope that less evolved groups can catch up? Any environment or group, to which they are not suited or are unable to achieve in, is branded as racist. Consider the following scenario:- A genetically similar, but technologically superior, alien race arrives on our planet and promptly replaces all our familiar technology with theirs and alter our environment with new transport, construction and farming techniques etc. Our language and written communication is replaced with telepathy. This technology works on principles, which we are not yet able to conceptualize. All control is achieved by means of mental telepathy etc. and a careless thought results in damage or catastrophe. They also replace all the familiar laws, rules and religious principles, with their own, the transgression of which results in swift retribution. All the necessary educational institutions are provided - where all lectures are presented telepathically on the assumption that we have evolved sufficiently to grasp their concepts. They then decide that we are their equals and charge us with the responsibility for this new environment. If anyone of them protests that we are not prepared (evolutionary) for the task, they are told that they are racist. How competent would we be in this environment? How frustrated? -- 'Fish Out Of Water' perhaps? This is the equivalent experience of the more primitive groups. Unless we accept that we are different, (even genetically- hence the easy identification of race by forensics) have different needs and that we are not all comfortable, suited to, or able to cope, in the same environment- we cannot hope to avoid conflict. We need to stop forcing a foreign environment on others and above all stop trying to adopt a culture, which is unnatural, and then complain that they are disadvantaged. All the valid genetic, physiological and psychological studies that have been done which highlight the differences between the races have been covered up as racist. How much longer are we going to paint over hard facts with the brush of political correctness? There will always be exceptions in any group. Usually these are paraded as proof of equality. However neither nature, nor evolution is governed by exceptions. Which exception or oddball's characteristics would determine the environment for the rest of us? The Whites do not hold up Albert Einstein as an example of Joe Average! Any suitable environment will always be governed by and evolve to the average requirements of a particular group or species. Forced adaptation of our environment in an attempt to accommodate these races will simply retard western progress. Just consider the contribution to western progress and lifestyle the trillions of dollars, squandered in Africa in the futile attempts to drag them into the modern era, could have made. THESE ARE YOUR HARD EARNED TAX DOLLARS!! ANY attempt to create a single environment for everyone will of necessity be a retrograde step, and result in it not being ideally suited to anyone - Resulting in feelings of discrimination on all sides and conflict. How much longer are we going to keep our heads buried in the sand and ignore the obvious? Only a fool defies the laws of nature. Why are the so called aids activists not telling aids infected women to not get pregnant, instead of demanding that millions more of our tax dollars are wasted on useless free aids treatment- just to create a generation of orphans which will consume even more aid and who will probably infect themselves with aids by the time they are in their teens! We must apply our efforts to improving our environment and culture for ourselves and not allow our evolution and progress to be retarded by these groups. (Yes, evolution is an ongoing process) If they insist on trying to impersonate the western culture then it must simply be a case of 'sink or swim' or 'fit in or FO'. We must not sacrifice our identity or allow our race/group to be swamped by foreign entities because of our generosity Evolution will not respond to any 'DEMANDS'!! The concept of racism was created to avoid the myth of equality being exposed. Remember this document the next time you see a parasitic minority march or a demonstration trying to force their opinion on you or demanding that you hand over our resources for them to squander. --- If you had to run riot in the streets smashing windows, Looting, Burning cars etc. you would probably be shot. If however you were part of a minority mob (especially black) trying to negate democracy by forcing their opinion on others, then you would somehow be immune to prosecution. They expect the whites to grant them rights and priviledges which they do not grant each other !! JVB "Western man towers over the rest of the world in ways so large as to be almost inexpressible. It is Western exploration, science, and conquest that have revealed the world to itself. Other races feel like subjects of Western power long after colonialism, imperialism, and slavery have disappeared. The charge of racism puzzles Whites who feel not hostility, but only baffled good will, because they don't grasp what it really means: humiliation. The White man presents an image of superiority even when he isn't conscious of it. And superiority excites envy. Destroying White civilization is the innermost desire of the league of designated victims we call 'minorities.'" A WHITE COLONIST'S APOLOGY We white colonists wish to make a confession. We confess our sins against the black people of Africa (and those of our forefathers), which are outlined in detail below:- 1. We apologize for giving them doctors, new hospitals, medical services that enabled them to survive plagues, disasters and to multiply into uncountable numbers. 2. We apologize for teaching them to read and write the English language and even for putting their own languages down in writing for them. We even taught them mathematics and built hundreds (if not thousands) of schools for them even rebuilding and repairing same when they burnt them down or vandalized them. 3. We apologize for building factories and shops, which gave them work. We apologize for taking them into our houses to work, giving them food and even paying them. 4. We apologize for building farms out of barren bush and gardens from which we fed them . 5. We apologize for giving them clothes and shoes instead of leaving them in the animal skins they wore before we found them wandering aimlessly around the plains, mountains and valleys not having evolved sufficiently to invent even the wheel or written language. 6. We apologize for extracting minerals from below the earth, minerals which had always been there but were unknown to the local inhabitants. We apologize for paying them to work in these mines. 7. We apologize for those among us who established charity organizations to feed and clothe them while they themselves never knew, or know now, the meaning of charity. 8. We apologize for building a network of roads all over the country which they now use to give Africa one of the highest road accident rates in the world. 9. We apologize for building huge dams which keep them supplied with fresh water, even in times of drought. 10. We apologize for paying the lion's share of the countries tax burden while spending the least upon ourselves. 11. We apologize for giving them modern construction techniques which enabled them to move out of the mud and grass structures which they copied from bird's nests. For all these evil sins we most humbly beg forgiveness, and if they will only accept our apologies, we will gladly take back all of the above mentioned evil deeds and leave them where and as we found them. !!!! The current inhabitants of Egypt had nothing to do with the creation of its constructions. Which is why they have no knowledge of their creation. In fact it is western man who has provided the most insight into their mysteries, including the ancient languages. Do you think that their ancestors just forgot to mention an achievement of that scale and significance? Did they forget to write down the details despite having invented the first known written language? They were either built by another race on their way north and who moved on, or who died out from disease. (the more likely scenario) The current inhabitants are merely nomads who stumbled across it. They are nothing more than squatters claiming credit for others achievements. From shalehperry at attbi.com Wed Jul 3 11:46:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 03 Jul 2002 08:46:26 -0700 (PDT) Subject: Regular expressions in python In-Reply-To: <3D231C1E.FBB4BE89@ilangua.com> Message-ID: On 03-Jul-2002 Graeme Longman wrote: > Hi, > > I'm using the python module re to search through strings of html text > but I have found that it is taking too long using the seach method. > > I am looping though a list of regular expressions and I find that it > takes much longer when no match is found for the expression than it does > when a match is found. Is this normal ? > > I have fixed the problem for now by using string.find() before searching > the text but was wondering if anyone had any ideas on a better > technique. > > Is there something else I should be using ? I am using '.*' and > re.DOTALL in my expressions but that doesn't seem to be the problem. > > Thanks for any help in advance. > sometimes regexs are not the answer, sometimes they are the best answer. string.find is sometimes a solution. Other times the htmllib module is a better choice. Perhaps if you pasted a sample we could help you decide. From fredrik at pythonware.com Wed Jul 24 14:20:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 24 Jul 2002 18:20:13 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: "Shagshag13" wrote: > so using it like i use it, is ok ? (even if it's over complicated). sure. on my machine, the readlines version is actually about 15% faster, given a large enough file. ymmv, as usual. From christophe.delord at free.fr Mon Jul 8 16:49:56 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Mon, 8 Jul 2002 22:49:56 +0200 Subject: List assignment, unexpected result References: Message-ID: <20020708224956.5e4eedb4.christophe.delord@free.fr> On 8 Jul 2002 13:20:15 -0700 steve.coates at talk21.com (Steve Coates) wrote: > A friend of mine recently sent me some code and asked if I could > predict what it would do. I guessed wrong. Code as follows:- > > grid = [['.'] * 4 ] * 4 The problem is that ['.'] * 4 is instanciated 1 time and grid is a list containing 4 "pointers" to the same sublist. Decompose it like this: row = ['.'] * 4 grid = row * 4 so grid[1][1] = '1' is equivalent to row[1] = '1' because (grid[1])[1] is row[1] so grid is now [ '.', '1', '.', '.' ] * 4 The solution is to instanciate 4 different rows like this for example : grid = [ [ '.' for x in range(4) ] for y in range(4) ] > grid [0][0] = '0' > grid [1][1] = '1' > grid [2][2] = '2' > grid [3][3] = '3' > for i in grid: print i > > The intent is clear i.e. fill the diagonal with 0,1,2,3; but the > result is somewhat different. Could anyone explain why this doesn't > work as expected - and even better, come up with an assignment for > 'grid' that would work. My only suggestion was an explicit > [['.','.','.','.'],['.','.','.','.'],etc. but it gets a bit cumbersome > for large grids. > > Thanks > Steve -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From rs at onsitetech.com Wed Jul 24 19:27:28 2002 From: rs at onsitetech.com (Robb Shecter) Date: 24 Jul 2002 23:27:28 GMT Subject: Base classes or global functions References: Message-ID: <3D3F37E0.2000209@onsitetech.com> Stephen Boulet wrote: > I have two classes, Class1 and Class2. Class1 contains a list of Class2 > objects, but no inheritance is involved > > Both classes use some functions I wrote. What's the best way of making the > functions available to the classes? > Good questions. To answer it, we'd have to know what the functions do - what information they manipulate. Depending on your answer, any of the following scenarios are possible: 1. The functions become methods of Class1. 2. The functions become methods of Class2. 3. The functions become methods of a new, as yet unwritten class. 3a. This new class would be used by Class1 and Class2 3b. This new class would be subclassed by either Class1 or Class2. Robb From g.vonrotz at chello.nl Wed Jul 3 18:15:05 2002 From: g.vonrotz at chello.nl (Ria) Date: Wed, 03 Jul 2002 22:15:05 GMT Subject: how can I put mysql input without ([,]) References: Message-ID: And how about when I use: cursor.execute("select column_1, column_2, column_3 from tabel") then I am not abel to get only text? ('text','text','text') ('text1','text1','text1') ('text2','text2','text2') ('text3','text3','text3') I need text text text text1 text1 text1 ent. Bennie, B From marklists at mceahern.com Wed Jul 3 09:08:02 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 3 Jul 2002 08:08:02 -0500 Subject: what's up with 'patterns'? In-Reply-To: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> Message-ID: > i've seen several topics referring to 'patterns'. > > i am unfamiliar with this. could someone explaint to me what this is all > about? On one level, you can just take the term at face value. That is, look the term up in the dictionary and apply its meaning(s) to software engineering: A consistent, characteristic form, style, or method. People have observed patterns in good software engineering and they have given these patterns names so that they can be studied and emulated. You'll hear people refer to the GoF, or gang of four. These are the folks who wrote the seminal Design Patterns book: http://www.amazon.com/exec/obidos/ASIN/0201633612/ There's the Portland Pattern Repository: http://c2.com/cgi/wiki?PortlandPatternRepository which can be disconcerting to the newcomer, but has lots of good nuggets about patterns. Oh well, I'm sure if you a bit on google, you'll find more than you'd ever want to know about patterns in python: http://www.google.com/search?q=patterns+python Cheers, // mark - From thehaas at binary.net Sat Jul 20 16:49:02 2002 From: thehaas at binary.net (thehaas at binary.net) Date: Sat, 20 Jul 2002 20:49:02 GMT Subject: XSLT processor References: Message-ID: <21k_8.103407$%%2.4630636@news2.east.cox.net> Stefan Heimann wrote: > Saxon - a XSLT processor written in Java - provides such an internal > API. Does anyone know if there is something similar for python? I have no idea if the "pure-Python" XSLT processors (4xslt, etc.) have that, but you want Python and functionality in Saxon, than use Jython. It works great with external Java objects (I use it for that myself), and I have never had any Python/Jython compatibility problems. Note, however, that Jython is currently at 2.1, so no generators, or iternators. -- mikeh -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas GnuPG key: http://www.binary.net/thehaas/mikeh.gpg From china at thewrittenword.com Mon Jul 1 23:12:05 2002 From: china at thewrittenword.com (Albert Chin-A-Young) Date: Tue, 02 Jul 2002 03:12:05 -0000 Subject: zipfile and Tru64 UNIX Message-ID: Anyone aware of problems with zipfile against Python 2.0.1, 2.1.2, or 2.2.1 and 64-bit systems like Tru64 UNIX? I'm testing against 4.0D and 5.1 and a zipfile that tests out using testzip() on IRIX, HP-UX, and Solaris gives a CRC error on Tru64 UNIX. I've tried creating the zipfile with the UNIX zip program or zip.write() and get the same error. The only bug I could find on sf.net was: http://sourceforge.net/tracker/index.php?func=detail&aid=453208&group_id=5470&atid=105470 > import zipfile > zip=zipfile.ZipFile('/tmp/a.zip','r') > zip.printdir() File Name Modified Size vmunix 2002-05-31 14:29:06 9225952 > foo=zip.read('vmunix') Traceback (most recent call last): File "", line 1, in ? File "/opt/TWWfsw/python221/lib/python2.2/zipfile.py", line 354, in read raise BadZipfile, "Bad CRC-32 for file %s" % name zipfile.BadZipfile: Bad CRC-32 for file vmunix > bar=zip.getinfo('vmunix') > bar.CRC -2068761705 The output of binascii.crc32 on the contents of 'vmunix' is: 2226205591 or from the unzip program: $ unzip -v /tmp/a.zip Archive: /tmp/a.zip Length Method Size Ratio Date Time CRC-32 Name -------- ------ ------- ----- ---- ---- ------ ---- 9225952 Stored 9225952 0% 05-31-02 14:29 84b13397 vmunix -------- ------- --- ------- 9225952 9225952 0% 1 file Adding some debugging statements to zipfile.py reveals that the CRC returned by binascii.crc32() is 2226205591 which is 0x84b13397. So, this matches the output above from unzip. So, bar.CRC is wrong. BTW, the /tmp/a.zip file used in this example was written with the zipfile module (it is a valid zip file as I unpack with unzip and ran cmp against /vmunix, the original source). -- albert chin (china at thewrittenword.com) From m.faassen at vet.uu.nl Thu Jul 11 12:37:33 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 11 Jul 2002 16:37:33 GMT Subject: Python in the enterprise: Pros and cons References: <200207110952.21663.b.maryniuk@forbis.lt> Message-ID: Cliff Wells wrote: > On Thu, 11 Jul 2002 05:47:22 -0400 > Tim Peters wrote: [the enterprise] >> It's an especially annoying American buzzword for "business use, as opposed >> to consumer, research, or educational use". Your enterprise-ready software >> is primed to take on the challenge of synergizing mission-critical business >> logic in empowering ways. IOW, it computes the sales tax right more often >> than not . >> > I always took "enterprise" to mean "runs on an AS/400 with a text interface", > or possibly as a synonym for "token-ring". I thought it involved that starship with the federation and the vulcans and such. Their computer system gets taken over by alien entities quite frequently, so I imagine they run software for the Enterprise. Deflect-the-warp-tetrion-plasma-field-dimensional-flux-ly yours, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From squelart at hotmail.nospam.com Wed Jul 17 22:52:32 2002 From: squelart at hotmail.nospam.com (Gerald Squelart) Date: Thu, 18 Jul 2002 12:52:32 +1000 Subject: SSL support in 2.2.1/win References: <3d362ab9@duster.adelaide.on.net> Message-ID: <3d362d71@duster.adelaide.on.net> Oh, and I've just tried with python/cygwin, linux and bsd, they all have SSL built-in... So, why the inconsistency?... Gerald. "Gerald Squelart" wrote in message news:3d362ab9 at duster.adelaide.on.net... > Hi! > > I've downloaded and installed python 2.2.1 on my win2k machines, and tried > my first program... And I was disappointed to see that SSL support is not > enabled by default. That was embarassing since my colleague made a similar > program in perl, which seems to support SSL by default. > Any reason for not including SSL by default? > Do I have to rebuild the world to get SSL? > Will it be included in future versions? > > I'd just like to be able to give my little program to friends and tell them > 'Just install python, then it will work'. > > Maybe I'm wrong or something, please point me in the right direction then! > > Cheers, > Gerald. > > From gerhard.haering at gmx.de Tue Jul 9 06:37:58 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 12:37:58 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <200207091218.50549.b.maryniuk@forbis.lt> References: <200207091218.50549.b.maryniuk@forbis.lt> Message-ID: <20020709103758.GC1792@lilith.my-fqdn.de> * Bo M. Maryniuck [2002-07-09 12:18 +0200]: > On Tuesday 09 July 2002 11:56, Boudewijn Rempt wrote: > > It's part of the kdebindings module: > > http://developer.kde.org/language-bindings/java/index.html > > AFAIK, QT isn't KDE, right? It actually, *is*, [...] No, Qt exists in non-GPL versions for win32 and Mac. The Java binding will most likely just work there, too. > And you can not use Java for very small and fast programs (console > use) -- it'll start a half of hour... FUD. gerhard at lilith:~$ javac nothing.java gerhard at lilith:~$ time java nothing # IBM JDK 1.3.1 real 0m0.651s user 0m0.560s sys 0m0.110s gerhard at lilith:~$ gcj -o nothing nothing.java --main=nothing gerhard at lilith:~$ time ./nothing real 0m0.113s user 0m0.100s sys 0m0.010s gerhard at lilith:~$ cat /proc/cpuinfo processor : 0 model name : Celeron (Mendocino) cpu MHz : 498.011 processor : 1 model name : Celeron (Mendocino) stepping : 5 cpu MHz : 498.011 [...] Once you use lots of classes, there are some problems with startup time. Because of bytecode verification and all that. > And also not for very-very-very large projects with GUI and other > stuff. I've seen no one success project, written on Java. I have. One. Both GUI (formerly VJ++/WFC, then converted to Swing) and backend (Intershop Enfinity - eCommerce engine, EJB, Oracle, XML, CORBA). > Even all the tools from the Oracle 8i-9i -- they always mostly fails > or crashes in the middle of the work (JDeveloper, Oracle Installer, > OAS etc). :( Oracle developers apparently have no clue about 1) Writing installers. 2) Writing client-side Java that doesn't look crappy and actually works. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From just at xs4all.nl Thu Jul 4 03:05:31 2002 From: just at xs4all.nl (Just) Date: Thu, 04 Jul 2002 09:05:31 +0200 Subject: Reportlab References: Message-ID: In article , Marcus Vinicius Laranjeira wrote: > Does anyone here uses Reportlab to create charts !? > > I need some help about this, but I could'n find anywhere .... Since > reportlab is a library to create graphics, pdf and charts with python... I > hope someone here uses it ! There's a reportlab users mailing list here: http://two.pairlist.net/mailman/listinfo/reportlab-users Just From chris_mk at hotmail.com Tue Jul 30 17:44:12 2002 From: chris_mk at hotmail.com (Christopher) Date: 30 Jul 2002 14:44:12 -0700 Subject: decoding XML-ified special chars such as " (Correction) References: Message-ID: Whoops, sorry, I read the email wrong at first. The escape function makes the " strings. Sorry. I am working on something else (but I am going to test it first this time...) Chris From craigmclean at shaw.ca Wed Jul 10 17:10:41 2002 From: craigmclean at shaw.ca (Craig McLean) Date: Wed, 10 Jul 2002 21:10:41 GMT Subject: Behaviour of print in functions References: <20020710224014.27499085.christophe.delord@free.fr> Message-ID: OK I just found out that function names are detected statically, which answers my whole question. You gotta like it when you post to usenet and then five minutes later you find the answer in your book, and the section is prefaced by saying that this is the most common question that gets asked. Never fails that right after you hang yourself out on usenet, the answer shows up through some other source, and makes you look illiterate. From rjones at ekit-inc.com Thu Jul 25 22:11:48 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 26 Jul 2002 12:11:48 +1000 Subject: how to count lines in a file ? In-Reply-To: References: Message-ID: <200207261211.48567.rjones@ekit-inc.com> On Fri, 26 Jul 2002 12:01 pm, Tim Peters wrote: > [Richard Jones] > > > I think the major problem that we're running into here is that > > before there was GC, the refcounting-based cleanup of objects was clear, > > straight-forward and reliable. Now it's not clear when objects are > > cleared up. > > Then you don't understand CPython's flavor of gc: refcounting didn't go > away in CPython. [snip] > Did you catch that the example was run under Jython? Jython never used > refcounting. Ah, this is my fundamental misunderstanding. So it's Jython that changed the rules because it doesn't do refcounting. Righto, all clear now. It's still a problem that I was completely unaware of - I should have paid more attention to Jython, even though I didn't figure it'd have any impact on things I wrote :( > Yet it shouldn't be "a problem" at all. Nothing has changed except that you > have fewer memory leaks. But something has changed - files aren't closed reliably in Jython when they are in CPython. Richard From theller at python.net Tue Jul 2 05:51:56 2002 From: theller at python.net (Thomas Heller) Date: Tue, 2 Jul 2002 11:51:56 +0200 Subject: reloading modules References: <1FVT8.56956$xy.18941573@twister.socal.rr.com> Message-ID: "Jeff Davis" wrote in message news:FE3U8.42816$1D2.18794662 at twister.socal.rr.com... > Thanks very much, it seems to work exactly like I needed! > > I have one question though: you say in the message: > "The purpose is to speed up the development process, not to > update long running programs on the fly." > > Could you explain a little further? I was planning to use the module for > web development in mod_python (where I don't want to worry about > restarting the server just for a minor change). Will it work for that kind > of thing? Knowing nothing about mod_python, I cannot say anything about this, but IMO it should work. I have used it (for example) for changing methods in a wxPython program without restarting it. Thomas From johnroth at ameritech.net Sat Jul 27 08:20:20 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 27 Jul 2002 08:20:20 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: "Steve Holden" wrote in message news:Lap09.24994$724.6190 at atlpnn01.usenetserver.com... > "John Roth" wrote in message > news:uk3abpr4treeb9 at news.supernews.com... > > > > "Britt A. Green" wrote in message > > news:mailman.1027705851.8443.python-list at python.org... > > > So I know what lambda functions are, their syntax and how they're > > used. > > > However I'm not sure *why* one would use a lambda function. What's the > > > advantage that they offer over a regular function? > > > > They let you put short, one-time functions inline. In some > > environments (Tkinter comes immediately to mind) there > > are lots of places where short, one-line functions are useful. > > Putting a short, one-time function inline aids readability, > > (at least for people who regard lambdas as readable.) > > > > IMO, if the function is of any significant length, or if it > > duplicates functionality from elsewhere, it should be > > named and written separately. > > > > And let us not forget that those who hate naming one-off functions can reuse > the names if they want. > > def a(x): > print x > def a(y): > print y*y > > is perfectly legal Python. It took me a moment to realize what you were getting at. Granted, it's perfectly legal Python, but the first def is rebound by the second, so it has absolutely no effect unless (and this is what wasn't obvious from the example) it's bound to something else before the second definition. Also, that's probably going to confuse lots of software. I'd suspect that most class browsers, if they found six methods with the same name in a class, would report either the first or the last, or else flag it as an error. John Roth From pinard at iro.umontreal.ca Sun Jul 7 17:47:56 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 07 Jul 2002 17:47:56 -0400 Subject: procmail replacement in Python In-Reply-To: References: <3u8pea.617.ln@127.0.0.1> Message-ID: [Sheila King] > Thanks or the copy I received in email. However, that tarball that > you sent seems to be incomplete and doesn't have any .py source files. > Seems mostly to have .pycmailrc and other types of config files, .doc type > files and install files. The README files make it look very intriguing. > I'd sure like to get my hands on the Python source. I glanced through `pycmail' and decided to postpone for now, so I do not have much experience to share with you. The Python source is file `pycmail' at the top-level after extraction. It does not have a `.py' extension. For my things, I usually compile a `.py' at installation time and `import' it through a very small bootstrap, to avoid re-compilation at each use. Yet, I sometimes wonder if the extra disk accesses are really worth the saving in compilation times. Maybe `pycmail' does it the efficient way? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From marklists at mceahern.com Tue Jul 16 08:46:19 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 16 Jul 2002 07:46:19 -0500 Subject: switch recipe? In-Reply-To: <5IRY8.85116$vm5.3089324@news2.tin.it> Message-ID: [Alex Martelli] > I'm not sure what an lcd is in this context, but I did mean to > loop least-common-multiple(m, n) times, treating the two sets > as equivalent. So I guess I had misunderstood the specs! I seem to have a penchant for maligning concepts. Thanks for the correction on denominator --> multiple. Would it make sense to say lcd (least common denominator) is a conceptual subset of lcm (least common multiple)? If so, that explains my confusion. I like your 2.3 version, especially making it handle empty setn: > def weave(setn, setm): > """Return an iterator that iterates over iterator setn and > sequence setm until setn is exhausted. If setn is larger than > setm, cycle over setm.""" > m = len(setm) > if not m: > raise ValueError, "Set to be cycled on cannot be empty" > for index, item in enumerate(setn): > yield item, setm[index%m] I posted a summary of all the code presented in this thread here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/139210 Thanks! // mark - From edream at tds.net Thu Jul 25 15:13:01 2002 From: edream at tds.net (Edward K. Ream) Date: Thu, 25 Jul 2002 19:13:01 GMT Subject: Speed up Python by up to 5% ? References: Message-ID: <15Y%8.25161$fH5.25088525@kent.svc.tds.net> Thanks very much to all who replied. To summarize the responses: 1. The trick of moving loop code into the case SET_LINENO code won't work if line numbers are suppressed with the -O option. 2. It's not clear how much time really would be saved, but I knew that :-) Compiling the interpreter with DYNAMIC_EXECUTION_PROFILE and DXPAIRS macros is one way to get dynamic statistics. 3. "The current thinking is that a 10% to 15% speedup could be had by changing ceval to use a register VM rather than a stack VM." Obviously, this is a major undertaking. I eagerly await these developments. Thanks again for all these informative responses. I'm glad I asked. Among other things, this has saved me the trouble of suggesting that SET_LINENO opcodes be "optimized." Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From sandeep182 at hotmail.com Mon Jul 1 13:46:00 2002 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: Mon, 01 Jul 2002 17:46:00 GMT Subject: execvp on Windows Message-ID: On Linux, os.execvp(executable, args) replaces the current process, while on Windows, it seems to spawn a new process and then complete the current process. On Windows, this means I get back the command prompt followed by the output of my executable. For example, ====================== D:\>python Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.execvp("python",["python"]) D:\>Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ====================== On Windows, is there any way to delay the completion of the first process until the execvp executable returns? One idea is to use os.spawn*, but I was looking for others. Thanks Sandeep From shagshag13 at yahoo.fr Wed Jul 24 10:41:12 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 24 Jul 2002 16:41:12 +0200 Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: "Alex Martelli" a ?crit dans le message de news: MTy%8.131876$vm5.4340949 at news2.tin.it... > Bo M. Maryniuck wrote: > ... > >> > for line in open(filename): > >> > count += 1 > > > > In anyway this example probably does not work: looping over not sequence > > and you probably should use xreadlines(). > > Not with today's Python, 2.2.* -- looping over files and dicts is > perfectly well supported today (and since 7 months ago)... so and definitively which one should i prefer ? this : for line in open(filename): count += 1 or this : fhi = file(filename) while 1: lines = fhi.readlines(bufferSize) if not lines: break lineCount += len(lines) thanks, s13. From fredrik at pythonware.com Thu Jul 18 17:11:15 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Jul 2002 21:11:15 GMT Subject: replacing a part of a string using a regexp References: Message-ID: Rajarshi Guha wrote: > a line contains: > > > > And I want to replace the url and make the line: > > > > Using re.sub I can substitute the whole string bewteen quotes, but the > substituion needs to use the string that is *found* in the quotes. > > How can I access the matched portion in a re.sub() expression? (if you don't read the documentation, how come you always find the right module/function to use? ;-) you can use backreferences, or a callback method. I prefer callbacks (faster, more pythonic): def fixup(m): return "http://myserver.com/prog.py?" + m.group(1) page = re.sub('', fixup, page) also see: http://effbot.org/zone/re-sub.htm From jonathan at onegoodidea.com Wed Jul 17 03:13:19 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 17 Jul 2002 08:13:19 +0100 Subject: history xml file parse help References: Message-ID: On 17/7/2002 7:47, in article ah33go$b6i$1 at newsreader.mailgate.org, "a64bs4$1oo$1 at newsreader.mailgate.org" wrote: > i'm totally newbie to python/xml > (just reading first book of those) > > i'd like to parse a history file(galeon browser) > and feed into database > and crawl each url and save it in database also.. > so that i can do search on it.. > > well.. > this history file looks very easy to parse.. > but i couldn't find a working sample code.. > > can anyone help me plz? > thank you Try: >>> from xml.dom.minidom import parse >>> from xml.xpath import Compile, CreateContext >>> >>> doc = parse( 'history.xml' ) >>> query = Compile( '//item' ) >>> >>> for item in query.evaluate( CreateContext(doc) ): ... title = item.getAttribute( 'title' ) ... url = item.getAttribute( 'url' ) ... print title ... This assumes that you have the PyXML package installed: You don't need to use the XPath query since the document structure is so simple, but it makes the code much shorter than the equivalent decomposition of the DOM nodes. You can also pull neat tricks like: //item[@visits > 1] to get just the URLs you've visited more than once. Jonathan From tim.one at comcast.net Mon Jul 8 00:01:02 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 08 Jul 2002 00:01:02 -0400 Subject: Fatal Python error: PyThreadState_Get: no current thread with extension module In-Reply-To: <3D28A5FC.7080302@rogers.com> Message-ID: [Mike C. Fletcher] > I'm trying to compile a new extension module Aha! There's your problem <0.4 wink>. > (based on mx.TextTools), and I'm discovering that the programme gets a > Fatal Python error after completing a test suite (likely during cleanup > of the various modules). > I'm trying to figure out what the error really means, and in which > crack I should put my finger to stop the dike from bursting. Is there a > guide/guidelines/helpful-elf-who-sneaks-into-the-shop-at-night for > debugging this kind of error anywhere? No, these are hard, but if Python didn't produce this message, your program would die nanoseconds later with a NULL-pointer dereference instead. Are you using threads? If so, the most likely cause is that some thread is calling back into the Python interpreter (== calling a function in the Python C API) without first acquiring the global interpreter lock. You didn't say which version of Python you're using, but in older versions it's also possibly due to a shutdown race that has since been fixed. You also didn't say which OS you're using, and assorted races in practice have historically been strongly correlated with OS due to differences in their native thread scheduling (e.g., Windows is much happier to swap threads frequently than is Linux, and some races discovered on the one proved impossible to provoke on the other). If you're not using threads, you've got a real mystery on your hands. just-another-reason-it-sucks-to-be-you-if-so-ly y'rs - tim From john.abel at pa.press.net Fri Jul 12 04:35:57 2002 From: john.abel at pa.press.net (John Abel) Date: 12 Jul 2002 09:35:57 +0100 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <000201c22870$1a679780$bd5d4540@Dell2> References: <000201c22870$1a679780$bd5d4540@Dell2> Message-ID: <1026462958.25060.3.camel@lestat.howden.press.net> If we ever meet in person, I will gladly buy you many beers. Thank you for your time, and patience :) Regards John On Thu, 2002-07-11 at 01:15, Brian Quinlan wrote: Here is some XML-RPC IP-based authentication code that works: import sys, os, gzip, smtplib, SimpleXMLRPCServer, string class AuthenticatingSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPC RequestHandler): class UnknownIP(Exception): pass def _dispatch( self, method, params ): ip, port = self.client_address if ip not in ["144.178.233.83","144.178.234.189", '127.0.0.1'] : raise self.UnknownIP, "Client IP Is Not Authorised" else: SimpleXMLRPCServer.SimpleXMLRPCRequestHandler._dispatch(self, method, params) def GetFiles(FileRequest): print FileRequest RetrFile = open(FileRequest,"r") FileContents = "Not Found" for FileLine in RetrFile: if FileContents == None: FileContents = FileLine else: FileContents = FileContents + FileLine return FileContents if __name__== "__main__": XMLRPCServer = SimpleXMLRPCServer.SimpleXMLRPCServer ( ("127.0.0.1",8000), AuthenticatingSimpleXMLRPCRequestHandler ) XMLRPCServer.register_function(GetFiles) XMLRPCServer.serve_forever() > Thanks again for your help and patience. If we ever meet in person, you owe me many beers :-) Cheers, Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerhard.haering at gmx.de Tue Jul 9 19:17:08 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 9 Jul 2002 23:17:08 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: Simon Foster wrote in comp.lang.python: > Huaiyu Zhu wrote: >>Simon Foster wrote: >>>On Tue, 9 Jul 2002 15:23:49 +0200, "Bo M. Maryniuck" wrote: >>>>On Tuesday 09 July 2002 14:43, Simon.Foster at smiths-aerospace.com wrote: >>>>> eval! >>>>Overkill. Unsafe. Ugly. Lame. >>>What do you mean by unsafe? >>Something like the following could happen (don't try it!) >># eval('system("rm -rf /")') > You seem to be mistaking me for an idiot. This is not about taking anybody for an idiot. It's about wether you can trust the source you get your data from 100 %. One typical example where you can not is if its part of a form submitted via CGI. Using exec or eval without explicit dictionaries _is_ dangerous, if you can't absolutely trust the data. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From tjreedy at udel.edu Sat Jul 20 11:25:25 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Jul 2002 15:25:25 GMT Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> <1027175934.94979.0@iris.uk.clara.net> Message-ID: > Also, is there likely to be a 2.2.2 ? (Based on my lurker reading of developer list) yes (but no idea when) tjr From phr-n2002b at NOSPAMnightsong.com Sat Jul 20 00:26:39 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 19 Jul 2002 21:26:39 -0700 Subject: Session ID & Security References: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> <3D38B779.3090602@removethisandallhyphens-o-n-e.net> <7xwurrkwes.fsf@ruckus.brouhaha.com> <3D38D519.8070501@removethisandallhyphens-o-n-e.net> Message-ID: <7xadonkosg.fsf@ruckus.brouhaha.com> - c o v e n t r y - writes: > http://web.systhug.com/kernel-lock/ - for linux atomic file locking. > > of course, wether your system is mulitprocess or multithreaded will vary > the lock - a python multithreaded application can perform all locking > internally. multiprocess requires external locking, such as the file > locking provided above in linux kernels and filesystems. Note that > _how_ you store and lcok your data can play a big part in how the lock > affects performance. a single, big lock on a single file containing all > session data will not scale. I use individual files per session in my > projects, and lock individually - thus only simultaneous requests from > the same session can block each other - which is normally acceptable. Thanks, that's kind of interesting, but because of the issues you mention and because of the file system overhead (even if it's a ram disk), I still think shared memory is the best mechanism by far. http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html is a Python interface to the shm system call that does everything required. Alternatively a semaphore operation (basically a call to an atomic test-and-set instruction) could be added to the existing mmap module, and you'd simply map a shared file into memory. For more flexibility, it might be interesting to use MPI for all this stuff. Run your web server on a Beowulf cluster! From dave at pythonapocrypha.com Mon Jul 22 21:35:20 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: 22 Jul 2002 18:35:20 -0700 Subject: Which gui for slow (133 Mhz) pc References: <3d3b9eaa.7275472@news.utanet.at> Message-ID: <477762c2.0207221735.48b1792c@posting.google.com> scrutinizer at gmx.at (Francesco S.) wrote in message news:<3d3b9eaa.7275472 at news.utanet.at>... > Hello, > > What gui can you recommend for my slow pc (win95). > > I was impressed by the Wxpython demo. > But for developing, the startup speed for a simple hello world app > with about 10 sec is not acceptable for me. Another option is to just do "normal" Win32 GUI programming using the win32 (Mark Hammond's) Python extensions. Actually, you have 2 options: you can write Python code that looks nearly equivalent to MFC GUI code, or you can write Python code that looks nearly equivalent to C Win32 GUI code. Either way you'll have very fast load times and your program itself will be quite small (no huge libraries to ship with it). The downside of course is that you have to do more of the work yourself, but I've used this approach in a few programs and it worked well for me. The extensions come with a few examples to get you started, and if you have experience writing the equivalent C/C++ code then development actually goes quite fast. Anyway, it's something to consider.. -Dave From ls2312 at netcom.com Mon Jul 8 19:53:18 2002 From: ls2312 at netcom.com (Lowel Stern) Date: Mon, 08 Jul 2002 16:53:18 -0700 Subject: Help with Popen in 2.2 Message-ID: I have a problem that I can't seem to get around. I hope somone here can help. snipet import os fp = os.popen('prog "stern:STWA" 1234') ky = fp.read() print ky[2:] the above works fine. The quotes must be as shown they may not be changed. The problem is I need to be able to change programatically the section "stren:STWA" and the 1234 section I have not figured a way to do the substitution yet any ideas. Lowel From mgerrans at mindspring.com Fri Jul 5 22:24:09 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Fri, 5 Jul 2002 19:24:09 -0700 Subject: Why self? References: Message-ID: > What I mean by the legacy part is that you have to name self in the > list of arguments to the class methods. > This part is redundant - but once you are inside a method, it is fine > that you have to explicitly qualify by self when refering to class > variables. I kind of like this part of the syntax, especially when using os.path.walk() with a walker method in a class; it is very clear what is going on with the "self" pointer, as opposed to the implicit pointer in C++ which can be confusing in similar circumstances. > As holger points out, a frequent source of errors in C++ is that a > method takes an argument with the same name as a class variable - > which then hides the class variable. I don't agree with this argument -- a simple compiler warning solves this problem; no need to throw out the baby with the bath water. I also don't think it is a frequent source of errors. In Python, I think the required "self" reference in methods is a case where the solution is worse than the problem it solves. Since indentation is the method of scoping in Python, this addition of five characters to each instance variable is particularly annoying -- a one-line statement that contains several instance variables can easily become unmanageable. It's a bit like that horrible blight on the programming community called "Hungarian Notation" that needlessly polutes code with incomprehensible variable prefixes so that you know your string is really a long pointer to a zero terminated array of signed 8-bit characters. As if you cared, or needed to be constantly innundated with such superfluous information. Fortunately, the Hungarian Notation investation has for the most part been limited to Microsoft's C and C++ APIs and thier usage, but hasn't infected others -- and nowadays it even seems to be on the decline in Redmond (C# examples are generally free of it). I never had a much of problem in C++ with distinguishing member variables from local variables and I never liked those cheesy ("Some cheese, please, my good man!") conventions of always using "m_" or "this->". If you keep your methods small and clean, you don't need all this slop. However, since Python doesn't have declarations, some method is required to distinguish whether an assignment in a class's method is an assignment to a instance variable or a local variable. I prefer the solution of simply making it illegal to have local variable names match class variable names. Hmm... this doesn't help with the problem of globals, but there is a keyword for that. > When I prototype new classes, the methods often start out as > functions, and typically I forget to add self to the argument list > when they are promoted to methods. Me too! From jb at hotmail.com Fri Jul 26 14:07:25 2002 From: jb at hotmail.com (JB) Date: Fri, 26 Jul 2002 20:07:25 +0200 Subject: GUI toolkits References: <236EC44367AE7427.C793EF1731020582.0EADC366DFAE2535@lp.airnews.net> Message-ID: <3d418e04_8@news.newsgroups.com> Cameron Laird wrote: > Is there a technical problem with PyQt on Windows, > or are you saying the license doesn't suit you? I used PyQt with Qt 2.3 on Windows. I was astonished when everything ran "out of the box". The only problem was that the Qt non-commercial version displayed the message "freeware" in the window captions and you could not switch that off. But rumour has it that later they made it impossible to use captions with the non-commercial versions at all. -- JB -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From chris.lyon at spritenote.co.uk Sun Jul 7 01:30:43 2002 From: chris.lyon at spritenote.co.uk (chris lyon) Date: Sun, 7 Jul 2002 06:30:43 +0100 Subject: Concept Error Message-ID: <3d27d274$0$24427$afc38c87@news.easynet.co.uk> I've been at it all night and I don't understand why this does work:- (Its derived from www.e-coli.net/pyado.html , ok it's a straight copy ) import win32com.client class RecordSet: def __init__(self, DBConnection): """Initialize a Record Set Object""" self.rs = win32com.client.Dispatch(r'ADODB.Recordset') self.conn = DBConnection def listfields(self): for x in range (self.rs.Fields.Count): print 'Name:-',self.rs.Fields.Item(x).Name print 'DefinedSize:-',self.rs.Fields.Item(x).DefinedSize print 'Type:-',self.rs.Fields.Item(x).Type print 'Value:-',self.rs.Fields.Item(x).Value conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/octavia/c4i.mdb;' conn.Open(DSN) fred = RecordSet(a) fred.rs.CursorLocation = 3 fred.rs.Open('[Categories]',a.conn,1,3) fred.listfields() But this fails to run. import win32com.client class RecordSet: def __init__(self, DBConnection): """Initialize a Record Set Object""" self.rs = win32com.client.Dispatch(r'ADODB.Recordset') self.conn = DBConnection def listfields(self): for x in range (self.rs.Fields.Count): print 'Name:-',self.rs.Fields.Item(x).Name print 'DefinedSize:-',self.rs.Fields.Item(x).DefinedSize print 'Type:-',self.rs.Fields.Item(x).Type print 'Value:-',self.rs.Fields.Item(x).Value def getalltable(self , tablename, conn): self.rs.CursorLocation = 3 #adUseClient self.rs.Open('[Categories]', conn , 1 ,3) #adOpenKeySet adLockOptimistic conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/octavia/c4i.mdb;' conn.Open(DSN) fred = RecordSet(a) fred.rs.CursorLocation = 3 fred.getalltable('Categories', a) fred.listfields() It Fails with:- File "C:\Python21\win32com\gen_py\00000205-0000-0010-8000-00AA006D2EA4x0x2x5.py", line 2008, in Open return self._oleobj_.InvokeTypes(0x3fe, LCID, 1, (24, 0), ((12, 17), (12, 17), (3, 49), (3, 49), (3, 49)),Source, ActiveConnection, CursorType, LockType, Options) TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object. Why can't I just treat rs as a property of the class RecordSet ? Obviously I can get functionality I require but I do not understand why I can't treat the RecordSet this way. I've examined as much of the underlying code as I can but I'm quickly lost, and I notice that win32com.client.Dispatch is a function not a class so I can't sub-class it so that way seems closed. It feels that I am missunderstanding some aspect of the class mechanism so I would dearly like to know what I'm doing wrong. ( And I will NOT write this app in VBScript :-) Chris Lyon From jepler at unpythonic.net Mon Jul 29 10:57:09 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Jul 2002 09:57:09 -0500 Subject: lexing nested parenthesis In-Reply-To: <200207282357.21550.dcinege@psychosis.com> References: <200207282357.21550.dcinege@psychosis.com> Message-ID: <20020729145707.GB10578@unpythonic.net> Regular expressions are not powerful enough to match nesting constructs. Jeff From jerf at jerf.org Tue Jul 23 00:00:59 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 23 Jul 2002 04:00:59 GMT Subject: Metaclasses & docstrings in 2.2 Message-ID: <%x4%8.613290$352.131254@sccrnsc02> Python session you can copy & paste to follow along: ----- class M1: "M1's docstring." def __init__(cls, name, bases, dict): pass class A: "A's docstring." pass A.__doc__ ----- The last line will print "M1's docstring." I'm new to metaclass stuff (though loving it!), and I wanted to check to make sure I understand this, so please correct the following statements as you see fit: 1. In theory, A.__doc__ *should* equal "A's docstring", because A's docstring is more specific and should override the metaclass's docstring. 2. This happens in practice because the metaclass is executed after the class statement for A is executed, and the setting of the docstring ends up affecting A. (If 1 is false, and theory and practice match up, then I'm not convinced "metaclass" is the best word possible, though I don't have a better suggestion. "Metaclass" to me would imply something that *generates* classes, not *modifies* classes after the fact. This is an observation, not a challenge; this usage is probably too entrenched to change now.) And a note to anyone who hits this problem themselves, the solution is either leave the docstring off of the metaclass (obvious), or add cls.__doc__ = dict["__doc__"] though the latter might kill the pickler; I didn't test it. (Oh, and this stuff rocks. A three line metaclass, and two lines activating it on a couple of base classes, is saving me oodles of typing and goodness only knows how many bugs based on forgetting those lines in some obscure subclass. I had a hard time understanding the metaclasses until I found a need for them, but now it's crystal clear. Thanks, Python team, this f'in ROCKS!) From aleax at aleax.it Sun Jul 7 10:10:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 14:10:05 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D2766B3.1010501@ob_scure.dk> <3D283436.8060308@ob_scure.dk> Message-ID: <1ZXV8.51684$vm5.1915512@news2.tin.it> Thomas Jensen wrote: ... > I didn't known there was a Zope Corporation :-) They used to have a different name ("Digital Creations", I believe), but www.zope.com now gives their name as "Zope Corporation". > I guess it is, and we do have redundancy on most of our systems. (We are > currently looking into total redundancy, but it quickly adds up). Very. For 99.99% uptime, you may be better off accepting or ot two highly reliable single-point-of-failure subsystems, rather than trying to add redundancy *every*where (as higher levels might require). Alex From cliechti at gmx.net Tue Jul 2 15:08:31 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Jul 2002 21:08:31 +0200 Subject: Add parent directory to path? References: <3D21F62D.9050801@wag.caltech.edu> Message-ID: Rick Muller wrote in news:3D21F62D.9050801 at wag.caltech.edu: > I often use the little hack > > import sys > sys.path.append('..') i would use sys.path.append(os.path.abspath('..')) as you might change the current dir of the app later. > to add the parent directory to the python path. It's nice, e.g., if I > want to keep a directory below the program directory that contains test > scripts, but still let them easily import the parent directory's modules. > > This hack worked on Unix and Windows/Cygwin, which up until recently > were my only build targets. Now I just got a Apple OS X box, and I find > that, despite the BSD heritage, this little hack no longer works. Is > there a good platform-independent way of doing this? I figure that > something like this should live in os.path, but I didn't find anything > appropriate. doo you have printed os.curdir() and os.path.abspath(os.curdir) do thay return somthing useful? don't have OSX, but i would expect it to act like a unix too.... -- Chris From bokr at oz.net Sat Jul 13 17:34:38 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Jul 2002 21:34:38 GMT Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308dcd_2@news.newsgroups.com> Message-ID: On Sat, 13 Jul 2002 22:37:44 +0200, JB wrote: >Emile van Sebille wrote: > >> JB >>> I have two lists and . The entries of >>> these lists have the format (id,rest), where is a >>> natural number. The list are sorted, the key is . >> >> Your use of the term 'key' here is throwing me. Lists >> don't have keys, >> dicts do. Dicts aren't sorted. ;-/ > >The list entries are tuples. The first element of a tuple is >the sorting key. It is a natural number n, 0<=nis the number of all entries. Some of the entries are in >list1 and some of them in list2. I am working on a list >view widget. list1 contains "visible lines" and list2 the >invisible lines. The moving between the lists is brought >about by changes of a user defined filter. > What about keeping all your lines in a single list, and just filtering for purposes of generating the list view window? OTOH, if you do want two lists, what about making them both able to contain the full list, and just use None as a placeholder when moving an element from one to the other? If your id numbers are just the indices on the full set, you don't even need to store them as data, since you know the range. And if you do want a copy of one of the lists without the None placeholders, you can use the builtin filter function to get non-False-evaluating elements like noNonesList = filter(None, alist). (note that you will lose null strings that way though). Now you just need a fast way to check both lists and see whether your predicate says to swap corrensponding elements, which will be None and something or something and None. Gotta go... Regards, Bengt Richter From david.iungerich at kwe.com Wed Jul 24 17:44:29 2002 From: david.iungerich at kwe.com (David Iungerich) Date: Wed, 24 Jul 2002 16:44:29 -0500 Subject: http to https forwarding Message-ID: Has anyone setup anything to implement the following scenario. I need to do it, and fast. Thanks in advance for any help. I need to an http to https forwarder. My scenario is as follows: I have an appserver that needs to POST http requests to another company's appserver. Unfortunately, the particular product we are using has issues being able to send https, and the other company requires it. They have issued us certificates to talk to them. I need to be able to send http POST reqests to a middle man (Python), have it encrypt the request with the other company's provided cert, and then pass the POST onto that company's server via https. No browser involved. Eventually, I will need to do the same thing in reverse, but initially I just need to be able to send in this direction. Can anyone tell me the specifics of how to do this with Python, or point me to an implementation already done that I could use. Again, our server http to Python middle man, then encrypt, and send to other company's server via https. I'm not rigid with the use of Python, I just know there is some stuff already available to do parts of this. Thanks in advance, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Tue Jul 16 09:47:36 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Jul 2002 08:47:36 -0500 Subject: uniform interface for MySQL & MSSQL In-Reply-To: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> References: <4pi7jug03p5q8l6ucn954ub3miu16mtrmo@4ax.com> Message-ID: <15668.9208.206542.918637@localhost.localdomain> Can't you use the mxODBC stuff for mssql? Heck, it may even support mysql... -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From mertz at gnosis.cx Thu Jul 11 12:22:39 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 11 Jul 2002 12:22:39 -0400 Subject: Open document formats References: <96c7f32.0207090659.b5b9a27@posting.google.com> <6425018709313012.B034167ED9F3563C.A514BB864F414733@lp.airnews.net> Message-ID: |David Mertz, Ph.D. wrote: |>As far as I know, every OS, since maybe 1985, has had drivers for |>postscript printing. Almost all the applications that do not use OS claird at starbase.neosoft.com (Cameron Laird) wrote previously: |Well, wasn't Windows itself holding out against PS for a long time? |OK, I'm not motivated enough to research this myself just now ... My recollection is that early Windows versions Windows/286, Win3.0, etc. indeed had rather poor or non-existent standard postscript support. But even back around 1990, you could easily enough obtain Windows PS drivers from the makers of PS printers. At least as early as 1991, I was using PS drivers on Windows, then using a commercial postscript-interpreter program called "GoScript" (before Ghostscript was around) to send the output to dot-matrix printers. -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 20:52:15 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 17:52:15 -0700 Subject: Percent sign in format string? References: Message-ID: <7x4rewczeo.fsf@ruckus.brouhaha.com> Ron Levine writes: > How can I put a "%" sign in a format string? > > For example, x=98 and I want to output > "x = 98%" "x = 98%%" is the usual way. From larooy at xtar.co.nz Mon Jul 1 20:18:32 2002 From: larooy at xtar.co.nz (John La Rooy) Date: Tue, 2 Jul 2002 12:18:32 +1200 Subject: File read problem in Windows References: Message-ID: <20020702121832.51ed39eb.larooy@xtar.co.nz> On Tue, 02 Jul 2002 00:11:17 GMT "news" wrote: > f = open('myfile,'r') > a = f.read(3072) > > When I do a len(a) I only get 634 bytes. It doesn't seem to want to grab > the full 3072. This ONLY happens in windows...when I run my program in > Linux I get the full 3072 and everything works fine! > > Any ideas? > > Thnx...Larry > > perhaps the file has the windows EOF character in it? ctrl-D or ctrl-Z i think. try f=open('myfile','rb') John From mhammond at skippinet.com.au Wed Jul 10 20:24:40 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 11 Jul 2002 00:24:40 GMT Subject: Python, COM and MatLabs Safearray References: <1OSW8.205616$IR.3395800@news.chello.at> Message-ID: <3D2CD11B.8090202@skippinet.com.au> Weirdron wrote: > I'd like to use the COM Interface of MatLab and the functions to transfer > matrices use the following datatype: > > Pointer SafeArray Real 8 (Flags = 3) > > How do I create this datatype with Python? Any help is greatly appreciated. You should simply need to pass a tuple or list of Python floats. Make sure that you have run makepy over MatLab's COM type library. Mark. From usenet at thinkspot.net Sun Jul 7 03:53:31 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 07 Jul 2002 00:53:31 -0700 Subject: procmail replacement in Python References: <3u8pea.617.ln@127.0.0.1> Message-ID: The tarball URL for the pycmail packages is not working for me. Did anyone grab a copy that they can share? I would like to look at this package. We are often get potential clients at asking about our web hosting services, who would like to use procmail. However, procmail doesn't run well on our system due to the Qmail mail permissions and such. It would be interesting to see if this python procmail replacement might do the job? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Wed, 19 Jun 2002 11:52:28 +0200, Radovan Garabik wrote in comp.lang.python in article : > Gerhard H?ring wrote: > : * Radovan Garabik [2002-06-19 08:38 +0200]: > :> Gerhard H?ng wrote: > :> : Does such a thing exist? I've recently looked into the procmail sources > :> > :> > :> http://melkor.dnp.fmph.uniba.sk/~garabik/pycmail.html > :> > > : Whoa! _Exactly_ what I was searching. Would you mind registering it at > : Freshmeat, so other people can find it more easily? > > http://freshmeat.net/projects/pycmail/ > has been there for a long time:-) > > : Looks like a good project for my next weekend to convert my > : fetchmail/procmail setup to getmail/pycmail. > > I would welcome especially suggestion about possible syntax > changes. Since I cannot help myself, but the syntax (chosen functions > and procedures dealing with mail) does feel a bit clumsy to me > (even though I am the author :-)) From aahz at pythoncraft.com Tue Jul 9 00:04:51 2002 From: aahz at pythoncraft.com (Aahz) Date: 9 Jul 2002 00:04:51 -0400 Subject: replacing instance __setattr__ References: Message-ID: In article , Tim Peters wrote: > >The object dict (x's dict in the above, which has nothing to do with >object's dict) is never searched for methods, and not in any version of >Python. Methods can only come from classes in Python. If the name >"somemethod" isn't found in x's class or any of its base classes, then >"somemethod" is not a method of x. "somemethod" may well be a data >attribute of x that's bound to a function that "acts like" a method, or >close enough to acting like a method that your app doesn't care about the >difference, but even so it's not a method of x if you're careful with words. >An object's (as opposed to the builtin class named object) dict in Python >can only supply data attributes. Your argument appears to be failing my duck test: import new class C: def __init__(self, val): self.val = val def __str__(self): return str(self.val).upper() x = C('foo') x.__str__ = new.instancemethod(__str__, x, C) print str(x) What am I missing? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From ianb at colorstudy.com Sat Jul 13 12:48:46 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 13 Jul 2002 11:48:46 -0500 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <3D2FAE89.21082.361CABA@localhost> References: <3D2FAE89.21082.361CABA@localhost> Message-ID: <1026578927.3148.5.camel@lothlorien.colorstudy.net> On Sat, 2002-07-13 at 06:37, Opus wrote: > As for the nicest formated languages for reading, coding and debugging, I would > have to say that my experience with 4Test (the language developed by Segue for > QA Partner and Silk) was the best I have had. It required that you use the IDE > (you could use a text editor if you really wanted, but why?) to enter code. > The IDE and the language supported collapsible blocks. When you were coding, > it automaticly indented for you, and showed a [-] next to the line to show that > you could collapse it. A [+] showed that you could expand it. The IDE also > had options to expand and collapse the current block, all sub blocks, and the > entire file. Because it was saved as a text file that was then checked into a > repository, it was a company standard to collapse all blocks before checking it > in. The Oberon system had something like this as well, though I believe only for larger blocks (functions, classes, etc.) and not control structures. One thing I wonder... would it be possible to use Emacs outline mode with the python mode, so that every syntactic : is a level in the outline? (well... I'm sure it's possible, but has anyone already done it?) Ian From ianb at colorstudy.com Wed Jul 31 02:26:15 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 31 Jul 2002 01:26:15 -0500 Subject: Let's Talk About Lambda Functions! In-Reply-To: <3D475AB5.2060207@nowhere.org> References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitete ch.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> <3D475AB5.2060207@nowhere.org> Message-ID: <1028096804.836.1812.camel@lothlorien.colorstudy.net> On Tue, 2002-07-30 at 22:33, Bryan Olson wrote: > Ian Bicking wrote: > > > I've seen people argue that you can do all the same things with > > iterators as Smalltalk does with code blocks. And, really, it's not as > > though Smalltalk has truly novel control structures -- everything still > > boils down to while, for, and if. > > Decades before anyone implemented a programming language, Alonzo Church > boiled all the control structures down to just one: lambda. And Smalltalk *pretends* to implement something like the lambda calculus -- but deep down, they had to use the same if statements we all use (for performance reasons). but-they're-all-turing-equivalently y'rs, Ian From dcinege at psychosis.com Thu Jul 25 00:40:58 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Thu, 25 Jul 2002 00:40:58 -0400 Subject: cmd, readline, and /path/filename completion In-Reply-To: <20020724175117.B3904@eecs.tufts.edu> References: <200207241627.04037.dcinege@psychosis.com> <20020724175117.B3904@eecs.tufts.edu> Message-ID: <200207250040.58148.dcinege@psychosis.com> On Wednesday 24 July 2002 17:51, Michael Gilfix wrote: > The readline library is sufficiently general such that it's meant ... > consider to be the atomic words are. Maybe that makes sense? I've generally understood this from the get go. What I'm not clear on is to what extent readline 'just works' and what need to be coded explictly. For instance I understand, '/' was removed as a delimiter. But I don't know where readlines's behavior is defined to know that it should match a path where '/' is involved...and furthermore how to altered that behavior should I want to. > I once implemented an application where I wanted to complete against > files in a 'current dir'. My solution was to gobble up a list of files > in teh current directory (I assume you have that part down), and then > set an attribute of "completion words". Now I wrote this particular app I'm by no means a coding novice, and I already know I (or somewhere in readline) must walk the path and gather a list of executable files. Where I'm lost is how to pass this to readline. (Or activate it in readline) The reviewing the functions of the readline module makes me go 'huh?' http://www.python.org/doc/current/lib/module-readline.html From mcfletch at rogers.com Wed Jul 3 20:42:54 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 03 Jul 2002 20:42:54 -0400 Subject: Parsing References: Message-ID: <3D239A0E.3080605@rogers.com> For your task, look at: re (low-level text processing) htmllib or sgmllib (actually parses HTML/SGML, lets you define callbacks to handle content) xml (same basic idea as previous, but more committed :) ). in the standard Python library or search Google's groups for "strip HTML" in the Python newsgroup to find examples using those libraries that get posted every few months or so :) . For example: http://groups.google.com/groups?th=fbebe304ebf2c36e&rnum=1 For actual generalised parsing solutions (which are a pretty big hammer for such a simple task), Google about for: PLY SPARK SimpleParse PyLR Yapps kwParsing Plex or even just search for "Python parsing". Have fun, Mike Thomas Berglund wrote: > Hello all > > I'm new to this group and new to python =). > > I was thinking, as a first project, to have a program that would > download a random quote from a homepage that gives such, parse all the > html out of it and print it. Should be simple, no? ... > but, that's not really working out. I was just wondering if there was > some kind of standard parsing library for python to help me get rid of > those nasty html tags. Any pointers would me much appreciated. > > Have a nice day, and thanks. > > /Thomas From vchen at meetingmaker.com Fri Jul 12 11:55:26 2002 From: vchen at meetingmaker.com (Victor Chen) Date: Fri, 12 Jul 2002 11:55:26 -0400 Subject: automating command line program Message-ID: <005301c229bc$8c6f2580$e503010a@int.meetingmaker.com> More specifically, I'm trying to automate testing for a command line program. I've successfully launched the program and now the program is prompting me for some information. However, I'm not able to tell python to input the information which I would like to enter. I've tried os.popen, and os.system, but they will not input information into the program, instead, they will run after i break out from the program and tries to input the information into the windows command prompt in which will result in an windows command prompt error because the information is not recognized as a valid command. If I don't break from the program, then I will be at a halt because the program just keeps on waiting for input of the information and will not exit itself. Further, I've looked up a module called the Expect module for python. Sometimes called Expectpy or expy but am unable to find a windows version of it. I will look into popen2. Thank you. Victor "Cameron Laird" wrote in message news:200207121609.LAA06741 at starbase.neosoft.com... > In article , > Mark McEahern wrote: > >I'm fairly new to python and I've been trying to automate the usage > >of a command line prompt program and I'm able to successfully run the > >application from command line but once the program has launched, I'm unable > >to enter anymore commands into the program. I've basically just tried using > >os.system, os.popen, and print statements. Is there other python commands > >that will allow me to do this? I've looked around the web and I've found a > >module, Expect, that may be able to help me but I'm unable to find a windows > >version of this module for python. Any help is appreciated, thank you. > >Victor > > > >Could you please be more specific? What is it you're trying to do? What > >specifically have you tried? What specifically isn't working? > . > . > . > Myself, I thought he made it clear enough. He's made > some progress with os.popen; now he needs to be told > about os.popen2 (and possibly os.popen3--my guess is > that's unlikely, though). > > Victor, look those up in whatever documentation you're > using. I suspect you'll find they give you everything > you're after. > > Are there any warnings about popen2 under Windows Victor > should hear? > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://starbase.neosoft.com/~claird/home.html > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.grabietz at img-online.de Tue Jul 30 11:13:50 2002 From: michael.grabietz at img-online.de (Michael Grabietz) Date: Tue, 30 Jul 2002 17:13:50 +0200 Subject: Check undefined variable Message-ID: <3D46AD2E.709@img-online.de> Hi, how is it possible to check whether a variable 'a' is undefined or not. e.g.: if a==NULL : # something like that print 'a is undefined !' else print 'a already undefined !' Regards, Michael From emile at fcfw.fenx.com Tue Jul 30 15:46:51 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: 30 Jul 2002 14:46:51 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 30) Message-ID: QOTW: "If you don't have time to learn another language, then you will likely never realize any of the benefits that Python, and learning Python, might have to offer." -- George Demmy "... -- doing nothing gracefully is important because there's sometimes nothing that needs be done ." timbot http://groups.google.com/groups?q=g:thl477273455d&dq=&hl=en&lr=&ie=UTF-8&selm=mailman.1026524959.15573.python-list%40python.org Michiel de Hoon gets help and works through making a windows installer on cygwin with distutils. http://groups.google.com/groups?threadm=3D3CD77B.1040102 at ims.u-tokyo.ac.jp Erik Max Francis announces the rebirth of Munch as empy 1.0, a system for embedding Python expressions and statements in template text (or any other unexecuted content) which replaced GNU m4 as a macro processor for its author. http://groups.google.com/groups?selm=3D3DBE23.4E164323 at alcyone.com Raymond Smith releases Fnorb 1.2, which incorporates a number of changes required to make Fnorb a truly pure-Python based ORB including a pure Python IDL parser and pure Python CDR processing. It represents the first stable release of Fnorb since it was open sourced. http://sourceforge.net/projects/fnorb Guido van Rossum makes his Powerpoint slides for his keynotes addresses at EuroPython and OSCON available. http://groups.google.com/groups?selm=mailman.1027555542.30285.python-list at python.org Currencies and decimal places without saying the "f" word... http://groups.google.com/groups?threadm=mailman.1027484434.16234.python-list at python.org Joost Jacob launches a Project to provide functions to turn a Python class into a server. http://groups.google.com/groups?selm=13285ea2.0207250503.b974470 at posting.google.com Greg Ewing releases version 0.4 of Pyrex, a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. http://groups.google.com/groups?selm=mailman.1027522928.20293.clpa-moderators at python.org Clark C. Evans releases pyYaml v0.21. YAML(tm) is a machine parsable data serialization format designed for human readability and is optimized for data serialization, configuration settings, log files, Internet messaging and filtering. http://groups.google.com/groups?selm=mailman.1027570414.31317.python-list at python.org David Levy asks for tips on SOAP.py and complex types information for input messages that require user defined types like the one for the new Amazon web service. http://groups.google.com/groups?threadm=3D3BDD02.3997B185 at xrce.xerox.com A history unfolds when Philippe Gendreau asks "What is it with the '_'. I have seen it used in many places for what seems to be different purposes." http://groups.google.com/groups?threadm=mailman.1027526320.10233.python-list at python.org Larry needs help getting UDP Multicast to work properly. http://groups.google.com/groups?threadm=PuF%8.650192$cQ3.104714 at sccrnsc01 Dave Cinege announces proctitle, a stand alone module that manipulates the 'argv[]' (process listing) of the Python process allowing one to change the output seen from 'ps'. It is useful for hiding 'python', an argument that is a password, or update process information. http://groups.google.com/groups?selm=mailman.1027382614.7327.python-list at python.org Bobby Beckmann releases PyDumper, a GDB helper script that wraps GDB and is able to extract a stack trace and all relevant data (func args, globals, locals, instance vars) to help debugging apps that get stuck. http://groups.google.com/groups?selm=3D3F805E.9050205 at piels.com Eugene Kim wants to make a p2p application in python like napster. http://groups.google.com/groups?threadm=ahdqla$kd$2 at newsreader.mailgate.org Jay O'Connor wonders about writing a distributed Python framework, and will save the effort finding many to choose from. http://groups.google.com/groups?threadm=20020724.064941.722308542.1589 at cybermesa.com Markus von Ehr bumps into a known bug that causes the DOS-Shell to hangs when using python/Tkinter. http://groups.google.com/groups?threadm=3D3FBF1A.C1531FB3 at ipm.fhg.de Gerard A.W. Vreeswijk asks for a function wrapper a la Perl's Hook::WrapSub and gets a quick roll-your-own response. http://groups.google.com/groups?threadm=3D3E9F34.90FB8B3F at cs.uu.nl Remi Delon introduces freecherrypy.org providing Free CherryPy hosting. CherryPy is a Python-based tool for developing dynamic websites. http://groups.google.com/groups?selm=585c0de9.0207252302.558a7953 at posting.google.com Michael Hudson recalls, locates, then adapts this regular expression. Care to guess what it does? Or how it works? (helpful names changed) >>> def x(num, ex=re.compile(r"^1?$|^(11+?)\1+$")): ... return ex.match('1'*num) is None http://groups.google.com/groups?selm=lkadoekcqj.fsf at pc150.maths.bris.ac.uk ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jdhunter at nitace.bsd.uchicago.edu Wed Jul 17 12:19:36 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Jul 2002 11:19:36 -0500 Subject: how to ask google, altavista or another search engine... References: Message-ID: >>>>> "Shagshag13" == Shagshag13 writes: Shagshag13> but i'm also looking for others search engines Shagshag13> wrappers like altavista or metacrawler, etc. If you are willing to go to the dark side, you may find the WWW:Search perl mods useful. John Hunter From cbbrowne at acm.org Sat Jul 13 12:25:57 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 13 Jul 2002 16:25:57 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: Message-ID: In the last exciting episode, pinard at iro.umontreal.ca (Fran?ois Pinard) wrote: > [Jonathan Hogg] >> I really am willing to eat humble pie here and admit that I'm >> mistaken if someone can give me a similar list of good reasons to >> *not* use XML for off-line hierarchically structured data. > > Any file is a hierarchy of some sort. We often see a file being a > sequence of lines, a line being a sequence of fields or tokens, and > tokens being a sequence of characters. In many, many, really many > applications, this organisation in lines and fields is wholly > satisfactory. Reusing the enumeration above, it is easy to parse, > easy to validate, easy to edit, easy to query, easy to transform and > easy to store. Let's be honest. People are comfortable with lines > and fields, examples and tools merely _abound_. > > XML becomes more sensible when you have a _lot_ of structure, > something which is complex, difficult, and which you have to > exchange with away parties. For simple things, it is just annoying > and heavy overkill, really... Heavens, that is an _excellent_ description of what's going on. I think that also nicely describes the way that trees tend to get nasty in SQL, too. In fact, it more than likely characterizes why "object oriented databases" are a controversial matter. > Speaking for my own situation only, as a Python lover, XML is gross > overkill even for quite complex things. It is extremely simple to > pickle rather complex structures, transmit them over wires to > applications on other machines, and unpickle them there. Using > Python as an API for such usages is natural and very comfortable, > and not to say, immensely faster than XML. SOAP is a nice example of something that _sounds_ good, but whose implementation turns out to be a lot uglier than you'd ideally want. There's little point to it if you're trying to pass around parameters/results looking like: P = [1, 4, 7, 27, 12341, "foo"] Many simpler and greatly more efficient marshalling schemes are available there. The place where it's more interesting are when you've got an XML message looking like: 1.2.3.4 foo.bar.com foo bar.com cache.bar.com 1.2.3.5 frobozz mail frobozz.bar.com or Pinard Francois IBM Inc http://www.ibm.com/ Transmeta Inc Torvalds Linus These are simple enough examples; the _problem_ is that the most typical sort of SOAP handling is for these to respectively translate into something like: H = [ ["1.2.3.4", "foo.bar.com", "foo", "bar.com", "cache.bar.com"], ["1.2.3.5", "frobozz", "mail", "frobozz.bar.com"] ] and C = [[ "Pinard", "Francois"], ["IBM Inc", "http://www.ibm.com/"], ["Transmeta Inc", "Torvalds", "Linus"]] Which are in a sense convenient enough ways to express the information, however you're left puzzling over what the actual intended structure is. Perl's SOAP::Lite actually expresses the results of SOAP queries as the full trees of elements and attributes, allowing you to walk the tree. Unfortunately, when it proves necessary to write a program to walk the tree, that shows that the "S" for "Simple" part just got more than a tad less "simple." The Python SOAP bindings don't handle this terribly wonderfully. >> Perhaps I'm missing something blindingly obvious here, but what >> benefits would I gain from coming up with my own format? > > For simple things? Ease, speed, simplicity, readability. Don't > fear it. The world will survive, you know, even if you sometimes > don't use XML. :-) I think the widespread lemming-rush to try to get _everything_ mapped onto XML-based formats is a demonstration that a whole lot of people have never even _looked at_ Lex and Yacc. Not everything in this world should require writing your own recursive descent parser. But I rather suspect that there are a lot of situations where the programming of parsing tasks might be handled with less code, less debugging, and less overall effort (mental and chronological) by building a Lex-based parser than is required to integrate an XML library into an application and then add the hooks to provide semantics for what it parses. -- (reverse (concatenate 'string "moc.enworbbc@" "enworbbc")) http://cbbrowne.com/info/linux.html MICROS~1 has brought the microcomputer OS to the point where it is more bloated than even OSes from what was previously larger classes of machines altogether. This is perhaps Bill's single greatest accomplishment. From aleax at aleax.it Sat Jul 6 16:40:48 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Jul 2002 20:40:48 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: Thomas Jensen wrote: ... > However the CEO (small company, told you :-), made a couple of somewhat > valid points against it. > 1) He was worried about getting a replacement devlopper in case I left. > 2) He said, "Name 3 companies using Python for key functions" > 3) He was worried about the stability/reliability of python in our > production environment (you know, 99.999 % and all that) Come visit www.python-in-business.org -- we founded the Python Business Forum, a non-profit alliance of firms which do use Python "for key functions", and one of the PBF's primary purposes is to help reassure CEO's (and CTO's &c, for larger companies:-) about just such issues as these. Point 1 is basically never a problem because Python is to easy to pick up (and somebody else's Python code is easier to maintain than for any other language), but the PBF aims to help, in the long run, by establishing a network and referral point for Python trainers and consultants. Point 2 is easy -- Zope Corporation relies on Python so much it pays to employ the Python core team, Google uses Python enough to demand Python skill in some of its job offers, Fidelity (a huge financial trust in Britain) is dependent on Python (tbe basis of all of ReportLab's excellent products) for all of its reports-as- PDF web sales strategy -- that's three. We can no doubt find more, but three is what your boss asked for. Point 3 is troublesome if taken literally -- I know of NO language claiming 99.999% freedom from defects for its implementations. The standard Python distribution is certainly far less buggy than, e.g., most Microsoft language products I've ever used -- on which many corporations, wisely or otherwise, rely for their business -- but that's still a FAR sight from 1-part-in-100,000-or-lower defect rates. One of PBF's plans, named "Python in a Tie", is a very stable Python distribution, due to be blessed by Guido but tested very intensely by the PBF. But the targets, though not quantified so far, are NOT as ambitious as 99.999%. If you're planning deployment in life-critical applications (the only reason I can see for such strict, enormously expensive demands) I think, regretfully, that you'll have to look elsewhere (I'll be curious to hear about what software tools you find that claim those reliability levels, at least if they back it up with real hard-cash reliability insurance -- words are cheap). Alex From duncan at NOSPAMrcp.co.uk Tue Jul 9 11:54:27 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Jul 2002 15:54:27 +0000 (UTC) Subject: 8 Queens Problem References: Message-ID: Simon.Foster at smiths-aerospace.com wrote in news:mailman.1026221774.20130.python-list at python.org: > I've been working on a solution to the eigth queens puzzle. > Here is my attempt. There's a solution in Scheme in SICP > which takes only 13 lines. Can anyone come up with a shorter > solution in Python, without any of the obvious silliness? Here are a couple of solutions based on your version but using generators. This has the advantage of giving you all the solutions for possible further processing, instead of just printing them out, and also allows you to avoid calculating all solutions if you just want one: from __future__ import generators def queens1(order, rows, solution=[], diaga=[], diagb=[]): """Generates all solutions based on the partial solution so far. Output: (solution, diaga, diagb)""" if order==0: yield solution, diaga, diagb return y = order-1 for x in rows: if x-y not in diaga and x+y not in diagb: r = rows[:] r.remove(x) for s, d1, d2 in queens1(y, r, solution+[(x,y)], diaga+[x-y], diagb+[x+y]): yield s, d1, d2 for s,d1,d2 in queens1(8, range(8)): print s break print "Total solutions",len(list(queens1(8, range(8)))) # A version that doesn't precompute the diagonals from operator import add, sub def queens2(order, rows, solution=[]): """Generates all solutions based on the partial solution so far. Yields each solution""" if order==0: yield solution return y, diaga, diagb = order-1, [], [] if solution: s = zip(*solution) diaga, diagb = map(sub, *s), map(add, *s) for x in rows: if x-y not in diaga and x+y not in diagb: r = rows[:] r.remove(x) for s in queens2(y, r, solution+[(x,y)]): yield s for s in queens2(8, range(8)): print s break print "Total solutions",len(list(queens2(8, range(8)))) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gerhard.haering at gmx.de Mon Jul 1 00:28:20 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 1 Jul 2002 06:28:20 +0200 Subject: old thread: SSL support for socket module for server sockets In-Reply-To: References: Message-ID: <20020701042820.GA7097@lilith.my-fqdn.de> * - c o v e n t r y - [2002-06-30 21:02 -0700]: > I was reviewing the archives and ran accross this patch submited for > python 2.0, but too late to make it in... There was an old patch, that was rejected, and http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=452110 which I recommended not to include. Don't expect any great changes to the existing client-side only Python SSL implementation. If Python grows a new and better SSL implementation, it will likely be a complete rewrite or the inclusion of one of the existing third-party alternatives (http://www.cs.fhm.edu/~ifw00065/pyssl/index.html), which, at least for M2Crypto and PyOpenSSL, are stable and have server-side SSL, real certificate management, etc. There was quite some discussion after a post of me to python-dev, but as far as I understood, there wasn't a definite conclusion. And those, who suggested to work on it, me included, apparently didn't have enough time to. Maybe it's about time to rise this issue again, but I still haven't seriously evaluated the existing SSL modules :-/ Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From whisper at oz.net Fri Jul 26 22:53:11 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Jul 2002 19:53:11 -0700 Subject: Two RE proposals In-Reply-To: <15681.61726.4250.930338@12-248-11-90.client.attbi.com> Message-ID: > >> The * doesn't (and shouldn't) operate over grouping parens. You're > >> asking it to supply you with a variable number of groups, which it > >> can't do. > > David> You're right - it doesn't operate over grouping parens, but why > David> _shouldn't_ it? IIRC, _some_ regex pacakges could do this... > > How about using non-grouping parens: > > >>> pat = re.compile(r"((?:a|b)*)") > >>> pat.match("ababaaaabccdabab") > <_sre.SRE_Match object at 0x40348ea0> > >>> _.group(1) > 'ababaaaab' > > Skip Thanks for the pointer on locals()... another nice Python feature :-) Here's a practical example of what I have in mind: str = "" attr = r"\s*\w+\s*=\s*['\"].*?['\"]" tag = r")*\s*/>" tagpat = re.compile(tag) tagmat = tagpat.match(tagpat, str) for attr in tagmat.group(1): print attr >> attr1='a' >> attr2='b' >> attr3='c' If you're the owner of the re module and are willing to provide mentoring, I'm willing to add these. Dave LeBlanc Seattle, WA USA From sholden at holdenweb.com Sat Jul 27 00:49:00 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:49:00 -0400 Subject: Image Loading References: Message-ID: "Ali K" wrote in message news:eeo09.679310$cQ3.106665 at sccrnsc01... > How do you load a picture inside a frame? > > Please Reply! > > Thank You! > > First you decide what kind of picture, then you explain what a "frame" is in this context. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From fredrik at pythonware.com Tue Jul 2 16:54:44 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Jul 2002 20:54:44 GMT Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> <35nU8.46034$n4.10990740@newsc.telia.net> Message-ID: I wrote: > > ... > > File "/usr/local/apache/MoinMoin/parser/wiki.py", line 335, in replace > > return apply(getattr(self, '_' + type + '_repl'), (hit,)) > > AttributeError: Parser instance has no attribute '_hmarker_repl' > > I have no idea -- it did work just fine about 30 minutes > before I saw your post... the RecentChanges page has the answer, I think: Python Version: 2.2.1 (#1, Jul 1 2002, 20:45:11) From jeremy at alum.mit.edu Thu Jul 18 16:55:54 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 18 Jul 2002 13:55:54 -0700 Subject: pickle performance on larger objects References: Message-ID: Sam Penrose wrote in message news:... > memory usage increases by about 20%, FWIW. For my particular use case > cPickle is still several (many ?) times slower than just recreating the > object by reading in a file. What implications this has for best > practices in persistence of larger objects I do not know, but I hope the > data point is of interest to others. MWH's comment about marshal is worth keeping in mind. cPickle is doing a lot of work that marshal isn't doing. Where marshal calls fwrite() directly in most cases, cPickle wraps fwrite() in a C function that w/ Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS. All those extra C functions certainly add up when you've got some many objects. It's also checking for cycles in the containers, which means it has to do a lot of extra bookkeeping for each dict it finds. You can disable that by setting the fast attribute on the pickler: p = cPickle.Pickler() p.fast = 1 Jeremy From pecora at anvil.nrl.navy.mil Mon Jul 8 14:52:50 2002 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 08 Jul 2002 14:52:50 -0400 Subject: Numarray vs Numpy References: Message-ID: <080720021452508286%pecora@anvil.nrl.navy.mil> In article , Fernando P?rez wrote: > numarray is a rewrite of numpy. As such it will address some flaws of numpy's > design which have been understood over the last few years of its extensive > use in science. But beware that in order to do that, numarray's designers > will be forced into breaking compatibility with numpy. So while _most_ numpy > code will work with numarray, some critical things will not. > Are these compatible with the Numeric module? From shalehperry at attbi.com Tue Jul 23 17:40:20 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jul 2002 14:40:20 -0700 (PDT) Subject: list to string In-Reply-To: Message-ID: On 23-Jul-2002 David LeBlanc wrote: > I have this code: > > fn = file('foo.txt') > > txt = fn.readlines() > > str = ?something?(txt) # or txt.?something?()... > > What's the something? This is probably so obvious, i'm going to feel dumb, > but I havn't been able to find anything in any doc I've looked at. > perhaps the ugliest syntax in all of python. ''.join(txt) # in other words make a string object from '' and call its join() # method i prefer to use import string str = string.join('', txt) From spam at oblomov.org Wed Jul 10 12:06:03 2002 From: spam at oblomov.org (oblomov) Date: Wed, 10 Jul 2002 18:06:03 +0200 Subject: JPython and Jython Message-ID: <20020710180603.50a4e417.spam@oblomov.org> Could someone tell me a bit about the diffrences between JPython and Jython? I want to implement Python as a scriptlanguage in my Java environment. What would be the best solution? kalle From bokr at oz.net Sat Jul 27 18:49:02 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Jul 2002 22:49:02 GMT Subject: how to count lines in a file ? References: <7aU%8.139472$vm5.4528856@news2.tin.it> <1027656130.63094@yasure> Message-ID: On Fri, 26 Jul 2002 07:34:02 GMT, Alex Martelli wrote: >Donn Cave wrote: > ... >> the garbage collection changes to the C Python that we use have not >> compromised its reference count driven behavior at all. > >Not yet. If one day a smart non-RC collector shows the potential >for, e.g., 20% or 25% speedup, though, what then? > > >> You're just looking at the other Python there, Jython. Its object >> lifetime policy is Java's, and that doesn't support timely finalization. >> There's your spanner. > >"Timely finalization" plays very badly with efficient garbage >collection. You can count on a good GC system to NOT guarantee >"timely finalization", more or less. > >One thought I've toyed with, at times, is to have the optional >ability to mark a few objects as _requiring_ stricter finalization >semantics than the run-of-the-mill kinds of objects. E.g., files >could be marked that way. References to such special objects would >then also have to be special and require the typical RC overhead >when manipulated. Cycles involving such objects would still be >a bother, of course. Alternatively, all references to such objects >could be special kinds of weak references EXCEPT one reference >held in the creation frame -- the object would then, differently >from all others, be owned by one specific primary reference and >finalized (with all other references to it, being weak, becoming >invalid) when that one specific primary reference goes away. > >Semantics could be per-object rather than per-type, e.g.: > > local(open('foo','w')).write('hi!\n') > >would not INSTANTLY close foo, but it WOULD close it as part >of the cleanup for the current frame thanks to the hypothetical >local() builtin. The .write() call would in this case be >happening on a kind of weak proxy for the file object. > >When I get to this point in my musings I typically tend to >get lost wondering how to UN-localize such an object so that >after the fact it's possible to get a more persistent reference >to it, etc, etc. But maybe even the simplest kind of 'local()' >could already have some usefulness, perhaps enough to make it >worth experimenting with. > I like this, but I think I would rather see timely finalization subsumed under a general event-handling mechanism for objects. Thus ref count going to zero would be a standard event that you could write a handler for. A rack of event handlers might be specified much like __slots__, except a list of tuples instead of names, (could use a dict, but might want to specify piority order to put likely events first) e.g., (using a fictional container for standard platform event, perhaps extendable a la sys.modules): class Foo: __events__ = [(sys.events.ON_ZERO_REFCOUNT, myFinalize)} ... def myFinalize(self, event, *rest): self.f.close() ... Regards, Bengt Richter From donn at u.washington.edu Tue Jul 9 15:30:48 2002 From: donn at u.washington.edu (Donn Cave) Date: 9 Jul 2002 19:30:48 GMT Subject: expect module and/or functionality? Or SSH wrapper module? References: Message-ID: Quoth claird at starbase.neosoft.com (Cameron Laird): ... | If not, no, you can't Expect with pure Python; there's no | practical way to get the pseudoterminal munging right without | calls into the C run-time library that Python itself can't | access. | I'm working on techniques to use standard distribution instal- | lations of (Tcl-based) Expect and (pure) Python to achieve | general results. The idea is that many hosts--essentially | all Linuxes, for example--are already equipped with these | executables, so all you'd need to install are your pure-Python | scripts. I don't have these ready yet, though. That will be interesting. There is actually some pseudotty support in posixmodule. Not sure if anyone has ever managed to make any real use of it - opening a pseudotty is only the start of your problems - but on some platforms (quite a few more than come with Expect), you can at least open a pseudotty. Expect is a big step up from there, though. Donn Cave, donn at u.washington.edu From anton.wilson at camotion.com Tue Jul 30 18:48:40 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 30 Jul 2002 18:48:40 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207302247.SAA21093@test-area.com> On Tuesday 30 July 2002 07:18 pm, brueckd at tbye.com wrote: > On Tue, 30 Jul 2002, anton wilson wrote: > > Maybe I am not being clear enough. I am concerned with a multi-threaded > > program that does not do any form of blocking on a Linux/Unix box. > > Quick tangential question: if there's no blocking of any kind, why are you > using threads, anyway? Off the cuff thinking says this seems like a misuse > of them. For a real-time system. ;) It will work. It would just be nice if they switched exactly every 10 byte codes becuase that means they only use about 10 to 20 milliseconds each. > > [0, 0, 0] > > > > ....(100+ times in all)... > > > > [35499, 16419, 0] > > > > ...(100+ times in all) .... > > > > [35499, 16419, 11556] > > > > This proves that the GIL does not block very often, and definitely not > > every 10 byte codes. Think about this for a while. > > No, it doesn't "prove" anything about the GIL. Without the print > statements, the main thread is spinning like crazy - the other threads > probably aren't even getting _started_ right away. The rest of the input shows that the lock is released and immediately reacquired even after threads start. The second set of printouts look like [35499, 16419, 0]. So the threads have started. Then the main thread prints out about 130 of those statements. That is past 10 byte codes. Therefore, it was releasing and reacquiring without hindrance. > Note that if you try the above experiment in C (start 3 threads and > immediately have main thread spin and print out wildly) you'll get very > similar output (lots of [0,0,0]'s printed at the beginning, etc). This should happen. I was just counting on python to force a 10 byte-code block once the threads did get started. Wrong assumption, but it nice assumption to be able to make. I really wanted it to run and block every time. It actually does wake up the other thread, it just doesn't block like I wanted it to. > > Just curious: how do you explain all the multithreaded Python programs > that currently work just fine? Are these all flukes? This brings me to the second reason that your program seems to work. The Linux OS gives threads time-slices and when these time-slices are used up every 150 or so milliseconds, the process is forcibly removed from the CPU. I presume that the reason your program seems to work is that in the time between when a thread releases the GIL and a thread tries to reaquire the GIL, it is forcibly removed from the CPU, and the other thread can now run. This would not be a rare occurence due to the high frequency at which the lock is released. > -Dave From flognat at flognat.myip.org Tue Jul 30 16:14:16 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Tue, 30 Jul 2002 20:14:16 GMT Subject: Win32com, "Microsoft Internet Controls" vs. "Microsoft HTML Object Library" Message-ID: Hmm I suppose, not 110% python, but I am examining the world of com with python, and I need pointers to the docs. I am following the ancient guide how to interface with MS IE through Win32 extensions, run Makepy on "Microsoft Internet Controls", and weeh I can fire up an IE and navigate around.. the nice PythonWin editor. >>> from win32com.client import Dispatch >>> ie=Dispatch("InternetExplorer.Application") >>> ie.Navigate("somewhere") When using it in pythonwin it doesn't suggest much, like typing doc. I only get a listbox with choices I have used.. But if I Makepy on "Microsoft HTML Object Library", the listboxes is full, contains much, but the structure of ie is different, not the same functions/variables.. Whats the diff, where do I read how to fix? I think I know where the MS IE controls docs can be found, IWebBrowser2, but what to look for for the HTML Object Library? Or am I totally off?? /Andy -- The eye of the beholder rests on the beauty! From thefogger at web.de Mon Jul 15 11:48:22 2002 From: thefogger at web.de (Jan Felix Reuter) Date: Mon, 15 Jul 2002 17:48:22 +0200 Subject: Python CGI - Session Management Message-ID: Hi, I'm trying to implement some session management in my website, to keep track of logged-in users. The site is entirely made of CGI's written in python. I just don't know where to start, I've looked at the Cookies module, I understand that allright, but where do I place the code in my CGI's? How does one do session managment in Python, anyway? Aren't there any modules that I have overlooked? Also, I'd like to know if there's a good website with resources about programming for the web with python. I google search didn't give me any meaningful results. Have fun, Felix From shalehperry at attbi.com Mon Jul 22 17:23:33 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 22 Jul 2002 14:23:33 -0700 (PDT) Subject: Python very slow on the Sharp Zaurus - any idea why? In-Reply-To: <20020722233024.5bec8f5f.alexandrecourbot@linuxgames.com> Message-ID: > > Yeah, I wonder if it's worth to profile the stuff! :) > whenever you have a speed question it is worthwhile to profile. Try profiling your game first, then python itself. > Guys, I'll first test it with Python 2.1.3. Adonthell (the game I'm > porting) works with any Python >= 1.5.2, so if the problem can be solved > in the short-term by regressing to 2.1, that'll be fine for now. If the > differences are significant, then maybe we could consider to add another > interger-only checking method that would suit in the case of Arm > processors. I'll try to give you news about it tomorrow. > Another possibility is the runtime overhead of constantly reading and running scripts. The Zaurus does not have the benefit of a pc's cache or swap space. But this is idle speculation until you have some profiling numbers. From usenet at thinkspot.net Sun Jul 7 15:29:18 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 07 Jul 2002 12:29:18 -0700 Subject: procmail replacement in Python References: <3u8pea.617.ln@127.0.0.1> Message-ID: On 07 Jul 2002 09:05:33 -0400, pinard at iro.umontreal.ca (Fran?ois Pinard) wrote in comp.lang.python in article : > [Fran?ois Pinard] > > > Here is a copy of my copy: > > Oops, sorry! > > I should not have Cc:ed python-list with the full archive. On the other > hand, as it is rather small, I think I will nevertheless sleep tonight :-). > In a word, I apologise, and will try paying more attention in the future. Francois, Thanks or the copy I received in email. However, that tarball that you sent seems to be incomplete and doesn't have any .py source files. Seems mostly to have .pycmailrc and other types of config files, .doc type files and install files. The README files make it look very intriguing. I'd sure like to get my hands on the Python source. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tim.one at comcast.net Sun Jul 28 12:18:24 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 28 Jul 2002 12:18:24 -0400 Subject: connection problems In-Reply-To: Message-ID: [giovanni] > Hello. In these days I am finding some problems in reaching > www.python.org. > Is it just a problem of mine or what? No, sorry to say it's universal. > Is the site under maintenance? We wish . Last I heard, the logs showed that the newly revitalized Wiki was going insane, and every time the site is brought back up it runs out of disk space a few hours later and crashes again. I'm not sure whether someone who knows all about the Wiki implementation has contacted Thomas Wouters yet. Patience, please; /F pointed you to a list of mirror sites for the duration. From imbosol at vt.edu Tue Jul 30 16:16:10 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 30 Jul 2002 16:16:10 -0400 Subject: lexing nested parenthesis References: Message-ID: Carl Banks wrote: > Fran?ois Pinard wrote: >> [Kristian Ovaska] >> >>> The language category you're dealing with is called context-free grammars. >>> It's more expressive than regular languages, and it can parse any >>> programming language. >> >> Any? :-) >> >> I would not go that far. There are strange beasts out there. > > Like, for example, C. Expressions can parse differently depending on > whether a symbol has been typedefed or not. Oops. I meant declarations and statements can parse differently, not expressions. -- CARL BANKS http://www.aerojockey.com From Gabe.Newcomb at noetix.com Tue Jul 23 22:04:52 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Tue, 23 Jul 2002 19:04:52 -0700 Subject: Tkinter Grid manager question Message-ID: <0C7CA8D8DF75494EB09AB6016990107FF0F894@NOXMAIL.noetixad.com> Basically put, I have 3 frames in a single root window, each one has been created using the widget.grid statement like so: f1 = Frame(root,height=80,width=900,bg='lightyellow') f1.grid(row=0,sticky=E+W) f2 = Frame(root,height=550,width=900,bg='lightyellow') f2.grid(row=1,sticky=E+W) f3 = Frame(root,height=100,width=900,bg='lightyellow') f3.grid(row=2,sticky=E+W) after this, I want to stick four different widgets alongside each other in the first frame (f1). Within this first frame, I create 4 sub frames, all this way ('app_width' is the total width of the root window, in this case 900). f1_1 = Frame(f1,height=80,width=int(app_width/4), bg='lightyellow') f1_1.grid(row=0,column=0,sticky=W+E) f1_2 = Frame(f1,height=80,width=int(app_width/4), bg='lightyellow') f1_2.grid(row=0,column=1,sticky=W+E) f1_3 = Frame(f1,height=80,width=int(app_width/4), bg='lightyellow') f1_3.grid(row=0,column=2,sticky=W+E) f1_4 = Frame(f1,height=80,width=int(app_width/4), bg='lightyellow') f1_4.grid(row=0,column=3,sticky=W+E) Now, when I put widgets in these frames, it becomes apparent that the frames aren't really 225 pixels wide. It's very difficult for me to make things look nice. Anybody have any tips on what I'm doing? Are the frames' widths being overridden by the small size of the widget each one might contain? Thanks in advance! Gabe From roy at panix.com Mon Jul 8 15:02:41 2002 From: roy at panix.com (Roy Smith) Date: 8 Jul 2002 15:02:41 -0400 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <080720021458067296%pecora@anvil.nrl.navy.mil> Message-ID: Lou Pecora wrote: >Solution? Sometimes I just use the underscore "_" as the self object >reference. That shortens the name. You don't have to use the word >"self." viz., > ># Within the object definition, x and z are object variables ... > > def func(_): > y=_.x * _.z > return y > >Not the best solution, but saves typing. Saves typing, yes, but makes your code harder to understand by somebody else who has to read and maintain it later. From brueckd at tbye.com Tue Jul 2 03:48:24 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 2 Jul 2002 00:48:24 -0700 (PDT) Subject: I'd give up Perl tomorrow if only... In-Reply-To: <20020701124340.G10625@prim.han.de> Message-ID: On Mon, 1 Jul 2002, holger krekel wrote: > > > But somehow one doesn't hear it very often from people who've been using > > > Python for a long time > > > > Just to chime in - Aahz hit the nail on the head here... for whatever > > reason, *not* having a CPAN thingy just isn't that painful right now. > > I somewhat disagree. IMO the standard-lib approach doesn't scale very well. > Python seems to get to a stage where the google-path doesn't cut it, either. I don't think it scales that well, either, and I agree that it's not the best long-term solution, but for now it seems to be an important-but-not-urgent type of problem. That's why I think it's a good idea to keep working on a solution. IOW, if one's focus is on the present and they say, "we need CPYN" I say, "nah", but if one's focus is on the future I say, "yeah". :) > >From Guidos keynote at EuroPython i recall some statistics about python's > growth. A Comprehensive Python Network (CPYN) could accomodate and support > this growth. Better sooner than later, not? Sure... I'm just musing that (1) when it becomes urgent (or a little sooner) I'm fully confident it'll get built and that (2) not being too urgent is why it hasn't happened yet. -Dave From chris.gonnerman at newcenturycomputers.net Tue Jul 16 00:12:24 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 15 Jul 2002 23:12:24 -0500 Subject: Windows modem question... References: Message-ID: <001101c22c7e$ff5bc160$0101010a@local> ----- Original Message ----- From: "Jason" > I've been digging through all of the past posts about using a modem, > and everything seems to reference serial modems. I was just wondering > if the serial modules will allow me to access internal modems, or if > that's a whole other problem. If it is a whole other problem, please > steer me in the right direction. Thanks. Internal modems ARE serial modems. There is no difference. Even nasty WinModems fake the Hayes-type AT command set behind a COM port interface. On Unixoid OS's you would be accessing /dev/ttyNN type portnames. I've never used the LinModem drivers so I don't know how they work. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From bokr at oz.net Tue Jul 16 18:10:38 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2002 22:10:38 GMT Subject: Newbie: Capture output of compile_dir References: Message-ID: On 16 Jul 2002 02:35:28 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >A quick experiment: > >>> class X: > ... def __init__(self): > ... self.s = [] > ... self.softspace=0 > ... def write(self,x): self.s.append(x) > ... [...] > >>> sox=X() > >>> sys.stdout = sox > >>> print 'hello',;sys.stdout.softspace=0;print 'hello' > >>> print 'hello',;print 'hello' > >>> sys.stdout = orig_so > >>> sox.s > ['hello', 'hello', '\n', 'hello', ' ', 'hello', '\n'] > >Nope, seems to be looking at original sys.stdout.softspace Oops, not so: sys.stdout.softspace=0 was effectively sox.softspace=0 there, so it seems to be using it if it's available (actually it creates it if not), but the bug is that either interactive echo characters should be teed/copied out to a redirected stdout *OR* interactive echo should not touch redirected stdout's softspace. ISTM the latter is more correct. >irrespective of redirection. And I'm still not sure that >third line is right. Why should the interactive echo to the next >line make a difference to softspace when stdout is re-directed? >Or is that what does it? It seems like a bug someplace... It still seems so to me, so I will post this under a bug heading. Regards, Bengt Richter From sholden at holdenweb.com Sat Jul 27 00:00:55 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:00:55 -0400 Subject: tarfile.py question References: <3d41619d$1_2@nopics.sjc> Message-ID: "Adonis" wrote in message news:3d41619d$1_2 at nopics.sjc... > i have downloaded tarfile.py by Lars Gust?bel and have trouble reading > tar.gz files. i am using the following code: > > import tarfile, sys > > if len(sys.argv) == 1: > print 'usage: untar ' > sys.exit() > > x = tarfile.TarFile(sys.argv[1], 'r') > tarfile.errorlevel = 1 > tarfile.debug = 3 > m = x.getmembers() > for i in m: > x.extract(i, sys.argv[2]) > x.close() > > i attempted to read a tar.gz file (gadfly) and when i load it no error is > posted nor any information at that, but the m variable is an empty list, > and if i attempted to do x.list() to get a list of files it returns None, > although it seems that it loaded the tar file properly no IOError was > generated, is there something i am missing? i have tested this by generating > a tar.gz file using the same module and it unpacked properly. > You need to ask yourself about the source of the "tar" files. Some web sites and browsers combine to use on-the-fly decompression, but if the client is clueless you can end up with an uncompressed file named "xxx.tar.gz" (for some reason this always seems to happen with Marc-Andre Lemburg's alpha and beta release files). So you should verify that your file really *is* both compressed and a tar file. See below for a suggestion as to how you might do this. > any help is greatly appreciated. > We do our best. Only you can say whether it's help :-) > Adonis > > note: im a windows user so i have no tar archiving present. > This may be the problem you should sove first. I'm an enthusiastic Cygwin user (see http://www.cygwin.com/), and that includes tar as one of the many Unix goodies you will suddenly find are available. "file" would be even more useful in this case. Just because you use Windows doesn't mean you can't get many of Unix's advantages too, you know! Hope this helps. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From johnroth at ameritech.net Sun Jul 28 07:49:58 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 28 Jul 2002 07:49:58 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <3D41AC9E.6080103@onsitetech.com> <41j09.125397$Jj7.2891527@news1.tin.it> <3D439089.3010305@nowhere.org> Message-ID: "Fredrik Lundh" wrote in message news:NuN09.1347$HY3.367000 at newsc.telia.net... > Bryan Olson wrote: > > > The mistake was limiting lambda to expressions. > > Guido can channel himself (or Tim will do it), but from what > I can tell, he's always said that the "mistake" was adding > something to the language that almost, but not completely, > works like lambdas do in other languages. > > (lambda, map, filter, etc was contributed code) > > the really big usage problem (whether you knew lambdas > from other languages or not) used to be that they were a > real pain to use under the LGB scoping rule. with the intro- > duction of nested scopes, that problem no longer exists. > > to fix the other "mistake", some needs to come up with a > really great syntax (and get michael hudson to implement > it for them ;-). ideas are welcome. What's the problem with that? If we give up the notion that anonamous functions need to look like expressions, it should be simple. Just stick the function definition inline, indentation and all. The only issue is defining a new keyword, since lambda doesn't work that way. "def" would probably work, since it's only allowed at statement level now. John Roth > > > > From uwe.schmitt at procoders.net Sun Jul 28 16:19:21 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 28 Jul 2002 20:19:21 GMT Subject: announcement Message-ID: Hi, in order to become acquainted with wxPython I developed a programm which facilitates the drawing of resistor nets, and is able to compute associatied electrial values. You can find more information at http://ziarc.procoders.net Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt python, php, c++, codes, tips, tutorials at uwe.schmitt at procoders.net http://www.procoders.net From benniego_s at mac.com Sun Jul 21 09:23:44 2002 From: benniego_s at mac.com (Bennie) Date: Sun, 21 Jul 2002 13:23:44 GMT Subject: Module Problem References: <1d95285a.0207161422.54dd6956@posting.google.com> Message-ID: <3D3AB5E0.2010008@mac.com> Carl heeft geschreven: > - I downloaded the Python22 software along the the Python Manuals. > - I got the part where you are supposed to save the fibo.py module. > - I saved the module to C:\Python22 using the notepad in windows 98. > the file in that directory was saved as fibopy~1 > the full file name reads as fibo.py.txt > - The python shell does not recognize this as a module when I try to import it. > - Please help me get around this problem. > > Thanks. Save in notepad with "fibo.py" you have saved as a text file. Look by type and than all or "fibo.py" and than save. For now, rename it in the command prompt. 'rename fibo.py.txt fibo.py' From me at michaelbauers.com Sat Jul 20 04:22:41 2002 From: me at michaelbauers.com (Michael Bauers) Date: Sat, 20 Jul 2002 03:22:41 -0500 Subject: text adventure game module for Python References: <7x1y9zmb31.fsf@ruckus.brouhaha.com> Message-ID: I understand a concern like that actually. I am not sure what a system like I am developing could do to avoid it however. Someone creating code for this system could do the same thing manually from within their program whenever they wated to however. I do not see how the environment I am creating makes it any easier for malicious code. "Paul Rubin" wrote in message news:7x1y9zmb31.fsf at ruckus.brouhaha.com... > "Michael Bauers" writes: > > If the user types in "drop rock", the interepreter will return a string like > > 'player.drop(rock)' which is then 'exec'd. Note that interperter excepts > > any string for object. > > Oh no! What happens if the user types > > drop rock);import os;os.system('rm\x20-rf\x20~') > > Do you exec it? > > Don't ever use exec on user input unless you really know what you're doing! From steve at ferg.org Sat Jul 13 09:38:51 2002 From: steve at ferg.org (Stephen Ferg) Date: 13 Jul 2002 06:38:51 -0700 Subject: Recomendations on Books References: Message-ID: I like "the quick python book" by Harms and McDonald, because it is very readable. If you are actually trying to code Python, though, your best friend will be a reference book like the downloadable library reference, or David Beazley's "Python Essential Reference". One of those two will be absolutely necessary for you. From ld at nospam.com Sun Jul 14 16:30:59 2002 From: ld at nospam.com (Larry) Date: Sun, 14 Jul 2002 20:30:59 GMT Subject: List to STR to List References: Message-ID: <7clY8.357964$R61.347463@rwcrnsc52.ops.asp.att.net> I did a typo...should be... List1 = [1,2,3] String1 = str(List1) Is there now a way to convert my String1 variable back into a list??? From yarlevub at aol.com Sat Jul 13 08:56:14 2002 From: yarlevub at aol.com (YarLevub) Date: 13 Jul 2002 12:56:14 GMT Subject: Pyrex References: Message-ID: <20020713085614.10328.00000368@mb-bd.aol.com> >Can any one send me a copy of pyrexc.py for windows because the >pyrexc that ships with pyrex does not work on windows, and I'm a newbie >to pyrex and python. Actually it will work on windows if you use the following command line to run it. python pyrexc You can also rename it to pyrexc.py. If that doesn't work for some reason, try deleting the first line. From martin at v.loewis.de Mon Jul 29 19:35:29 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Jul 2002 01:35:29 +0200 Subject: global interpreter lock not working as it should References: Message-ID: anton wilson writes: > I'm having a problem where the interpreter in ceval.c does not let > threads run concurently. Any thread that holds the lock never gives > up the lock until it has run to completion. I don't believe that statement. Do you have an example program that demonstrates you claims? To demonstrate my point, consider import threading, time def func1(): for i in range(3): print "FUNC1" time.sleep(1) def func2(): for i in range(3): print "FUNC2" time.sleep(1) t = threading.Thread(target=func1) t.start() func2() On my Linux system, it prints FUNC2 FUNC1 FUNC1 FUNC2 FUNC2 FUNC1 Regards, Martin From aleax at aleax.it Thu Jul 25 12:23:57 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Jul 2002 16:23:57 GMT Subject: Refer to function name (newbie ques) References: <805bee23.0207250649.5a4d89d0@posting.google.com> <3D401AF0.8090003@shinners.org> Message-ID: Pete Shinners wrote: > chris ciotti wrote: >> Is there a way to get the name of the running function? In a script >> I'm doing some error checking and I want to be able to name the >> function that screws up. Something like: > > one problem is if the function has multiple names... > > def foo(): > print 'In Foo' > bar = foo Not a real problem: bar.__name__ is 'foo'. The function may have any number of references to it, and may be called from any reference including one without a name, e.g. alist = [] alist.append(foo) alist[-1]() but the name of the FUNCTION, quite independently from the name (or lack thereof) of any REFERENCE to the function, is still 'foo'. Classes, functions and modules are object with names (in attribute __name__). Other kinds aren't, of course. Alex From tdelaney at avaya.com Mon Jul 15 00:29:06 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 15 Jul 2002 14:29:06 +1000 Subject: isA function? Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > For example, a unit test for a factory function might be checking > that instances of several different classes were being returned > depending on the parameters passed in. > > If the code were broken so that only a single class was represented > in the returned objects, Timothy's test would continue to pass > (bad!) while yours would fail - just as you'd want - alerting you > to the bug. Why would this be bad? Presumably you are testing that the returned objects have specified semantics. What does it matter if the returned objects are all of the same type or not - what is important is what happens when you use them. Assuming that the code was *broken*, this would show up in other tests. Artificially restricting the types that you can deal with is generally a bad idea. If it passes all the unit tests, either it is acceptable, or your unit tests are broken. If it passes all your unit tests except for an arbitrary type check, then I contend that your unit test is broken. Tim Delaney From aleax at aleax.it Tue Jul 9 11:40:34 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 15:40:34 GMT Subject: [snake-farm] Broken build system as of 2002-06-04 References: Message-ID: Michael Hudson wrote: ... >> "We've all heard that a million monkeys banging on a million typewriters >> will eventually reproduce the entire works of Shakespeare. Now, thanks >> to the Internet, we know this is not true." -- Robert Wilensky > > Do you really need an explanation of why this is bogus? :) Nah -- everybody knows it's because typewriters are not used on the net. Alex From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 11 14:46:56 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 11 Jul 2002 20:46:56 +0200 Subject: try..catch..finally? Message-ID: <3D2DD2A0.6040500@NOSPAMREMOVETHISxs4all.nl> Is there a reason why the finally clause cannot be used with the catch and else clauses? I'd rather write try: print 1/0 except: print 'oops!' finally: print 'afterwards' instead of: try: try: print 1/0 except: print 'oops!' finally: print 'afterwards' It's no big problem really, one extra try block, but I'm just curious why this is the case. Irmen de Jong. From chartmit.edu Tue Jul 23 16:55:08 2002 From: chartmit.edu (Chris Hartemink (at)) Date: Tue, 23 Jul 2002 16:55:08 -0400 Subject: crc32 with wintel files Message-ID: <7cgrjukbcu3piev8mn1uuc94g104pu9d9n@4ax.com> I'm trying to create crc32 checksums for files, not strings. I found a program on the web http://www.azstarnet.com/~donut/programs/fchksum.html but it is written for unix, and when I try to build it on my Wintel machine, I get all kinds of errors. Is there a way to get this working on Wintel, or might there be another way? .c. From peter at engcorp.com Thu Jul 18 23:48:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Jul 2002 23:48:44 -0400 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> <3D37429C.53BC0FDB@engcorp.com> <5606b639.0207181855.48496f5a@posting.google.com> Message-ID: <3D378C1C.9CA30855@engcorp.com> OtisUsenet wrote: > > Peter Hansen wrote in message news:<3D37429C.53BC0FDB at engcorp.com>... > > OtisUsenet wrote: > > > > > > Python newbie question. How does one do something like this in > > > Python: > > > > > > # assign the value of j to i and then increment j by 1 > > > i = j++ > > > > Is there anything you don't like about doing it exactly as your comment > > reads? > > Yes, actually :) > I don't like the fact that if 'j' is some kind of a global counter > variable, and I'm dealing with multiple threads, it is then, I > believe, possible for 2 or more threads to execute i = j at the same > time (i.e. before 'j' had the chance to increase). > One can probably work around this.... > ...although, now that I think about it, even i = j++ wouldn't be > thread-safe completely, as on the machine code level this still gets > executed in multiple steps.....I think. :) It's even worse than that! Even j++ is not thread-safe, and relying on such behaviour, especially without knowing exactly how the underlying implementation or hardware deals with it, is going to lead you into trouble with threads. Whether C or Python, it's always best to use the defined mechanisms to implement critical sections or similar mechanisms to ensure proper thread safety. Specifically with Python, you should probably be using something like threading.RLock to gain such protection. -Peter From nas at python.ca Mon Jul 8 11:18:30 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 8 Jul 2002 08:18:30 -0700 Subject: Using Python for processing of large datasets (convincing managment) In-Reply-To: <3D282290.1050101@ob_scure.dk>; from spam@ob_scure.dk on Sun, Jul 07, 2002 at 01:14:24PM +0200 References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> Message-ID: <20020708081830.A4427@glacier.arctrix.com> Thomas Jensen wrote: > I am quite certain that scaling (well) to multiple CPU requires one to > use threading at least. What's wrong with fork()? Neil From erno-news at erno.iki.fi Tue Jul 23 07:00:46 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 23 Jul 2002 14:00:46 +0300 Subject: ssh and Python References: Message-ID: In article , "Bo M. Maryniuck" writes: | On Monday 22 July 2002 14:28, Erno Kuusela wrote: || unless the administrator has disabled rsa keys | That's what I'm talking about. that probably means that they have disabled them because they fear people will use passphraseless rsa keys. i suggest you have a chat with the administrator, as hardcoding the password is a worse solution. -- erno From maio at stoupa.sh.cvut.cz Mon Jul 1 10:54:38 2002 From: maio at stoupa.sh.cvut.cz (Marian Schubert) Date: Mon, 1 Jul 2002 14:54:38 +0000 (UTC) Subject: communicate with serial port (ttyS0) References: Message-ID: On Mon, 1 Jul 2002 06:54:39 -0700 (PDT), Shaun Schulze wrote: >Hi > >I am running Debian/Linux kernel 2.4.17. >I need to communicate between custom hardware and my >python script via a serial port, eg. ttyS0, at >115.2kb/s. >I would like to know how to receive and send data to >and from the serial port. I would also like to know >how to set the baud rate of the serial port to >115,2kb/s. If anyone has some examples it will also be >much appreciated. http://www.google.com/search?q=python+serial+port CU, Maio From edream at tds.net Mon Jul 29 08:42:55 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 29 Jul 2002 12:42:55 GMT Subject: Leo.py: Some Thoughts References: <3D44EAA9.7010607@thomas-guettler.de> Message-ID: Hi Thomas, Thanks for these comments. They might be more appropriate for the Open discussion forum on Leo's SourceForge site: http://sourceforge.net/forum/forum.php?forum_id=10226 > +I didn't find a possibility to change the current text field without the mouse. > ctrl-u moves the text field. Can you change the focus without mouse? Control-T, Window-Toggle Active Pane toggles the focus between the outline and body panes. A bug. Some of the items in the Outline-Move/Select menu seem to be permanently dimmed. It should be possible to move the focus through the outline with Ctrl-Up, Ctrl-Down, Shift-Ctrl-Up and Shift-Ctrl-Down. I'll fix this for the next release. > +Link in FAQ "What's the best way to learn to use Leo?" > is broken All the links to this spot seem to works for me. On what page is the link? > +How do you export? The "Save as" method only lets you save as foo.leo Look at the commands in the Import/Export submenu in the File menu. > I am interested in HTML output. You can output anything you want, as long as it is text :-) The FAQ mentions some issues with JavaScript...If you have more questions on this topic, please ask on Leo's Open Discussion forum. > +Can you store pictures or tables (HTML-Tables)? You can store any text. If that text represents pictures or tables, fine. Depending on your situation this might be good enough. Often it is not. This limitation is due to the limitations of the standard Tk Text widget and probably won't be fixed until the Tk Text widget gets more capable. The Yellow Box version of Leo (now defunct) allowed almost anything to be embedded in text. Alas, Apple broke their promise to make YB cross-platform. > +Difference between "Save to" und "Save as"? Save As saves the file and changes the filename in the window, so a later Save saves to the new file name. Save To doesn't change the filename in the window. > +No email adress in the about box. Feedback welcome? I'll put something there for the next release. Thanks for suggesting this. > +If you open it by double-clicking (win32) the path is wrong, > the LeoDocs.leo can't be found. I'll look into this and see what can be done... > A Glossary discribing the following words would be nice: [snip] I'll add these to the glossary. > Exceptions: [snip] > File "leoPrefs.py", line 366, in onCancel > self.set_ivars(c) > File "leoPrefs.py", line 285, in set_ivars > self.target_language = self.lang_var.get() > File "C:\Python22\lib\lib-tk\Tkinter.py", line 234, in get > return getint(self._tk.globalgetvar(self._name)) > ValueError: invalid literal for int(): None Thanks for reporting this. This is new code. I'll fix it for the next release. 3.2 will come out in about a week. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From imbosol at vt.edu Tue Jul 2 02:26:06 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 2 Jul 2002 02:26:06 -0400 Subject: [NEWBIE]-Object referencing?? References: Message-ID: Alistair Campbell wrote: > > I can get all the other data items but a call to; > > current_brew.alcohol > > returns > > Try to forget Pascal. You want: current_brew.alcohol() Python will not call a method unless you put the () there. -- CARL BANKS http://www.aerojockey.com "Nullum mihi placet tamquam provocatio magna. Hoc ex eis non est." From aleax at aleax.it Tue Jul 9 08:51:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 12:51:11 GMT Subject: Converting a hex string to a number References: <4b628986.0207090252.5338178d@posting.google.com> Message-ID: <3%AW8.59659$vm5.2175030@news2.tin.it> tal wrote: > Hello, > I am trying to convert a hex string (for example: "0x12345678") to a > number (0x12345678 or just 12345678). > Can you help me please? > Thanks, Tal. >>> s = '0x12345678' >>> int(s, 0) 305419896 To get 12345678 instead, you'll have to use int(s[2:]) ... :-) Alex From sethtoday at hotmail.com Thu Jul 11 12:22:37 2002 From: sethtoday at hotmail.com (Seth Ainsley) Date: Thu, 11 Jul 2002 16:22:37 +0000 Subject: raw.input and other things Message-ID: An HTML attachment was scrubbed... URL: From schull at digitalgoods.com Mon Jul 29 12:06:06 2002 From: schull at digitalgoods.com (Jon Schull) Date: 29 Jul 2002 09:06:06 -0700 Subject: how do I create a full screen window with TkInter References: <2621b014.0207272101.7e796bc6@posting.google.com> <3lO09.1361$HY3.370982@newsc.telia.net> Message-ID: <2621b014.0207290806.269199e6@posting.google.com> "Fredrik Lundh" wrote in message news:<3lO09.1361$HY3.370982 at newsc.telia.net>... > Jon Schull wrote: > > > What would I add to this snippet to ensure to have the image being > > displayed be all we see? (no titlebar, full size, etc.) > > calls to geometry and overrideredirect. you can find sample > code here: > > http://effbot.org/zone/tkinter-toplevel-fullscreen.htm > > That did it, thanks! From aleax at aleax.it Wed Jul 24 08:29:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 12:29:37 GMT Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3E9BCF.90806@mxm.dk> Message-ID: Max M wrote: > Alex Martelli wrote: > > >> A respectable opinion. Mine is just the reverse -- were it not >> for backwards compatibility, I wouldn't mind losing __call__ in >> instances. A bound method can do it, and we could have a >> _convention_ about how a "primary" method (if any) should be >> named, just as we have for the 'self' argument. It's all >> theoretical anyway, __call__'s never going to go away in fact. > > > I believe you mean something like: > > class WithPrimary: > > def WithPrimary_primary(self): > # primary method due to naming conventions > pass > > Why is this better than having an explicit __call__ method? Is it > because of a dislike of the "__*__" methods in general? It's because of a dislike of *language rules that don't carry their own weight* in general. The more rules a language has, the more complicated it is. Python is not complicated, but it could be even simpler if it were possible to remove all of the deadwood, and I include __call__ in that category. I wouldn't mangle the methodname to include the classname -- no use, and indeed some downsides. Just pick one nice name and use that, is my personal preference. It WOULD mean you can't have an instance polymorphic to a function any more, not exactly -- though *bound methods* of that instance still would be. Boo-hoo, what a loss. > I must admit that I rarely use the __call__ method, but I have found it > very convenient in some cases. How is it more convenient to pass, say, object X, rather than to pass bound method (e.g.) X.primary? Take your example: > The funny thing though is that I have found it most usefull when I need > to set up a function in somehing like map(), sort(), filter() etc. where > I need additional data passed to the visitor function, which these > functions does not allow. They don't allow for such extras because there's zero need for them, of course -- closures, lambdas, bound methods and callable instances provide FOUR ways to perform very similar tasks (and currying, conceptually, a fifth, general way, though mostly you have to implement it on top of one of the other four:-). > So a "shortcomming" in Python is worked around by a strength, if you can > say it like that. I'm not sure I see any shortcoming. Bound methods are a SERIOUS strength, for sure. Closures are VERY handy as an alternative to bound methods -- you may save substantial boilerplate. But __call__ and lambda might perfectly well go without me shedding any excessive numbers of tears. They won't (go) of course, backwards compatibility if nothing else, so this is a quite theoretical discussion:-). Alex From alanmk at hotmail.com Wed Jul 17 07:27:52 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 17 Jul 2002 04:27:52 -0700 Subject: SVG viewer in python? References: Message-ID: gb at cs.unc.edu wrote in message news:... > Does anyone know of an open source SVG viewer written in Python? I'm > working with some students on a project to make SVG drawings (maps in > particular) accessible to visually impaired students. I haven't come across such a thing. The only suggestion I would have for how to get around lack of a pure python SVG viewer would be to use Jython with one of the many open source Java SVG viewers out there, e.g. Apache Batik. This would allow your students to still be writing in Python. However, the implementation of the SVG rendering algorithms, etc, would be Java. HTH, Alan. From fperez528 at yahoo.com Thu Jul 25 12:46:23 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 25 Jul 2002 10:46:23 -0600 Subject: Float class with infinity and stuff, interval computations References: <3d3f5c2b$1@duster.adelaide.on.net> Message-ID: Gerald Squelart wrote: > Hi all, > > Before I start coding away, I'd like to know if there's a module that > implements a float-like class that includes +/-infinity, NaN and possibly > +/-overflow. > I had a quick look at the Vault, but didn't see anything like that. > If it effectively does not exist, is anybody be interested? (i.e. should I > publish it?) > > Looking at the bigger picture (wow, sounds serious ;-), I'm working on an > interval computations class. Same questions as above... Take a look at numarray, which fixes some of the limitations of Numeric's IEEE floating point handling. But it's oriented towards array manipulations, so it may not quite fit what you have in mind (you may want to do scalar interval-based calculations). Cheers, f. From cliechti at gmx.net Fri Jul 26 14:44:00 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jul 2002 20:44:00 +0200 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: "Britt A. Green" wrote in news:mailman.1027705851.8443.python-list at python.org: > So I know what lambda functions are, they're syntax and how they're used. > However I'm not sure *why* one would use a lambda function. Guido may have asked himself similar questions, considering the note on the OSCON and EuroPython slides ;-) > What's the > advantage that they offer over a regular function? you can define a lambda in an expression, while a "def" is a statement. and that's probably all there it is. (lambdas have some constraints as they can only be expressions, but thats a detail) cause' lambdas are expresions, they are useful when writing functional style programs. map(lambda x,y:x+y, range(3), [7,8,5]) chris -- Chris From aleax at aleax.it Fri Jul 26 17:26:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 21:26:23 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> Message-ID: <38j09.146115$vm5.4761453@news2.tin.it> Paul Rubin wrote: > "Britt A. Green" writes: >> So I know what lambda functions are, they're syntax and how they're used. >> However I'm not sure *why* one would use a lambda function. What's the >> advantage that they offer over a regular function? > > You can use them inside other expressions, e.g. suppose you want to > sort a bunch of strings starting with the second letter: > > a = ['apple', 'banana', 'pear', 'watermelon'] > a.sort(lambda x,y: cmp(x[1],y[1])) > > => ['banana', 'watermelon', 'pear', 'apple'] > > Without lambda, you'd have to define a separate named function: Without lambda, you might be more tempted to do it right (a la DSU): aux = [ (x[1], x) for x in a ] aux.sort() a[:] = [ x for __, x in aux ] When you're sorting 4 items, it doesn't matter, but try -- not a huge number -- just 400, say. > There's a middle ground that says the name "lambda" (which comes from > Lisp) wasn't a good choice and another name should have been used > instead, like maybe 'func', which does the same thing. I guess that's > reasonable. I'm used to lambda from Lisp but another name would > probably be less scary to non-Lisp-users. It's not an issue of syntax sugar as superficial as what keyword to use. A REAL lambda, by any other name -- the ability to package up ANY chunk of code, not just an expression -- might add power enough to justify its existence. Today's lambda's just deadweight. And I do _not_ say that as a "non-Lisp-user" (though it's been a LONG time since I last used Lisp, or Scheme for that matter, in production use). Alex From merman at snafu.de Sun Jul 7 11:12:36 2002 From: merman at snafu.de (T. Kaufmann) Date: Sun, 07 Jul 2002 17:12:36 +0200 Subject: newbie-question: more then one constructor in a python-class? Message-ID: <3D285A64.6000904@snafu.de> Hi python-experts, is there a way to have more (then one) constructors in a python-class (like in Java)? I mean something like this in Java: public class MyClass { public MyClass() { ... do anything here } public MyClass(String param) { ... do anything here } public MyClass(String param, StringBuffer param) { ... do anything here } public static void main(String [] args) { ... } } Thanks for help. o-o Thomas From sadams123 at optushome.com.au Thu Jul 25 02:11:41 2002 From: sadams123 at optushome.com.au (Steven) Date: Thu, 25 Jul 2002 16:11:41 +1000 Subject: UDP Multicast HELP! References: Message-ID: <3d3f969f$0$11269$afc38c87@news.optusnet.com.au> > I truly appreciate you taking time to respond, but I really don't understand > what you are trying to explain to me. Everything else in python seems so > easy, and creating a tcp socket and udp socket is so easy, just a few lines > of code. I am really surprised that there is no EASY way to join a group. if you do a search at Google in the groups archive you should find plenty of examples on using IP multicast in Python Some example code I found has been uploaded here: http://www.tetrica.com/quickdry/python/ Steven From trentm at ActiveState.com Fri Jul 5 04:53:09 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 5 Jul 2002 01:53:09 -0700 Subject: ANN: px/p4lib.py v0.6.6 - a p4 wrapper and a Python Perforce interface Message-ID: <20020705015309.E5086@ActiveState.com> Where? http://starship.python.net/~tmick/ What are 'px' and 'p4lib.py'? Perforce is a source code control system (like CVS). One uses the p4 command line application (and/or a GUI client) to work with a Perforce repository. 'px' is a wrapper around p4. It provides all the functionality of p4 (defering work to it) plus it extends some standard p4 commands and adds a few new ones. If you are a Perforce user you might find these extensions useful. 'px' uses p4lib.py, a Python interface to the Perforce client application. If you are a Python programmer and script Perforce you might find this module helpful. Currently, most common commands (though your definition of "common" may differ from mine) are supported. What platforms? Windows and Linux. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From fredrik at pythonware.com Tue Jul 2 15:23:43 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Jul 2002 19:23:43 GMT Subject: Pyrhon language dedicated Wiki References: <53E8D5252F2A56A6.2639E30B7671B7A6.D458EC04D7BBB7B5@lp.airnews.net> <0X_T8.69154$F16.21319@atlpnn01.usenetserver.com> Message-ID: <35nU8.46034$n4.10990740@newsc.telia.net> Chris Liechti wrote: > > maybe we should start here: > > > > http://www.python.org/cgi-bin/moinmoin/Python > > > > and see what happens... > > ... > File "/usr/local/apache/MoinMoin/parser/wiki.py", line 335, in replace > return apply(getattr(self, '_' + type + '_repl'), (hit,)) > AttributeError: Parser instance has no attribute '_hmarker_repl' I have no idea -- it did work just fine about 30 minutes before I saw your post... Is J?rgen reading this? Or the python.org webmasters? From heikowu at ceosg.de Sat Jul 20 12:40:41 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 20 Jul 2002 18:40:41 +0200 Subject: Funny behaviour of MySQLdb In-Reply-To: References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> Message-ID: <1027183241.17774.143.camel@d168.stw.stud.uni-saarland.de> Hey Alex! Hey List! Thanks for the advice on threads, and I'm going to try to implement that some time now. The main problem is that the server needs to handle multiple requests at a time, as several servers create a network in which they do an "Identify" at some times. This identify works to create a routing table of the whole network, which is distributed to every server... Of course this method doesn't need database access, but still it would be nice to have a working way to have multiple threads accessing the database. On the other hand, the people writing MySQLdb explicitly stated the approach I chose now. and I guess someone should tell them that this approach is far from bug-free... ;) I guess I'll post something to their ML this night. btw. If anybody is interested in the project as a whole, once I get it to work, then just say so. What this server basically does is offer XML-RPC services to a frontend, and is especially well suited to get all that database and user administration code out of a web-application. It allows for recursive and distributed queries, in which case all servers (or a certain server which is found in the routing table) is queried for the function. The backend server imports modules on startup, which just stick to a certain interface, but that's it. Programming a module for the backend server is very simple. As I said, if anyone is interested, feel free to mail me; I guess I'm going to put the whole thing under the LGPL anyway. Yours, Heiko W. From aleax at aleax.it Wed Jul 10 03:11:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 07:11:51 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: Matt Gerrans wrote: >> Using exec or eval without explicit dictionaries _is_ dangerous, if >> you can't absolutely trust the data. > > Hey Gerhard, can you elaborate a bit on explicit dictionaries or refer me > to some reference material on this? (I did some searching on Python.org, > but only found a few offhand references). It's not very hard, and probably doesn't deserve much more than offhand references. If you just call eval or use the exec statement with a string or codeobject argument, e.g.: exec somestring whatever statements somestring includes will trample over your local and global namespaces. That's invariably a bad idea, with sundry downsides even apart from security -- for example, any function including this statement will slow down badly, because the compiler knows it doesn't know which variables are local (the statements in somestring could change things...). Debugging becomes near-impossible since anything that happens after the exec is a mystery -- you can't count on ANY variable or function name meaning what you think it means any more. Etc, etc. The solution is very very simple: fakelocals = {} exec something in fakelocals that's it! Now the statements in 'something' affect dictionary fakelocals instead of your real locals, there is no huge slowdown, etc, etc. This isn't secure, but it's still a darn sight better than exec without an explicit dictionary (I think Python would be a better language if exec had a MANDATORY 'in' clause). Anyway, whatever names 'something' binds you'll find as items in the fakelocals dictionary after the exec statement. For relative security, see the rexec module in the library docs (there's also a howto about it). It's not solid as a rock, but still better than what you could kludge up yourself. You build up a sandbox and run untrusted code in it -- untrusted code has a few key limitations about introspection / metaprogramming, plus any you want to place on what modules it can use, what entries from module sys, what it can do regarding I/O, etc, etc. You normally use a try/except statement around rexec uses, since all attempts at security violation are diagnosed by exceptions and you normally do want to catch those exceptions and do something about it. Things aren't all that different regarding the eval builtin function rather than the exec statement: result = eval(something, fakelocals) there are a bit fewer issues with eval than with exec, but it doesn't take much to bypass the "can only do expressions" limit, alas. E.g., string something could easily rebind any of your variables, even though it's an expression...: >>> eval('[x for x in (23,)]') [23] >>> x 23 So, it's still better to do: >>> fakelocals = {} >>> eval('[x for x in (23,)]', fakelocals) [23] >>> fakelocals['x'] 23 If you look at fakelocals at this point you'll notice Python has also inserted in it a key '__builtins__' and under it the dict of the built-ins module -- to get restricted execution you have to put a controlled version of built-ins in said dictionary. But use rexec instead, it's easier and better. Both with exec and with eval you may also choose to pass TWO dictionaries -- then, the first is used as fake globals (including the builtins stuff), the second as fake locals (for rebinding names, etc). Alex From aleax at aleax.it Tue Jul 9 11:28:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 15:28:47 GMT Subject: Multi-threading on Multi-CPU machines References: Message-ID: anton wilson wrote: > >> With a multithreaded approach you might keep the array in memory >> and have the main thread farm out work requests to worker threads >> via a bounded queue. You want the queue a bit larger than the >> number of worker threads, and you can determine the optimal size >> for a work request (could be one item, or maybe two, or, say, 4) >> via some benchmarking. Upon receiving a work request from the >> Queue, a worker thread would: >> -- get a local copy of the relevant points from the >> large array, >> -- enter the C-coded computation function which >> -- releases the GIL, >> -- does the computations getting the nes points, >> -- acquires the GIL again, > > > If the bounded queue were declared in a C extention module, would a thread > doing the calculations really have to reaquire the GIL everytime that > thread accessed this C data structure? Could mutexes be used instead? C code talking to other C code, with Python *nowhere* in the picture, does not need the GIL but may make its own arrangements. However, it's hard to see how the Python data placed in the queue would get turned into C-usable data WITHOUT using some of the Python API -- whenever ANY use of the Python API is made, the thread making such use must hold the GIL (of course Python can't _guarantee_ that EVERY such GIL-less use will crash the program, burn the CPU AND raze the machine room to the ground, unfortunately, but you should still program AS IF that was the case). Given that a C-coded function is called from Python, it IS holding the GIL when it starts executing -- what it must do it to RELEASE the GIL as soon as it's finished doing calls to the Python API in order to let other threads use the Python interpreter, then acquire the GIL again before it can return control to the Python that called it. There is no benefit that I can see in duplicating the Queue module in C with all the attendant locking headaches &c -- moving the loop itself into C seems to be a tiny, irrelevant speedup anyway. Alex From jdavis at empires.org Tue Jul 16 03:32:44 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 16 Jul 2002 07:32:44 GMT Subject: namespaces in python Message-ID: Is there a way to put functions and variables in a different namespace without putting it in a seperate file or instantiating a new object? Is there a way to have static methods that don't require instantiating the object first? I just want a clean way to divide up my modules a bit without cluttering up the filesystem (or requiring seperate i/o operations to fetch several files). Thanks, Jeff From g.vonrotz at chello.nl Wed Jul 3 14:28:39 2002 From: g.vonrotz at chello.nl (Ria) Date: Wed, 03 Jul 2002 18:28:39 GMT Subject: how can I put mysql input without ([,]) Message-ID: Hi, I have a question about list or string in Python/Jython. If I get a select command from mysql en put it in a string (print) than I can't use it. example... I wil know how many rows ther are in my database table: >>>cursur.execute("select count(*) from table") >>>data = cursur.fetchall() >>>if data: >>> for a in data: ... print a ... ([21345,]) how can I put only the 21345 without the ([,])?? Bennie, From gerhard.haering at gmx.de Wed Jul 3 12:21:38 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 3 Jul 2002 16:21:38 GMT Subject: creating XML elements References: Message-ID: Somebody claiming to be named "so very tired" wrote: > Hi, > I've been using python for parsing XML, but I need to now create and add > elements with subelements, attributes and text. How do I do this using > the DOM libraries assuming I just have an XML document with a root node? Here's an example: http://www.cs.fhm.edu/~ifw00065/VitaminP/addressbook.py These are the key lines: doc = implementation.createDocument(None, None, None) addressbook = doc.createElement(xmlconstants.AddressBook) doc.appendChild(addressbook) The rest is pretty obvious. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cliechti at gmx.net Tue Jul 23 13:35:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 19:35:05 +0200 Subject: how to count lines in a file ? References: Message-ID: "Denis S. Otkidach" wrote in news:mailman.1027443271.32201.python-list at python.org: > fp = open(filename) > it = iter(fp) > try: > while it.next(): > count += 1 > except StopIteration: > pass just a little sidenote: what you have written here is correct but the same as: for line in file(filename): count += 1 the only little diffrence is that line is left bound to the last line. however I consider this as much more readable. (the use "file" or "open" does not matter, i find "file" better readable in this context) chris -- Chris From gtalvola at nameconnector.com Tue Jul 16 12:42:40 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Tue, 16 Jul 2002 12:42:40 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty Message-ID: <61957B071FF421419E567A28A45C7FE514A5C4@MAILBOX.nameconnector.com> Tim Peters wrote: > > [Geoffrey Talvola] > > ... suppose that I actually did want the behavior I described above > > -- a reliable "if the queue is empty, raise the Empty exception, > > otherwise remove and return an item from the queue". > > If you're also not willing to block, you can't. You could > start by trying > > if the_queue_looks_empty_right_now: > raise Empty > else: > ??? > > If it takes the "if" branch, the queue may well become > non-empty by the time > the calling thread sees the exception. OTOH, if it takes the > "else" branch, > what are you going to do? There's no guarantee that the > queue is *still* > non-empty by the time you get to the "???" part. You have to > grab a lock to > say anything for sure, and as soon you try to grab a lock the > possibility > for blocking comes with it. > > > How would I write it? Do I need to busy-loop like > > this (untested): > > > > def get_nowait_reliable(self): > > while 1: > > try: > > return self.get_nowait() > > except Empty: > > # Let's see if it's really > empty. If not, > > try again. > > if self.empty(): > > raise > > > > or is there a better way? > > Sorry, that it isn't even *a* way. One problem is that it > can block forever > (unlikely, but possible, for another thread to put something > on the queue > every time you get to the "if self.empty()", but take it away > again every > time before you get back to the self.get_nowait()" -- then > you spin in an > infinite loop). > > The other problem is that it's quite possible that > self.get_nowait() raises > Empty, and self.empty() returns True, and that 100 other > threads then put > things back on the queue between then and the time your > thread gets around > to doing the "raise". So it's got the same problem you're > trying to solve, > but worse in that it can block for an arbitrarily long time. > > The inherent problem is that "empty" makes no sense except > with respect to a > specific observer at a specific time. Locks let you freeze > the state so > that the lock-holding observer can know the state for certain > while it holds > the lock, but getting the lock can block, and without a lock > you can't know > the state for certain -- you can only know what the state was > the last time > you looked at it, and "in theory", without *some* sort of > hard synch gimmick > an unbounded amount of time can pass between when you gather > the info and > when you're able to act on it. So long as you're working > outside a synched > area, all you can know is what some state was in the past. I understand what you're saying. Would it make a difference if I told you that for this application, it's OK if the "get_nowait_reliable" operation blocks for "a little while"? In other words, I don't mind if it blocks while 17 other threads manipulate the queue. What I care about is that once the queue is no longer being manipulated in other threads, I either get an Empty exception or an object out of the queue. For my purposes if the queue was empty at any point during the operation then raising the Empty exception is OK. My requirements are a bit fuzzier than the strict no-blocking requirement of Queue.get_nowait() so maybe it's possible to implement this. In case you're wondering, this is in Webware's WebKit application server where there is a pool of N threads, and a queue of (non-thread-safe) servlet instances acting as a cache. We only want to create servlet instances when all existing instances are in-use. When a given thread needs a servlet, it basically does: try: instance = cache.get_nowait() except Queue.Empty: instance = new_instance() # use the instance... cache.put(instance) The problem is that every once in a while get_nowait() returns Empty when the queue isn't actually empty, so the size of the cache grows slowly and unboundedly over time. But I'd prefer for the cache to contain at most N instances where N is the number of threads. - Geoff From tjreedy at udel.edu Sat Jul 13 12:10:55 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Jul 2002 16:10:55 GMT Subject: switch recipe? References: Message-ID: "Mark McEahern" wrote in message > Perhaps what I'm still looking for is a way to > weave-two-iterators-with-a-function all at once. One solution would be to > modify or wrap repeating_alternator() so that it was finite--then I could > just use map. *IF* you know the 'length' of iterator, or the iterable it is based on, as in the examples used in preious articles in this thread, this is easy and clean: def firstn(it, n): while n: yield it.next() n -= 1 n = len(iterator) # or whatever map(color_item, iterator, firstn(alternator, n)) Terry J. Reedy From celek at ca.ibm.com Tue Jul 9 09:05:08 2002 From: celek at ca.ibm.com (Christophe Elek) Date: 9 Jul 2002 13:05:08 GMT Subject: Python and Eclipse References: <3D17FAF4.35CC9F1B@earthlink.net> <81CC01E58BF2A99B.DFCD5EC6E4654907.32D731380951B9CA@lp.airnews.net> <3D189A8A.577C8186@earthlink.net> <3D18A6D2.5080404@dmsware.com> <3D18D159.2F66A9E8@earthlink.net> Message-ID: kalab at gmx.net (Gerhard Kalab) wrote in news:bf340738.0207090014.7fd2a74 @posting.google.com: > http://www.kalab.com/freeware/pythoneclipse/pythoneclipse.htm send a note to eclipse.org to have it listed -- Christophe Elek Eclipse Project http://www.eclipse.org From Hobbes2176 at yahoo.com Tue Jul 23 10:40:39 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Tue, 23 Jul 2002 14:40:39 GMT Subject: Make me beautiful (code needs help) Message-ID: Ok, I have the following data: data["A"] = [1,2,4,10,50] and I want to get: data["new"] = [?, 1, 2, 6, 40] That is, I want to get the successive differences into their proper place. I don't care what is in the question mark spot. I'll figure that out later. Here's my current code: for i in range(len(data["A"])): try: data["new"].append(data["A"][i] - data["A"][i-1]) except OutOfBounds: data["new"].append("?") Now, the other problem, is that in general, I want to fill data["new"] with an arbitary function of the values in data["A"]. As a dumb example, I might want to fill data["new"] with copies of the mean (average) of data["A"]. So, in some cases, the new values are relative to the current location (ie i and i-1) and in other they are absolute (ie all of them). I can certainly hack through this, but I'm looking for something pretty. I know python is up to it. Regards, Mark From never at mind.info Thu Jul 18 18:01:11 2002 From: never at mind.info (G. Willoughby) Date: Thu, 18 Jul 2002 23:01:11 +0100 Subject: Calling Fredrik Lundh, (dare i ask) Guido, all other Guru's, could this be a bug? Message-ID: I have been getting an error when quitting an app using a menu to call 'self.master.quit'. the error is: 'The instruction at "0x00d7a0a3" referenced memory at "0x00000008". The memory could not be "read".' I've also had a few people email me about old utils i've released about the same problem. This only seems to occur for people running WinXP. I've never had people email me about this before. My particular OS is WinXP Pro, with ActiveState Python 2.1 (#15, Jun 18 2001, 21:42:28) with PIL (via ppm.py) installed. any ideas whats going on? I never used to get this error with Win98 or WinME. Thanks, --G. Willoughby From fperez528 at yahoo.com Fri Jul 19 00:26:40 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 18 Jul 2002 22:26:40 -0600 Subject: Nested scopes question References: Message-ID: Mark McEahern wrote: > > You might want to read this thread: > > http://groups.google.com/groups?selm=3B98F3B0.53AC2524%40swiftview.com > > As Frederik Lundh points out: > > > http://groups.google.com/groups?selm=Eo7m7.53652%24e5.2684084%40newsb.telia. > net > > once you bind x in bar(), it is considered local.??End?of?story. > > If I remember correctly, this is the example Paul Graham used to make fun of > Python as not yet quite having evolved into Lisp.??;-) > Thanks a lot for the references. So I guess my uglyish hack of hiding the value inside a list is after all the solution for this problem. Well, at least it gets the job done :) Regards, f. From paddy3118 at tiscali.co.uk Sun Jul 28 05:08:10 2002 From: paddy3118 at tiscali.co.uk (Donald McCarthy) Date: Sun, 28 Jul 2002 10:08:10 +0100 Subject: Two dimensional regexp matching? References: <3D4285A3.80407@tiscali.co.uk> Message-ID: <3D43B47A.8090407@tiscali.co.uk> I feel so stupid after David Goodger pointed out that I should match over multiple lines. Of course! So, my example search becomes: r"([DG]).\n(?:..\n){0,2}.W\n(?!.\1\n)" Or, more clearly: r'''(?x)# Verbose #point1 point2 # Comment ([DG]) . \n # point1 == (D or G) (?:. . \n){0,2} # within three samples . W \n # THEN point2 == W (?!. \1 \n) # next point2 != earlier point1 ''' Well, time to try it. Thanks. Paddy wrote: > We already have the re module for regular expression matching on a > string. > > I am looking for pointers to references/algorithms for regular > expression matching for > files of tabular data, i.e. > > Table definition > ================ > 1) Samples from one point in the system appears in a column of the > table. > 2) Samples encoded as characters > 3) All points in the system are sampled at the same time to > produce successive > rows of the table > > So a system sampled at two points in successively may produce the > following file: > > GH > DF > AS > QW > FF > SD > > I want to be able to do regular expression type searches within the > file. Things like > Where can I find point1 == (D or G) then point2 == W within three > samples and where the > next sample of point2 != the earlier sample of point1? > > That was a small example, in reality there is usually hundreds of > points and tens of > thousands of samples in multi-megabyte files but I'd first like to see > if anyone else has > considered this kind of 'two dimensional regexp matching' > > Note: I DO NOT have queries in the date on sample points. The queries > will always be "Find > the range of sample times in which 'this' occurs". > > U have tried Google but without success - I don't know enough to think > of a suitable > search phrase, or, (much less likely), Google doesn't have it ;-) > > > Thanks in advance, Paddy. > From zopestoller at thomas-guettler.de Thu Jul 25 04:52:06 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 25 Jul 2002 10:52:06 +0200 Subject: Bug? cgi.escape(int) Message-ID: <3D3FBC36.2050708@thomas-guettler.de> Hi! It would be nice if cgi.escape(int) would not throw an exception. What do you think? thomas From andreas at kostyrka.priv.at Wed Jul 24 11:05:28 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 24 Jul 2002 17:05:28 +0200 Subject: A better self In-Reply-To: <200720021133247545%pecora@anvil.nrl.navy.mil> References: <200720021133247545%pecora@anvil.nrl.navy.mil> Message-ID: <1027523137.8772.9.camel@vaio2> Am Sam, 2002-07-20 um 17.33 schrieb Louis M. Pecora: > So, only the Python secret brotherhood gets to see The List? Well, it's better this way. The List [of speedup tricks] contains usually ugly things. :) So it's quite correct that it is only presented to the truebelievers. :) There is number of things, but the more important things to keep in mind: - function calls are relativly expensive in Python. At least compared to more static and compiled languages. - immutable objects need to be copied to be modified. str1+str2+str3+str4+str5+str6+str7+str8 is usually slower than "".join([str1,str2,str3,str4,str5,str6,str7,str8]) - every dot access is a dictionary lookup. And python usually cannot do constant folding, etc., because every call is dynamic: So instead of for i in xrange(): x="".join(...) one might write: fjoin="".join for i in xrange(): x=fjoin(...) There are certainly other rules, but these are the ones that came to my mind. :) Andreas From mark.charsley at REMOVE_THIS.radioscape.com Fri Jul 19 07:15:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Fri, 19 Jul 2002 12:15 +0100 (BST) Subject: Dpulicating "class Foo:" in C Message-ID: First let me point out, this is _not_ asking how to wrap up C functions in a python class. I'm using the boost::python stuff to do that with no troubles at all. I'm working on a C++ program where we're using python as an expression parser. We've got a whole bunch of variables and associated expressions that we read in from a file at run time. So for instance we might have a variable called "Foo" and an associated expression "spam * grumby + parrot". "Spam" "Grumby" and "Parrot" would be other variables and have their own expressions. We've had the system working lovely - all the input variables would have an associated Python object (created with PyDict_SetItemString) set to a value, and all the output variables would have an associated Python Expression Object (created with Py_CompileString), and we could set input variables and evaluate output variables fine. The problem came when The Powers That Be decreed that the expressions could be of the form "spam * grumby + Configure.parrot" Configure being a sort of namespace - it's name was fixed, but its contents was not. A quick bit of experimenting revealed that we could hack up namespaces with the following python... class Configure: pass and then we could add arbitrary variables to it, as below: Configure.parrot = "dead" Configure.spam = "spam, spam, spam" Configure.NumberOfChiefWeapons = 2 Configure.NumberOfChiefWeapons = 3 Configure.NumberOfChiefWeapons = 4 Alas after two days of experimentation, I can't find a way to replicate the above python from C. I'm currently having to call PyRun_String("class Configure:\n" " pass\n", Py_file_input, mDict, mDict); during my C++ object's initialisation, and then PyObject* Value = GetValueFromSnippedCode(); char* temp_name = "temp_var_39C22D08_D340_458a"; PyDict_SetItemString(mDict, temp_name, Value); m_ctxt.SetVariable(temp_name,value); std::string expr("Configure."); expr += m_xml.GetName(); expr += " = "; expr += temp_name; PyRun_String(expr.c_str(), Py_eval_input, mDict, mDict); Which works but is rather inelegant, and far from efficient. Every attempt I've made to work out how to replace the above calls to PyRun_String with direct calls to the C API have ended in miserable failure (well Access Violations and/or "foo is not a member of Configure"-style error messages). I was also a bit puzzled not to find any PyClass_* functions in the API: what exactly is a Python class (it seems to be some sort of Dictionary, but I can't work out how to create one)? Many TIA -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From coventry at removethisandallhyphens-o-n-e.net Fri Jul 19 21:06:01 2002 From: coventry at removethisandallhyphens-o-n-e.net (- c o v e n t r y -) Date: Fri, 19 Jul 2002 21:06:01 -0400 Subject: Session ID & Security References: <7x1ya3kkq5.fsf@ruckus.brouhaha.com> Message-ID: <3D38B779.3090602@removethisandallhyphens-o-n-e.net> Why bother reinventing the wheel for a shared memory implementation when you could just use the filesystem like everyone is used to, just on a ram disk? Linux and the BSDs have the capability to do this... Paul Rubin wrote: > Note that using shelve for holding session data shared between > multiple threads or processes is of dangerous unless you're using a > fancy dbm underneath (like Sleepycat). Someone really should > implement a session management scheme sometime using shared memory > instead of messing around with stuff like shelve. From tempe at pp.inet.fi Tue Jul 30 11:58:34 2002 From: tempe at pp.inet.fi (Teemu Luojola) Date: Tue, 30 Jul 2002 15:58:34 GMT Subject: UnicodeError... References: <3D459AE0.5030509@pp.inet.fi> Message-ID: <3D46B617.10909@pp.inet.fi> Martin v. Loewis wrote: > Teemu Luojola writes: > > >>This >>problem is dealt in Python FAQ in chapter 4.102. and the following >>solution is given: >> >> >>> # Set the string encoding used by the Unicode implementation. >>> # The default is 'ascii' >>> encoding = "ascii" # <= CHANGE THIS if you wish >>> > [...] > >>The problem is, that sys doesn't include setdefaultencoding(). >> > > I don't believe you. Did you try to modify this very location in > site.py? At that point, sys.setdefaultencoding is still present. > > Well, here is the result, when I entered precisely what was told in FAQ: >>>> encoding = "ascii" >>>> import locale >>>> loc = locale.getdefaultlocale() >>>> if loc[1]: > encoding = loc[1] > > >>>> if encoding != "ascii": > import sys > sys.setdefaultencoding(encoding) > > > Traceback (most recent call last): > File "", line 3, in ? > sys.setdefaultencoding(encoding) > AttributeError: 'module' object has no attribute 'setdefaultencoding' And here are some dir listings: >>>> import site >>>> site > >>>> dir(site) > ['_Helper', '_Printer', '__builtin__', '__builtins__', '__doc__', '__file__', '__name__', '_dirs_in_sys_path', '_init_pathinfo', '_test', 'addpackage', 'addsitedir', 'dircase', 'encoding', 'here', 'makepath', 'os', 'prefix', 'prefixes', 'sitedir', 'sitedirs', 'sys'] >>>> dir(site.sys) > ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'argv', 'builtin_module_names', 'byteorder', 'copyright', 'displayhook', 'dllhandle', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 'modules', 'path', 'platform', 'prefix', 'ps1', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver'] >>>> dir(sys) > ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'argv', 'builtin_module_names', 'byteorder', 'copyright', 'displayhook', 'dllhandle', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 'modules', 'path', 'platform', 'prefix', 'ps1', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver'] How it is possible, that sys.setdefaultencoding() does not exist? Where to get a proper module? - Teemu From ianb at colorstudy.com Sun Jul 14 11:18:36 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 14 Jul 2002 10:18:36 -0500 Subject: web hosting with python cgi In-Reply-To: <20020714120559.46e0a1f2.wilk-spamout@flibuste.net> References: <20020714120559.46e0a1f2.wilk-spamout@flibuste.net> Message-ID: <1026659917.584.3.camel@lothlorien.colorstudy.net> On Sun, 2002-07-14 at 05:05, William Dode wrote: > In France it's not very easy to find web hosting supporting > python cgi... They think only about php/mysql... > Even the compagny who support python doesn't show it. So > we are not sure they will continue. Most modern Linux distributions include Python as part of the base installation -- at least 1.5.2. I don't know about FreeBSD. If Python is installed, it will be available to you for CGI unless the host goes to efforts to keep people from using it -- which would just be mean (not that there aren't mean hosters). If a provider already has Python installed, even unadvertised, it's very unlikely to disappear. Ian From ingo at hilbert.ingoblank.com Sun Jul 7 14:06:48 2002 From: ingo at hilbert.ingoblank.com (User &) Date: 07 Jul 2002 20:06:48 +0200 Subject: sys.platform on UNIX Message-ID: <85bs9jfm4n.fsf@hilbert.ingoblank.com> Hi, I need a boolean function isUnix(), which returns true, if executed on a UNIX OS. I think it's best, to check the 'sys.platform' string. However, there are lots of possibilities: 'linux*','freebsd*','sunos*','solaris*','irix*','osx*','hpux' ... etc. Q: Is there any "official" statement about distinct contents of 'sys.platform' ? Or is there a better approach to solve this problem? Thanks --ingo voy NG arktb QBG qr [rot13] From mgerrans at mindspring.com Fri Jul 12 02:52:50 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 11 Jul 2002 23:52:50 -0700 Subject: Open document formats References: <96c7f32.0207090659.b5b9a27@posting.google.com> Message-ID: > Who on earth cannot generate PDF?! Even better: Why on earth cannot generate PDF?! If it is on the web and you want people to read it, what's wrong with html? I have never been satified with the Acrobat reader; it's navigation is cumbersome at best. It might be good for printing, but it is terrible for online viewing. From yduppen at xs4all.nl Tue Jul 9 08:30:21 2002 From: yduppen at xs4all.nl (Yigal Duppen) Date: Tue, 09 Jul 2002 14:30:21 +0200 Subject: Converting a hex string to a number References: <4b628986.0207090252.5338178d@posting.google.com> Message-ID: <3d2adb64$0$12283$e4fe514c@dreader4.news.xs4all.nl> > I am trying to convert a hex string (for example: "0x12345678") to a > number (0x12345678 or just 12345678). You can use int(), with 16 as the value for the second argument (radix) >>> int("0x1A2B", 16) 6699 Of course, if the number is very large, this won't work. In this case, use long >>> int("0x123456789ABCDEF", 16) Traceback (most recent call last): File "", line 1, in ? ValueError: int() literal too large: 0x123456789ABCDEF >>> long("0x123456789ABCDEF", 16) 81985529216486895L YDD -- .sigmentation Fault From jbarilla at princeton.edu Mon Jul 15 22:56:24 2002 From: jbarilla at princeton.edu (Joseph Barillari) Date: Mon, 15 Jul 2002 22:56:24 -0400 Subject: Base-class method access In-Reply-To: (Joseph Barillari's message of "Mon, 15 Jul 2002 22:25:46 -0400") References: Message-ID: > Hi. > Is it possible for a derived class to access overridden methods of its > base class? For example: > > > class Foo: > def frob(): << this is incorrect; should be (self) > print "Spam" > > class Bar(Foo): > def frob(): << this is incorrect; should be (self) > print "Eggs" > # In C#, the syntax to call Foo's frob() would be > # base.frob() > > > >> a = Bar() > >> a.frob() > Eggs > Spam > > Is there a means of doing this in Python? > > Thanks in advance. > > --Joe > I found the solution in the Webware source code: invoke the method by calling it as a method of the base class. My apologies for the unnecessary email. >>> class Foo: ... def frob(self): ... print "Spam" ... >>> class Bar(Foo): ... def frob(self): ... print "Eggs" ... Foo.frob(self) ... >>> a = Bar() >>> a.frob() Eggs Spam --Joe -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 265 bytes Desc: not available URL: From pinard at iro.umontreal.ca Sun Jul 14 13:01:34 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 14 Jul 2002 13:01:34 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: References: <7x65zj60ku.fsf@ruckus.brouhaha.com> Message-ID: [Jonathan Hogg] > [...] I consider XML to be "standardised" not because the W3C said so, > but because parsing, validating, querying, and transforming frameworks > are available for nearly any language off-the-shelf, editors support it, > and database and data manipulation tools support it. I'm afraid Pickle > doesn't come close in this regard (and isn't human readable anyway). I can read a pickle with Python and dump it as a readable, pretty-printed Python structure. Conversely, I can have Python to read in a text containing the source of a Python structure, and produce a pickle from the result. The programs to do so are very small. In practice, I do not maintain my original structures as pickles, but rather as very straight Python source files containing about nothing but data structures. These are easy to edit. For most people, even to those not familiar with Python, a Python structured constant is probably easier to read that any XML rendering of it. Python will parse and validate it for me. I can save the original text, or the pickle if I prefer so, in files and databases, and transmit either over networks. Python, the language, is also a wonderful and probably unequalled generic framework for transforming data structures. About being compatible with "nearly any language off-the-shelf", of course, is where some difficulty may rise. Until I have this problem, I'll rather stay comfortable with Python than push myself into miseries I do not need. Then, I could decide to transmit either lines and fields, or XML if available at the other end, or even analyse and produce source or data files for the other language, probably all from within Python. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mwh at python.net Mon Jul 8 07:30:50 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 8 Jul 2002 11:30:50 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D271A91.3D571053@engcorp.com> <3D271C1E.6000000@ob_scure.dk> Message-ID: Thomas Jensen writes: > (Perhaps I'm a bit paranoid about spam, but on the other side I get > less than one spam mail pr. week, which I belive is rather low ;-) Bloody hell yes. Though spamassassin has cut the spam that hits my inbox to about that level... Cheers, M. -- Academic politics is the most vicious and bitter form of politics, because the stakes are so low. -- Wallace Sayre From tundra at tundraware.com Mon Jul 29 13:30:03 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 29 Jul 2002 17:30:03 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: <5pt3ia.i7l2.ln@eskimo.tundraware.com> Syver Enstad wrote: > Tim Daneliuk writes: > > >>On a related note, where in the docs are values for KEY_READ, >>KEY_WRITE, >> >>and so forth, defined? I cannot seem to find these... > > > Can't you just do _winreg.KEY_WRITE instead of bothering with the > exact values? Or if you really want to know: print _winreg.KEY_WRITE > in a python console. > It's not really the values I care about - I want to know all the possible names that can go into the sam field... -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From dreed at capital.edu Thu Jul 18 13:04:13 2002 From: dreed at capital.edu (Dave Reed) Date: Thu, 18 Jul 2002 13:04:13 -0400 Subject: Sharp Zaurus In-Reply-To: <3D36EF5E.1C3EDF1B@noaa.gov> (message from Chris Barker on Thu, 18 Jul 2002 09:39:59 -0700) References: <1026919964.826307@irys.nyx.net> <3D36EF5E.1C3EDF1B@noaa.gov> Message-ID: <200207181704.g6IH4Dx06446@localhost.localdomain> > From: Chris Barker > Newsgroups: comp.lang.python > Organization: NOAA Messaging Operations Center > X-Accept-Language: en > Xref: news.baymountain.net comp.lang.python:173122 > Sender: python-list-admin at python.org > Date: Thu, 18 Jul 2002 09:39:59 -0700 > > sarayu balu wrote: > > Is there any Python, more appropriately Jython, > > The Zuarus is based on QT-embedded (or whatever they are calling it), so > CPython and PyQT couldbe an opiton too, if someone wants to do the port. > > -Chris Python and PyQt are both available from http://www.riverbankcomputing.co.uk/ They work pretty well - I've written a Python program using PyQt for my Zaurus just to try it out. Dave From chris_ciotti at attbi.com Thu Jul 25 18:55:50 2002 From: chris_ciotti at attbi.com (chris ciotti) Date: 25 Jul 2002 15:55:50 -0700 Subject: Refer to function name (newbie ques) References: <805bee23.0207250649.5a4d89d0@posting.google.com> Message-ID: <805bee23.0207251455.4af36522@posting.google.com> chris_ciotti at attbi.com (chris ciotti) wrote in message news:<805bee23.0207250649.5a4d89d0 at posting.google.com>... > Hi - > > Is there a way to get the name of the running function? In a script > I'm doing some error checking and I want to be able to name the > function that screws up. Something like: > > def foo(): > #stuff here > > if stuff != bar: > outfile.write("Mismatch in function %s\n" % (refer to > foo() here) > > > Sorry if this is really obvious. Thanks. Thanks for all the great info! -- chris From tim at bladerman.com Sat Jul 27 09:19:45 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sat, 27 Jul 2002 13:19:45 GMT Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> Message-ID: "Terry Reedy" > > Things I want to change is for example, everything should be "call > > refferense", > > It already is, which is why functions can mutate mutable objects. > (This surprises some beginners.) Of course, for immutables (numbers, > strings, tuples), there is no semantic difference between reference > and value passing except for reduced memory usage. I want to make all variables mutable. When you want to make functions like inc(x) where inc is supposed to increase the value of x by one. How is that done in Python? That is my view of CBR, maybe that is not the correct definition and I don't need CBR. Tim From martin at v.loewis.de Mon Jul 1 02:00:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Jul 2002 08:00:58 +0200 Subject: old thread: SSL support for socket module for server sockets References: Message-ID: Gerhard H?ring writes: > There was an old patch, that was rejected, and > http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=452110 > which I recommended not to include. I disagree. I think the standard SSL module is still the most convenient one to use, and I encourage gradual improvements to it. Waiting for the "big complete rewrite" likely means to wait forever. Yes, there are alternative SSL modules, but unless their authors step forward and contribute them, it is just as if they would not exist. Regards, Martin From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 20:47:17 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 22 Jul 2002 17:47:17 -0700 Subject: URLopener with x509? References: <174d1ff2.0207221638.4738a41b@posting.google.com> Message-ID: <7xy9c3clt6.fsf@ruckus.brouhaha.com> parameter at go.com (bilbo) writes: > I'd like to use https with Python as a client to a private apache > server. Good plan. > Because it's my server and my client, I thought I could create my own > RSA keys. Yes you can. > URLopener looks promising. It can take arguments called key_file and > a cert_file. That sounds like what I need. The documentation leaves > me wondering what should be in the key_file and cert_file. Does > anyone have an example of doing this? Last I looked, URLopener doesn't check certificates, but maybe it does by now. > Does the client need a private key for an https connection? It's optional. It's considered the most secure way to authenticate the client to the server, and eases management if you want to run a server that talks to a lot of different authenticated partners (just run a CA and give them certificates for public keys that they generate themselves). If you don't want to bother with this, since you control both the client and server ends, just set up a shared secret key string between them, for example in an HTTP cookie or HTTP basic authentication. Either of these will run underneath the SSL encryption layer so the secret string won't be interceptable by network snooping. > The code I've tested so far works with official keys from a > certificate authority, but not with my keys (I'm testing without using > the key_file and cert_file arguments). > > I'm hoping I can somehow refer the client to the server's public key > and have the client trust it without asking a certificate authority. Normally you would set up your own certificate authority and issue certs from it. See the ModSSL docs for how to do this. There's a rudimentary CA (perl script) included with OpenSSL and a fancier one written in Python at www.pyca.de. From maxm at mxm.dk Wed Jul 3 08:20:55 2002 From: maxm at mxm.dk (Max M) Date: Wed, 03 Jul 2002 14:20:55 +0200 Subject: Patterns and all that new fangled stuff ... Message-ID: <3D22EC27.4040805@mxm.dk> For the fun and education of it I have recently tried to refactor one of my projects using patterns. I did expect the code to be longer and more verbose, but was a little surprised when I found out that it got exactly twice as long ... But I know the code too well and cannot be objective about it, so I thought I would like to get a second opinion. Which code would you guys prefer to maintain down the line. The short "linear" version or the object oriented "pattern" version. Which one is the easiest to read? It as an .asp project. I have chosen not to include the html part of it as it just inserts html generated from the Python code. regards Max M Btw. It is a page from a project management system #################################################### # Short version first #################################################### import html_tools, iisUtils, mx import Tables import Factory req = iisUtils.request(Request) # date start and stop startDate, endDate = html_tools.getDateRange(req) dateWidgets = html_tools.dateRangeWidgets(startDate, endDate) table = [] # add simple calendar at top of graph dayRange = html_tools.DayRange(startDate, endDate) monthNumbers, dayNumbers, weekNumbers = html_tools.topCalendar(dayRange) table.append(['M?ned', monthNumbers]) table.append(['Uge', weekNumbers]) table.append(['Dag', dayNumbers]) sager = Factory.factory('RM_Sagkart', 'Sag') sager.getAll() sager.sort('Sagsnavn') for sag in sager: start = sag.StartDato slut = sag.SlutDato attr = {'sagsId':sag.GlobalObjectID} attr.update({'startDay':start.day, 'startMonth':start.month, 'startYear':start.year}) attr.update({'endDay':slut.day, 'endMonth':slut.month, 'endYear':slut.year}) table.append(['' + html_tools.url('case.asp', sag.getTitle(), **attr), sag.asGantRow(startDate, endDate, **attr)]) content = str(html_tools.Table(table)) #################################################### # Then the long version #################################################### import html_tools, iisUtils, mx import Tables import Factory import HtmlViewAdapter class PageFacade: """ This is where all the logic takes place on the page, and all the views are generated """ def __init__(self, startDate, endDate): "Set up all objects and data used on the page" self.startDate = startDate self.endDate = endDate self.dayRange = html_tools.DayRange( self.startDate, self.endDate) self.sager = Factory.factory('RM_Sagkart', 'Sag') self.sager.getAll() self.sager.sort('Sagsnavn') def dateWidgets(self): return html_tools.dateRangeWidgets(startDate, endDate) def dateDict(self): s, e = self.startDate, self.endDate return { 'startYear':s.year, 'startMonth':s.month, 'startDay':s.day, 'endYear':e.year, 'endMonth':e.month, 'endDay':e.day } def content(self): table = [] ta = table.append # add simple calendar at top of graph monthNumbers, dayNumbers, weekNumbers = html_tools.topCalendar( self.dayRange) ta(['M?ned', monthNumbers]) ta(['Uge', weekNumbers]) ta(['Dag', dayNumbers]) for sag in self.sager: sagHtmlView = sagHtmlViewAdapter(sag) ta([sagHtmlView.title(), sagHtmlView.gantRow()]) return str(html_tools.Table(table)) class sagHtmlViewAdapter(HtmlViewAdapter.HtmlViewAdapter): "Creates adapter to view sag in html" def getAttrs(self): attrs = {'sagsId':self._obj.GlobalObjectID} attrs.update(page.dateDict()) return attrs def title(self): return '' + html_tools.url( 'case.asp', self._obj.Sagsnavn or '???', **self.getAttrs() ) def gantRow(self): attrs = {'sagsId':self._obj.GlobalObjectID} attrs.update(page.dateDict()) return self._obj.asGantRow( page.startDate, page.endDate, **self.getAttrs() ) ############################### # This gets the initial input from the request, # calls the Pagefacade and starts it all req = iisUtils.request(Request) startDate, endDate = html_tools.getDateRange(req) page = PageFacade(startDate, endDate) From zopestoller at thomas-guettler.de Wed Jul 31 07:01:07 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Wed, 31 Jul 2002 13:01:07 +0200 Subject: ZPT Was: Good XML tools? References: <3D46D1B5.248A2921@q-survey.be> Message-ID: <3D47C373.4040805@thomas-guettler.de> Alan Kennedy wrote: > Laurent Szyster wrote: > >>In many case (if not most) XML processing is far easier with a >>dedicated language like XSLT. Use Python to generate XML and/or >>XSLT, but don't use it to transform XML: XSLT is far better at it. >> > > I strongly disagree. > > Have you looked at Zope Page Templates at all? ZPT is a way of > controlling the generation of (X|HT)ML from python. > > It is my own opinion that ZPT and Python is far superior to XSLT, for > the following reasons. > [cut] I programmed with ZPT, but I switched back to generating HTML with pure python: Example: (ignore the german words) def editListsForm(self, REQUEST): "docstring" ret=[] ret.append(self.standard_html_header()) ret.append('''
Projekte: Bitte w?hlen Sie die zu l?schenden Projekte aus:

%s Hinzuf?gen eines neuen Projekts:
''' %( Utils.keywordInput('del_projekt', self.defaults.GRS.grs_projektList()))) ret.append(self.standard_html_footer()) return string.join(ret) I switched to python from ZPT because python always gives me the line number where the typo/bug is. I wasted too much time searching an error message that happend in an eval(). If I have to create HTML or XML from an XML source I write a SAX parser store the data in python classes or dictionaries and then serialize it to XML or HTML. I prefer this to the magic done by ZPT or DTML thomas From marklists at mceahern.com Sat Jul 13 02:20:47 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 13 Jul 2002 01:20:47 -0500 Subject: switch recipe? In-Reply-To: Message-ID: > So where I've ended up is a place I'm sure there's some fancy > name for--but I don't know it. The thread on zip suggests the term "lockstep iteration." I can't use map or zip though because I have an unbounded iterator. Of course, I could easily bound that to the length of the finite iterator. // m - From jonathan at onegoodidea.com Thu Jul 4 05:51:43 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 10:51:43 +0100 Subject: baffling bug in this bit of code! References: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> Message-ID: On 4/7/2002 7:48, in article e7e4eac4.0207032248.7c988f2c at posting.google.com, "erik_w" wrote: > You might be better off with this snippet of code (if you run 2.1 or newer): > > nodes=self.nodes > locs_x = [nodes[n].location.x for n in nodes.keys()] > locs_y = [nodes[n].location.y for n in nodes.keys()] > max_x = max(locs_x) > max_y = max(locs_y) > > Shorter and probably faster. Hmmm. Shorter, yes; faster, unlikely - since it now has four separate loops and the creation of four intermediate lists. If an intermediate list isn't a problem in space then I'd go for: reduce( lambda (x1,y1), (x2,y2): ( max(x1,x2), max(y1,y2) ), [ (node.location.x, node.location.y) for node in nodes.itervalues() ], (0, 0) ) which is certainly shorter ;-) but breaking it out into an explicit loop would probably be faster. Jonathan From pete at shinners.org Wed Jul 10 11:35:34 2002 From: pete at shinners.org (Pete Shinners) Date: Wed, 10 Jul 2002 15:35:34 GMT Subject: Hierarchical Editor References: <3D2C3458.1090902@thomas-guettler.de> Message-ID: <3D2C5486.9030503@shinners.org> Thomas Guettler wrote: > Does someoone know an editor for editing > hierarchical text data? > > I need it for something like a todo-list. > One task can have several subtasks. > > Should be a GUI, not an web application. i just saw an announcement for a new version of LEO. i've never used it much, but i was just checking it out. it seems to be a generic 'text hierarchy editor'. there's an intro here, http://personalpages.tds.net/~edream/intro.html#anchor887874 and the main site is at, http://personalpages.tds.net/~edream/front.html From sholden at holdenweb.com Mon Jul 29 11:15:01 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Jul 2002 11:15:01 -0400 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> <7xlm7ywa2w.fsf@ruckus.brouhaha.com> <38j09.146115$vm5.4761453@news2.tin.it> Message-ID: "Carl Banks" wrote in message news:ahuqd8$1a7$1 at solaris.cc.vt.edu... [ ... ] > > Personally, I don't care about saving lines, per se. For me, lambda > helps me to avoid stopping mid-function call, scrolling many or few > lines to implement the function as a def, and returning. I.e., > lambdas save me cursor movement. > Well your programming style and mine are very different. I thought the whole point of using functions was to provide a usable abstraction of a portion of a program's logic. I therefore *conceptualize* a function long before I write it, and don't feel the need to make it's source code explicit just because I've caslled it somewhere in my (developing) program. it-take-all-sorts-to-make-a-newsgroup-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From shagshag13 at yahoo.fr Fri Jul 26 13:03:26 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 26 Jul 2002 19:03:26 +0200 Subject: AttributeError in re.findAll ? References: Message-ID: "Fernando Perez" a ?crit dans le message de news: ahru87$6e6$2 at peabody.colorado.edu... > Shagshag13 wrote: > > >>>> p.findAll(t2) > > Traceback (most recent call last): > > File "", line 1, in ? > > p.findAll(t2) > > AttributeError: findAll > > > > In [1]: p = re.compile("<[^>]*>") > > In [2]: p.f > p.findall p.finditer > > > spelling. > > f sorry & thanks s13. From sholden at holdenweb.com Mon Jul 29 11:31:37 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Jul 2002 11:31:37 -0400 Subject: DIV and MOD References: Message-ID: "Marcus Vinicius Laranjeira" wrote ... > I need to use some function like DIV (returns the integer part of a > division) and MOD (returns the reminder of a division) in python, but I > don't know how to do that. % does not work as expected (in this context) > and in the MATH module, I didn't find any kind of function to do such thing. > Perhaps you are looking for divmod()? No need for math modules in that case. >>> divmod(334, 5) (66, 4) >>> regards ---------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From aleax at aleax.it Wed Jul 10 03:45:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 07:45:16 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> Message-ID: Matt Gerrans wrote: >> >> eval! >> > >> >Overkill. Unsafe. Ugly. Lame. >> > >> >> What do you mean by unsafe? > > Also, in addition to the criticism of the suggested method (eval), you > could > post your simpler, safe and able-bodied alternative. Perhaps it was: > > try: > n = eval(string) > except: > n = 0 The one obvious way to perform the task asked for in the subject. and clarified by the original poster, has been posted since MANY posts ago in this thread, and it's n = str(thestring, 0) [you can also use 16 as the second argument if you're sure about the 'hex' part -- 0 looks for a leading 0x as indicator of hex-ness]. Alex From claird at starbase.neosoft.com Fri Jul 26 10:37:04 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 26 Jul 2002 09:37:04 -0500 Subject: GUI toolkits References: Message-ID: <236EC44367AE7427.C793EF1731020582.0EADC366DFAE2535@lp.airnews.net> In article , Steve Menard wrote: . . . >wxPython. Perhaps pyQT or pyGTK would change that, bttu since they are not >(completely) available on Windows, I don't have the choice of even >considering them. . . . Is there a technical problem with PyQt on Windows, or are you saying the license doesn't suit you? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From gumuz at looze.net Thu Jul 4 10:20:42 2002 From: gumuz at looze.net (Guyon Morée) Date: Thu, 4 Jul 2002 16:20:42 +0200 Subject: sending a file through sockets References: <3d243bc8$0$223$4d4ebb8e@news.nl.uu.net> Message-ID: <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> aha, thanx! so the trick is to convert a file to a string representation right? i still have to try it out, but maybe you can confirm my way of thinking here :) ------- encode some_file.jpg to basecode64 makes: SsDfgFVSFgfsaSZFASasfgAS in send it through the socket and decode it back and write it to a file. ------- right? "Bo M. Maryniuck" wrote in message news:mailman.1025787068.11554.python-list at python.org... On Thursday 04 July 2002 14:17, Guyon Mor? wrote: > Who knows how to send and receive a file(binary data) through sockets? At least you can convert it to MIME base64 first... -- Sincerely yours, Bogdan M. Maryniuck As usual, this being a 1.3.x release, I haven't even compiled this kernel yet. So if it works, you should be doubly impressed. (Linus Torvalds, announcing kernel 1.3.3 on the linux-kernel mailing list.) From oliver.eichler at dspsolutions.de Fri Jul 5 05:41:06 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Fri, 05 Jul 2002 11:41:06 +0200 Subject: redirect stdout References: Message-ID: Oliver Eichler wrote: > Hi > > I am using the bdb module wrapped by my own script to step thru a python > script. Within the debugged script I have some textual printout to stdout. > Is it possible to redirect the stdout stream e.g. to a socket? > > Oliver Never mind, it's easy :) sys.stdout = sock.makefile("w") I guess... Python is to easy for me :) Oliver From claird at starbase.neosoft.com Tue Jul 9 14:31:58 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 9 Jul 2002 13:31:58 -0500 Subject: python & web services References: <6pNV8.24555$2w.1181063@news20.bellglobal.com> Message-ID: In article <6pNV8.24555$2w.1181063 at news20.bellglobal.com>, John wrote: >What is currently available for the development of web services in python? >Does Zope provide a complete solution? (I am new to both and plan to learn >them together) . . . People mean a WIDE range of different things by "Web services". It'll help a lot if you describe first what you intend by this phrase. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From aleax at aleax.it Sun Jul 21 05:03:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Jul 2002 09:03:28 GMT Subject: getting date into rfc822 format References: <6Mq_8.6690$Ga1.1849904@news1.news.adelphia.net> Message-ID: Jon J. Morin wrote: > Hi all. I'm writing a program that sends email in an environment that ... > date = time.ctime(time.time()) > > Which gives me a date like this: > Sat Jul 20 00:02:03 2002 > > When what I want is something like this: > Fri, 01 Mar 2002 00:18:17 -0500 (EST) Well, you're almost 5 months late for the latter. However: >>> import email >>> email.Utils.formatdate() 'Sun, 21 Jul 2002 09:00:38 -0000' >>> import time >>> email.Utils.formatdate(time.time()-3600*24) 'Sat, 20 Jul 2002 09:01:01 -0000' >>> and if you insist on using your local timezone rather than UTC: >>> email.Utils.formatdate(localtime=True) 'Sun, 21 Jul 2002 11:01:58 +0200' >>> That's what the +0200 &c is by RFC 2822, btw -- offset of your local timezone from UTC, positive in most of Europe, Asia, and Africa, negative in the Americas. Alex From andreas at kostyrka.priv.at Sat Jul 27 05:54:32 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 27 Jul 2002 11:54:32 +0200 Subject: how to count lines in a file ? In-Reply-To: References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> Message-ID: <1027761473.8774.242.camel@vaio2> Am Sam, 2002-07-27 um 05.44 schrieb Steve Holden: So, what you *seem* to be saying is that it would be p[erfectly possible to > collect objects thatdon't have __del__() methods, but once they acquire such > they are no longer collectible even when only cyclic references exist? That > seems an odd asserion. Nope. Consider: class A: def close(self): self.child.close() def __del__(self): self.close() a=A() b=A() a.child=b b.child=a Now we have a basic cyclic reference. Please explain to me, if a or b should be deleted first? Basically, if you do have __del__ methods, these might try to do something with the __dict__ values or slots. Now, without __del__, this works quite well, because we just free the memory, and that was it. > Well, certainly you *always* have to be careful that references haven't been > invalidated before use. But thats the problem. Python being dynamic, you cannot even try to sort the deletion because we cannot be sure about what __del__ does before we try to execute it. (eval&exec are our friends[enemies] here) And there cases that are unsolvable (because a depends upon b for deletion and vica-versa). So Python doesn't try. > > > It's a sort of philosophical thing. If you can be sure that having closed > > the door, no-one will open it again then the room on the other side is > > allowed to simply disappear ;-) > > > > __del__ only has sensible semantics in the presence of reference counting. > > Either have reference counting or throw away __del__. When it comes down > to > > it you gotta pick one or the other. > > > I'm afraid you're going to have to explain that one. I don't think there is > any great philosophical difference bvetween ourpositions, but I'm not yuet Well, it's actually trivial. The execution environment of finalization in "true" garbage collection are usually to random to be of any use, except perhaps unconditional release of external resources (but this doesn't happen usually at the Python level, this is more a thing for C language level interface modules). This is so, because no GC algorithm (except reference counting) gives you any order of deallocation. (basically they are random) Consider an object a that is registered with another one [m]. Now one might propose that a deregisters from m in it's finalization. But with true garbage collection a cannot be sure, that m still exists. Basically, because the system state during collection is in a flux, the possible failure modes for finalization functions multiple quite fast. Now there uses for finalization with GC, but they usually do not apply to python (because python do not contain things like unprotected references, etc., and the whole interfacing with non-gc libraries is done in C). > completely sure I understand what you are saying. As the Reverend Sydney > Smith observed upon seeing two women shouting at each other from opposite > windows: "I fear they will never agree, for they are arguing from different > premises". Andreas From bokr at oz.net Fri Jul 26 15:08:58 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Jul 2002 19:08:58 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: On Wed, 24 Jul 2002 14:12:39 +0200, =?ISO-8859-1?Q?Walter_D=F6rwald?= wrote: >Alex Martelli wrote: > >> [...] >> ...would you please share your uses for metaclasses? I can use >> all the good examples I learn about -- it's hard to teach people >> how to use metaclasses without actual motivation, and the more >> real-life examples I can collect and quote, the more likely I >> can help people achieve that motivation! > >The upcoming release of XIST (http://www.livinglogic.de/Python/xist/) >has several uses of metaclasses (see >http://www.livinglogic.de/viewcvs/index.cgi/LivingLogic/xist/_xist/xsc.py?rev=2.117.2.25&content-type=text/vnd.viewcvs-markup >for the source code. > >The first example is a customized repr for nested classes, >that shows the class nesting: > First, thank you for showing an example with __metaclass__ not bound to a class defined outside. ISTM this way of doing things should be shown to be an alternative to the __metaclass__ = MCxxx pattern of defining an outside metaclass and binding to it. It would be a good addition to decrintro.html. (Of course that brings up the question of whether there are pros and cons associated with the two ways, other than being able to reuse the same metaclass). There appears to have been a little glitch in cutting and pasting, but after the change, it worked for me as advertised. >class Base(object): > class __metaclass__(type): > def __new__(cls, name, bases, dict): > dict["__outerclass__"] = None > res = type.__new__(cls, name, bases, dict) > for (key, value) in dict.items(): > if isinstance(value, type): > value.__outerclass__ = res > return res > > def __repr__(self): > return "" % (self.__module__, >self.__fullname__(), id(self)) ^--( line obviously wrapped ) > > def __fullname__(cls): > name = cls.__name__ ---[ needs a dedent >------------------- > while 1: > cls = cls.__outerclass__ > if cls is None: > return name > name = cls.__name__ + "." + name ---< needs a dedent ]------------------- > __fullname__ = classmethod(__fullname__) > [...] Now I can play with this pattern. Thanks ;-) Regards, Bengt Richter From aleax at aleax.it Wed Jul 24 11:50:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 15:50:16 GMT Subject: how to count lines in a file ? References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: Shagshag13 wrote: ... > this : > for line in open(filename): > count += 1 > > or this : > fhi = file(filename) > while 1: > lines = fhi.readlines(bufferSize) > if not lines: > break > lineCount += len(lines) Two clear and obvious lines or six complicated and mysterious ones? Hmmm, a hard question indeed. BTW, GvR claimed (less than a month ago on the python-dev list) that having an integer argument to readlines was a design error. So, two clear and obvious lines using the language release that has been current for the last 7 months, or six complicated and mysterious ones using what the language designer now considers a design error? The choice is becoming harder and harder... Alex From marklists at mceahern.com Fri Jul 12 08:18:54 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 07:18:54 -0500 Subject: try..catch..finally? In-Reply-To: Message-ID: [Michael Hudson] > Yeah, just get used to functions that start > > try: > try: > try: perhaps we can call that "The Little Engine That Could" construct? // m - From deltapigz at telocity.com Mon Jul 1 23:25:38 2002 From: deltapigz at telocity.com (Adonis) Date: Mon, 1 Jul 2002 23:25:38 -0400 Subject: somewhat off-topic Message-ID: <3d211d32$1_5@nopics.sjc> i wrote a http server using SimpleHTTPServer, im using the GET command as my cgi trigger, and would like to "hide" the path? i.e. i get a: GET /login?user=foo&pass=bar client side (on their url box they see) http://host/login?user=foobar&pass=bar i want them to just see: http://host/login or just http://host/ since login is really mapped to a class. i know it has to do something with headers, but have failed to find it on google. any help would greatly be appreciated. Adonis From Pekka.Pessi at nokia.com Tue Jul 30 19:02:10 2002 From: Pekka.Pessi at nokia.com (Pekka Pessi) Date: 31 Jul 2002 02:02:10 +0300 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: >Is there a way to do that? I tried putting > def __call__(x): ... >into foo.py but that didn't work. There is no magic in a __call__ attribute. Python language reference does not promise you anything about it. For example, >>> class O(object): ... pass ... >>> o = O() >>> o.__call__ = lambda x: x * x >>> o(1) Traceback (most recent call last): File "", line 1, in ? TypeError: 'O' object is not callable However, the __call__ method is special: >>> class O2(object): ... def __call__(self, x): ... return x * x ... >>> o2 = O2() >>> o2(2) 4 The function __call__ you added to the module is an attribute, not a method, so it does not have any magic. (The __call__ attribute does work on instances, but I think it is considered as a bug.) >>> class I: ... pass ... >>> i = I() >>> i.__call__ = lambda x: x * x >>> i(2) 1 Now, back to your question. You can have a callable module, no problem: >>> import types >>> class module(types.ModuleType): ... def __call__(self, x): return x * x ... >>> module()(2) 4 If you want to call the __call__ attribute, that is a no-brainer, too: >>> class module(types.ModuleType): ... def __call__(self, *x, **kw): ... try: ... func = getattr(self, "__call__") ... return apply(func, x, kw) ... except AttributeError: ... raise TypeError("'%s' module is not callable." % (self.__name__,)) ... >>> m = module() >>> m.__call__ = lambda x: x * x >>> m(2) 4 You can propably find out rest of the gory details by looking around in imp and knee modules. >If there's not a way to do this already, maybe it's a reasonable >addition. Guido disagrees, I'm afraid. I have asked twice, and got nixed twice. Pekka From pecora at anvil.nrl.navy.mil Fri Jul 12 11:04:59 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Fri, 12 Jul 2002 11:04:59 -0400 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> <3D2E8F10.B9B4EFD2@alcyone.com> <3D2E91ED.B061D0EB@engcorp.com> <3D2EA00F.582923B3@alcyone.com> <3D2EDC81.15FDD23F@engcorp.com> Message-ID: <120720021104599515%pecora@anvil.nrl.navy.mil> In article <3D2EDC81.15FDD23F at engcorp.com>, Peter Hansen wrote: > Louis' comment that I ought to just develope (sic) my own ^^^^^^^^ Verbatim from the original. :-) -- Lou Pecora - My views are my own. From gerhard.haering at gmx.de Wed Jul 10 07:46:08 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: 10 Jul 2002 11:46:08 GMT Subject: [Ann] SimpleParse 2.0.0a2 available References: Message-ID: In article , Mike C. Fletcher wrote: > URL: > http://simpleparse.sf.net/ What am I doing wrong if almost all the parsers I try creating with SimpleParse 1.0 get in an infite loop when it tries to compile them? I'm asking because I'd really like to use it - I really like the syntax for its rules. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From pinard at iro.umontreal.ca Mon Jul 8 08:05:39 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 08 Jul 2002 08:05:39 -0400 Subject: `~/.pythonrc' `from __future__ import' In-Reply-To: References: Message-ID: [Tim Peters] > > How should I proceed to activate this [future division] ]option once > > and for all for interactive applications? > You can write an alias to start interactive sessions by passing -Qnew to > Python. I've heard about this undocumented feature indeed, and hoped to go without resorting to it. Moreover, this option only works for division, it does not apparently activate generators, for instance. I would rather have all future features available all the time when I write interactively, yet I guess why some people would prefer not. > The PYTHONSTARTUP file acts as if executed via the execfile() function. > That implies it can leave behind visible bindings in the caller's > globals, and have other non-local side effects (such as importing other > modules), but like all exec and eval gimmicks, it executes in a code > block distinct from its caller's. It's a separately compiled unit, > and a future statement's useful effects are limited to the compilation > unit in which it appears. In effect, that means it only "works" for > the code in the startup file itself. I understand and, Tim, I thank you for your patient explanations, However, it wonder if this is all fully right. The actual documentation and the PEP say that one could `import __future__' explicitly, so to check at run time what features are currently available in the running Python. Besides its compile-time effect, `from __future__ import division' (say) dynamically defines `division' at run-time in the global space, at least when done from the startup file, but this is no strong clue about if the feature has been activated or not (at least when the Python version lies between the introduction version and, excluded, the mandatory version). Would it mean that one has no other choice than "benchmark" the feature at run-time, the ugly way, to know whether it is active or not? The current intent is to let an `from __future__ import FEATURE' generate an error if the FEATURE is wanted in a module, but not available in the current Python. Suppose, for example, that I write a module in which some function makes good use of some future feature (it could be the `yield, statement), but I want to provide an alternate implementation of that function which is less interesting (because it gets much complex and slower) in case the feature is not available. Since I cannot except out of the `from __future__ import' statement, for reasons I understand, I do not see how I take good advantage of available future features, in a program meant to be portable between versions. Maybe the future statement is rougher than I expected? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From tim.one at comcast.net Fri Jul 12 04:22:31 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Jul 2002 04:22:31 -0400 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: [Miki Tebeka] > Although it's in the Humor section I take the Python Zen > (http://www.python.org/doc/Humor.html#zen) quite seriously. > > However I can understand what does “Sparse is better than > dense” means. > > Any Ideas (Tim?) The value of an aphorism is in provoking you to ponder. So long as you suspect there's something of value in it that you don't yet understand, it's doing its job. As soon as someone thinks they understand it, and then just repeats it (whether to endorse or ridicule doesn't much matter) in lieu of contemplation, its usefulness is exhausted. I suspect that's why God always arranges to get himself killed whenever he takes on human form . I've read that if you confine too many rats in too small a living space, they become sociopathic. That's density for you. I've seen no reason to suspect that code, concepts, data structures, interfaces, programmers or managers have an advantage over rats in this respect. Give yourself some room to breathe and stretch: couple interfaces loosely, let a subsystem deal with a little rather than a lot, leave a little whitespace for flowers to grow between tokens, fail soft on feathers instead of hard on rocks, don't do two things at a time until you're pretty sure you can do one, a function with 14 arguments-- or a module with 14 classes --is a bad idea, don't fall for the idea that between any two abstractions you always need to compromise on a third. Etc. In other words, sparse is better than dense. Except when it comes to chip design, where sparseness plain sucks . pythons-swallow-rats-one-at-a-time-ly y'rs - tim From gerhard.haering at gmx.de Mon Jul 8 04:51:22 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 8 Jul 2002 10:51:22 +0200 Subject: the meaning of life In-Reply-To: <3eeda89d.0207071133.4c07a86e@posting.google.com> References: <3eeda89d.0207071133.4c07a86e@posting.google.com> Message-ID: <20020708085122.GA8564@lilith.my-fqdn.de> Somebody whos parents couldn't think of any better name than "Thinkit": > Take a break from python and realize the meaning of ALL conscious beings. Wow! You just discovered the meaning of life!!!!11. You should get a noble prize. I just can't think of any suitable category. > [...] *PLONK* Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 22.2 ?C Wind: 2.1 m/s From mwh at python.net Fri Jul 26 06:04:26 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 10:04:26 GMT Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <16Q%8.116512$Jj7.2728704@news1.tin.it> Message-ID: Alex Martelli writes: > Jonathan Hogg wrote: > ... > >> I prefer simplicity. "Do the simplest thing that can possibly work". > >> As you're showing, __call__ encourages tossing simplicity away. > > > > Hah. You've got me there :-) > > > > Yes, I believe in adding infrastructure that I know > > the-day-after-tomorrow, I'll be glad I did ;-) > > Bingo. I had much the same approach for the first 20 years > or so of my programming career, Then I'm ahead of you by ... erm ... 13 years. Wow, I've been programming (admittedly only as a hobbyist) for nearly a third of my life. That's scary somehow. Cheers, M. -- >> REVIEW OF THE YEAR, 2000 << It was shit. Give us another one. -- NTK Know, 2000-12-29, http://www.ntk.net/ From fperez528 at yahoo.com Sat Jul 27 14:29:38 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 27 Jul 2002 12:29:38 -0600 Subject: Python Cookbook (was: extract elements of n char from a list) References: Message-ID: <3D42E692.5090505@yahoo.com> > The book looks very nice, btw. Good job, > > > I just got the Cookbook yesterday, and it *does* look good! I believe we > can primarily thank Alex Martelli for that -- from what I saw, he put an > enormous amount of work into organizing, cleaning and improving the content. > In fact, I wouldn't be suprised to learn that he wrote all the chapter > intros too . Well, I'd like to make a few comments on it. First, It kept me up last night until 3am, so you guys owe me a few hours of sleep :) Overall, I think you all did a _fantastic_ job. I highly recommend this to anyone wanting to learn not just about python solutions, but in general about intelligent ways of solving real-life problems in various areas of computing. This isn't a review, since I only paged through it (cover to cover though). But a few points struck me as I was reading: 1. Even though it has many authors for the recipes, the book managed to remain very cohesive in tone and style. You can feel enough differences to hear the 'community voices', but not to the point of being distracted by them. Maintaining that balance was IMHO a tough act to pull off, and I think the editors succeeded admirably. 2. In a past life I kept the Perl cookbook semi-permanently on my desk, so I was drawn to making a mental parallel between the two. Without wanting to disparage the Perl CB (which is a remarkable piece of work), I was struck by a fundamental difference between the two. My main use of the Perl CB was for situations of the type 'I know _logically_ how to do what I want, but how can I manage to get this $@%#{}~ language to do it?' (for the perl non-initiated, that was not an expletive but simply a short sample of the most commonly used characters in the language ;). For example, often needing complicated nested structures (e.g. hashes of hashes of arrays), I constantly needed to look up the deeply quirky syntax needed to keep track of such things, since it's subtle enough that you make mistakes unless you use it every day. That gets old quick. With python, that problem never arises, and the book reflects it. Instead of being devoted to reminding you how to do things you should be able to do without a book, it's mostly a discussion of the type 'here's a common problem for which naive solutions can have subtle pitfalls, and here are various ways to tackle it with real intelligence and power'. And python being such a clear language, it is a perfect one to express the ideas just discussed in a concrete implementation. So in a sense I'd argue that the python CB reads almost more like an algorithms/computer science book than a 'python' book. It so happens that the ideas discussed are illustrated in python. To me that is a huge virtue (the power of generality) and a great testament to the quality of python as a language. Of course I'm not arguing that it's going to replace Knuth's series any time soon ;). But it was refreshing to me to read often a discussion of the various approaches in terms of their asymptotics and even of the balance of the fixed additive or multiplicative constants involved. I felt like I was not just learning python, but simply learning. That's good: a nice balance of (reasonably) 'deep thought' and practicality. 3. Here and there I found recipes that to some extent could qualify as workarounds for quirks in either the language or the library. While that's great to have, it would probably be nice to keep a list of such things as candidates for enhancements (especially the library ones, which are far less sensitive and controversial than language changes). One that jumps to mind is recipe 4.17, p.143 on how to write a mkdirs function which doesn't crash on pre-existing directories. That's the kind of thing for which adding a keyword argument to the existing functions can be a great solution. I think of keyword arguments like command line switches on the shell, as a way of extending the life and usefulness of functions without disrupting their core interface. One could for example add a 'quiet=None' option which if set to true would make os.makedirs() behave like the proposed mkdirs(). Just a random idea... So I think the book could be a nice base for a check list of things that sometimes require less than elegant solutions, and for which a fix is easy and non-disruptive. I know that core language changes are in a different league, but often small improvements to functions can make people's life easier without any significant drawbacks. At any rate, congratulations to all the authors, and a big applause to the editors. I highly recommend this book to the python crowds (and even to seasoned programmers in other languages, who will probably be seduced by the clarity with which python can express often subtle and powerful solutions). Cheers, f. From peter at engcorp.com Tue Jul 16 07:57:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Jul 2002 07:57:45 -0400 Subject: Newbie: Capture output of compile_dir References: Message-ID: <3D340A39.2514C3BE@engcorp.com> "Denis S. Otkidach" wrote: > > Informational messages from compile_dir go to stdout and error > messages go to stderr. You should redefine both. > > orig_so = sys.stdout > orig_se = sys.stderr > sys.stdout = sys.stderr = captured = StringIO() > ... By the way, "sys" has _stdout and _stderr already, which I believe point to the originals, so I believe you don't need to preserve these in your own locals unless you're expecting to have to nest these sorts of redirections. -Peter From thefogger at web.de Tue Jul 16 11:33:20 2002 From: thefogger at web.de (Jan Felix Reuter) Date: Tue, 16 Jul 2002 17:33:20 +0200 Subject: Session ID & Security Message-ID: Hi, I'm developing / already have some CGI scripts written in Python. Now I want to implement Session Management & User Authentication, which is a new area for me. I already have a simple session ID system in place. It doesn't do much more than assining a random number as an ID and placeing it in a Cookie on the client. If the client already has a cookie in place the CGI will leave it as it is and get some data from a shelve based on that ID. (Thanks to Ian Bicking who told me that earlier) Now I'm concerned about security, because with this sheme an attacker could easily get access to a user's session by just guessing its ID. After some research I found out about Message Authentication Codes and the hmac python module. How does one use it? Do I apply the algorithm to every message (cgi output?) and place the hash in another cookie or appended to the session ID string? So, if the client sends back a hash that differs from the last hash the server has send, the session is discarded, is that how you do it? Hashing all the output seems a bit overkill to me. Wouldn't a simple random number suffice? I get the feeling that I misunderstood the whole MAC thing. Yadda, yadda. Felix From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 17:11:42 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 22 Jul 2002 14:11:42 -0700 Subject: Python very slow on the Sharp Zaurus - any idea why? References: Message-ID: <7xfzybii29.fsf@ruckus.brouhaha.com> Tim Peters writes: > Python used to use float arithmetic to detect int mult overflow, but that > didn't work correctly on some 64-bit boxes. > > It got replaced by over 100(!) lines of all-integer int mult > overflow-checking code, and I believe that's still in 2.1.3. > > But that had an obscure endcase bug too, and it get replaced in 2.2 by a new > float method that doesn't make unwarranted assumptions about the relative > sizes of C longs and C doubles, and usually gets out quickly -- provided > float arithmetic isn't pig slow. Ouch!! That doesn't sound so good for the Zaurus. Is the idea here to discover if a*b overflows 32 bits, if a and b are 32 bit ints? On compilers supporting 64-bit (long long) ints, it may be faster to use them instead of floating point for this check. I think that includes GCC and current Microsoft compilers among others. It may even be ok to synthesize 32-bit multiplication from several 16-bit multiplications, to avoid these overflows. From skip at pobox.com Tue Jul 23 10:38:11 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Jul 2002 09:38:11 -0500 Subject: Queue.Queue examples? In-Reply-To: <3D3D66CF.9060603@icqmail.com> References: <3D3D66CF.9060603@icqmail.com> Message-ID: <15677.27219.119985.991705@12-248-11-90.client.attbi.com> Dave> despite having read the manual, i'm still totally ignorant on the Dave> basic concept of Queue and how can it be used to safely pass Dave> objects between two (or more) threads. could someone enlighten me? Suppose you have a Queue object: q = Queue.Queue() In one thread you can execute: q.put(someobj) In another thread you can execute: someobj = q.get() -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From mcherm at destiny.com Tue Jul 23 09:02:37 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 23 Jul 2002 09:02:37 -0400 Subject: good books Message-ID: <3D3D53ED.7040602@destiny.com> >> what is a good book in python, If i can only afford to buy just one book? > > IMO Python 2.1 Bible, www.hungryminds.com > I'd second that. At my last python confrence I spent a bit of time looking over various books on the table, and picked it over several others which had been recommended to me simply because when I skimmed chapters it seemed so GOOD. However, it's probably not the best single book if you're a beginner. -- Michael Chermside From robin at stop.spam.alldunn.com Fri Jul 26 17:13:25 2002 From: robin at stop.spam.alldunn.com (Robin Dunn) Date: Fri, 26 Jul 2002 21:13:25 GMT Subject: [Q] wxPython - layout & placement References: Message-ID: "Rolf Marvin B?e Lindgren" wrote in message news:lbzznwnpu98.fsf at aqualene.uio.no... > I'm trying to place a button in a dialog window. this works: > > > but I'd like to use layout controls. I've figured out how to do it > with wxPanel, but wxDialog doesn't seem to work the same way. Automatic layout happens during the default EVT_SIZE handler for windows, but on Windows the wxDialog does not get a size event when shown like wxFrames do. So if there is no size event then there will be no autolayout. You can usually get around this by calling self.Layout() at the end of your dialog's __init__. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From marklists at mceahern.com Thu Jul 11 10:59:30 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 11 Jul 2002 09:59:30 -0500 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <3CgX8.68516$vm5.2504519@news2.tin.it> Message-ID: [Alex Martelli] > It definitely doesn't make any difference to the compiler, but > it makes a huge difference to ME, as a human reader of the code, > to avoid wasting a line and thus fitting more lines onto a screen. > > This is particularly important with small screens, such as the > Sharp Zaurus' 300x200 screen or thereabous, but even on large > screens it lets me use a larger and thus more readable font for > any given amount of lines that I need to see at once on-screen. I hadn't thought of different screen sizes. That's a good point. > Personally, I have no difficulty whatsoever "visually scanning" > these constructs -- the lack of any indented line under the keyword > stands out and quite effortlessly makes my eyes glide rightwards. The advantage I find in using two lines for for these constructs is that I don't have to parse the keyword and notice the lack of an indented line. I speculate that the contour of indentation is easier to see "at a distance" and can be done without having to see/parse the individual keywords. Of course, the other explanation for my sentiments is that I'm just stubborn and I haven't really tried to cultivate an appreciation for this other approach. I remember having a strong dislike for using underscores in identifiers, but I've gotten used to that. > I MUCH prefer to use entirely blank lines for separation of > _semantically *meaningful* blocks_ of code, rather than breaking > every compound statement into more lines than needed, most > particularly when such a compound statement corresponds to > a single "compound thought". Yes, I'm a fan of using blank lines to separate chunks. I hadn't thought of applying that to the short compound statements. I appreciate your example: > style B: > > while True: > prelim_one() > X = prelim_two() > Y = another_thing(X) > > if X > Y: break > > yet_another(X, Y) > prepare_next(X+Y) > > > Style B forgoes the wanton linebreak at the 'if' and invests > that line (plus another presumably saved elsewhere by using > no wanton breaks:-) to make the loop's exit condition stand > out much better. > I suspect we'll have (at best) to agree to disagree on the > specifics of this. Well, I'm glad I piped up--I received the unexpected gift of a well articulated view counter to my own. Thanks! Cheers, // mark p.s. Anecdotally, I was looking at the source for a Python C extension early this morning and it had what seemed like completely inconsistent indentation. // all of these styles appeared in the same file... for (...) { statements } if (...) { statements } if (...) { statements } I didn't investigate, but this may have been at least partially due to weird voodoo in my .emacs file--but I doubt it. So I think I was even more sensitive than usual to the joy of Python's enforced indentation rules. - From claird at starbase.neosoft.com Fri Jul 12 09:27:21 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 12 Jul 2002 08:27:21 -0500 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <4E3460539B64F648.0AAA94C8E4F0F752.085B12876729F7A3@lp.airnews.net> In article , Matt Gerrans wrote: >> XML combines all the inefficiency of text-based formats with most of the >> unreadability of binary formats :-) > >Maybe it was surreptitiously introduced by a consortium of router and disk >drive manufacturers, to ensure increasing sales of hardware, by its >voracious appetite for bandwidth and disk space. ;-) > > CORBA people *know* this is true. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From tim_one at email.msn.com Wed Jul 10 00:02:36 2002 From: tim_one at email.msn.com (Tim Peters) Date: Wed, 10 Jul 2002 00:02:36 -0400 Subject: File size error in os.stat with large files. In-Reply-To: <15659.23994.749181.970029@gargle.gargle.HOWL> Message-ID: [someone] > You have to compile python with large file support to handle files > over 2GB. To test whether you have this enabled: [Matt Gerrans] > Do you know why the binaries are not compiled with large file > support as default? [Skip Montanaro] > I suspect it allows the same binaries to run on a larger number of Windows > versions. "Even Win95" supports 64-bit file sizes and offsets via the Win32 API, which has long supported them (albeit that Win95 didn't support any filesystem capable of storing such large files)! That's not the problem, and there's no compile trick you can use in Python 2.1 or earlier to get large files to "work right" under any flavor of Windows. Those versions of Python used "the usual" assortment of C functions under Windows, and Microsoft's implementations of those just plain don't work for large files. All the relevant Windows file code in Python was rewritten for 2.2, to use crankier functions that do work with large files (and on any Win32 box). The only cures are to move to Python 2.2.1 (then it just works out of the box), or eschew portable Python file operations and code to the Win32 API by hand. "large-file-support"-means-something-different-on-every-platform- and-counting-unix-as-a-dozen-distinct-platforms-ly y'rs - tim From paddy3118 at tiscali.co.uk Sat Jul 27 07:36:03 2002 From: paddy3118 at tiscali.co.uk (Paddy) Date: Sat, 27 Jul 2002 12:36:03 +0100 Subject: Two dimensional regexp matching? Message-ID: <3D4285A3.80407@tiscali.co.uk> We already have the re module for regular expression matching on a string. I am looking for pointers to references/algorithms for regular expression matching for files of tabular data, i.e. Table definition ================ 1) Samples from one point in the system appears in a column of the table. 2) Samples encoded as characters 3) All points in the system are sampled at the same time to produce successive rows of the table So a system sampled at two points in successively may produce the following file: GH DF AS QW FF SD I want to be able to do regular expression type searches within the file. Things like Where can I find point1 == (D or G) then point2 == W within three samples and where the next sample of point2 != the earlier sample of point1? That was a small example, in reality there is usually hundreds of points and tens of thousands of samples in multi-megabyte files but I'd first like to see if anyone else has considered this kind of 'two dimensional regexp matching' Note: I DO NOT have queries in the date on sample points. The queries will always be "Find the range of sample times in which 'this' occurs". U have tried Google but without success - I don't know enough to think of a suitable search phrase, or, (much less likely), Google doesn't have it ;-) Thanks in advance, Paddy. From sholden at holdenweb.com Thu Jul 25 10:56:28 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 25 Jul 2002 10:56:28 -0400 Subject: asyncore: limiting number of simultaneous connections? References: Message-ID: <5kU%8.45583$xo1.33957@atlpnn01.usenetserver.com> "Alex Martelli" wrote in message news:JcU%8.139488$vm5.4529193 at news2.tin.it... > Steve Holden wrote: > ... > > which a read condition is accepted. Any time the socket is so listed (in > > the select.select() arguments) any number of simultaneous connections > > might occur, though this is unlikely. > > Hmmm... ANY number? Doesn't the N passed in socket.listen(N) provide > an upper limit to the number of connection requests that may be at > the same time outstanding? > OK, then "... any number of simultaneous connections allowed by the socket ..." Technically, yes, the N passed to socket.listen() specifies the number of unanswered (queued) connection requests that the transport layer will allow for the socket. We should also remember that usually the transport layer itself will impose some upper limit on N. ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From alf at orion.logilab.fr Mon Jul 15 05:24:46 2002 From: alf at orion.logilab.fr (Alexandre Fayolle) Date: Mon, 15 Jul 2002 09:24:46 +0000 (UTC) Subject: 8 Queens Problem References: Message-ID: Dans l'article , Alex Martelli a ?crit : > One way to think about the problem: you want all permutations of range(0,8) > that satisfy certain constraints. The "permutations of range(0,8)" part is > about having 8 queens on the board, never two on the same row or column; > the "certain constraints" are about never having two queens in the same > diagonal either. Omitting the "certain constraints" would clearly solve > the "8 rooks problems", for example. And this is the whole point of the constraint propagation system I'm working on as part of the logic-sig. http://www.logilab.org/python-logic/constraint.html Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From mwh at python.net Thu Jul 18 05:45:03 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Jul 2002 09:45:03 GMT Subject: map del efficiency python2.2 and 2.1 References: Message-ID: Michael Hudson writes: > John Hunter writes: > > > Now where do I go to get a deep understanding of my platform's (glibc > > 2.2.2) implementation of free and why it behaves so badly? > > I believe 2.3 will be better here. Not a lot of help, no... By this I meant glibc 2.3! Python 2.3 will also be better, but for a different reason. Cheers, M. -- I'm a keen cyclist and I stop at red lights. Those who don't need hitting with a great big slapping machine. -- Colin Davidson, cam.misc From skip at pobox.com Tue Jul 23 07:16:52 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Jul 2002 06:16:52 -0500 Subject: Mastering Regular Expressions 2nd Ed. In-Reply-To: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> Message-ID: <15677.15140.974805.322468@12-248-11-90.client.attbi.com> Tim> The multi-thousand byte full expression to match a valid RFC822 Tim> e-mail address was practically worth the price all by itself! And then they released RFC 2822 and made the book obsolete. How inconsiderate. S From tweedgeezer at hotmail.com Sat Jul 20 02:12:13 2002 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 19 Jul 2002 23:12:13 -0700 Subject: Renting CPU time for a Python script References: <25c15ddd.0207190852.2aecc26c@posting.google.com> Message-ID: <698f09f8.0207192212.76272194@posting.google.com> Fernando P?rez wrote in message news:... > 1- code in automatic checkpointing and self-restarting abilities. It's fairly > easy to do, and saves a lot of headaches. Do you know of any examples of this in available code, or could you outline how you would implement something like that? I have a project right now that such a capability would come quite useful in, but rather than hazard my own implementation right off, I'd like to try and leverage some other efforts. Thanks, Jeremy From K.Rdt at TU-Berlin.DE Tue Jul 2 02:22:06 2002 From: K.Rdt at TU-Berlin.DE (Klaus Reinhardt) Date: Tue, 02 Jul 2002 08:22:06 +0200 Subject: Python language dedicated Wiki In-Reply-To: Message-ID: Am 01.07.02 22:04:41, schrieb "David LeBlanc" : >I've always thought it would be a nice idea to put PythonDoc into a wiki, >not only on a website, but also as part of the distribution. --------------------------------------------------------------------- Hi What does mean Wiki; no acronym found. K at Rdt --------------------------------------------------------------------- From aleax at aleax.it Tue Jul 9 09:53:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 13:53:55 GMT Subject: sorting many arrays from one... References: Message-ID: Shagshag13 wrote: > > "Alex Martelli" a ?crit dans le message de news: > nYAW8.59639$vm5.2174555 at news2.tin.it... > >> aux_list = zip(drive, other1, other2, other3) >> aux_list.sort() >> >> for i in range(len(drive)): >> drive[i], other1[i], other2[i], other3[i] = aux_list[i] >> > > thanks ! it's quite impressive and even works with array (i didn't even > knew this "zip" built-in function nor thought that sorting was possible on > tuples). I think that if you don't use "map" to replace the "for loop", > it's because it's impossible, so i don't need to try ;o) No, as Duncan just showed in another post -- you can just use zip the other way 'round (zip(*aux_list)) to give the right sequences again (though you then also need map or a list comprehension to make the tuples into lists). I had just coded this in the simplest way that came to mind, without any special effort to do clever things (and that zip is in a sense its own inverse IS pretty clever indeed:-). > i have another question, i need a way to have a one to one mapping from > string to integer to save storage : in fact having an id key associated > with strings (like in a database). I'm not sure how that would save you any storage at all. Since the strings DO need to be stored somewhere anyway, what's saved by using their id's rather than just references to them, as Python usually does? I don't think you're saving any storage at all with all the code below. Why not just try using a simple dictionary vs this approach (with some HUGE number of keys to make sure) and use platform dependent ways, e.g. program 'top' under Linux, to check VM usage in either case? > and again great thanks for all your advices / replies... You're welcome! Alex From Jonas at localhost.localdomain Tue Jul 2 11:42:27 2002 From: Jonas at localhost.localdomain (Jonas Geiregat) Date: Tue, 02 Jul 2002 17:42:27 +0200 Subject: python newsgroup server Message-ID: is there a special server hosted by python.org a python news server ? From lac at strakt.com Mon Jul 22 06:11:29 2002 From: lac at strakt.com (Laura Creighton) Date: Mon, 22 Jul 2002 12:11:29 +0200 Subject: Alex Martelli is off the net for a few days :-( Message-ID: <200207221011.g6MABTVa009663@ratthing-b246.strakt.com> Some construction workers have severed his phone and internet lines. Expect him back in a few days, not a few hours. :-( Laura Creighton From martin at v.loewis.de Thu Jul 11 03:00:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Jul 2002 09:00:27 +0200 Subject: How to replace multiple-line text References: <3D2D0782.45FCEC98@bellatlantic.net> Message-ID: David Lees writes: > I would like to process a code file and substitute one multiline block > of code for another. I know how to do this in Python by brute force > scanning through on a line by line basis until the first line of the > pattern is found then looping over the rest of the lines in the target > pattern for a match, then substituting in an output string multiline > substitution. But I am sure there is a neater solution, perhaps using > regular expressions. Could someone point me towards sample code or > something similar that I could modify. Regular expressions might work, as might plain list slicing. You will need to describe the properties of this replace process in more detail to get good advise. In plain English, please describe: - how would you recognize (by visual inspection) that the multiline block starts? - how do you recognize that it ends? - how does the block you want to insert depend on the block you want to remove? Regards, Martin From Chris.Barker at noaa.gov Thu Jul 18 12:35:30 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 18 Jul 2002 09:35:30 -0700 Subject: python2 import trouble (linux - redhat) References: <20020714141757.128895ce.mmellor1@yahoo.com> <3D35A628.A9ADF9B6@noaa.gov> <1026930878.3325.1.camel@jwilhelm.ofsloans.com> Message-ID: <3D36EE51.4CC0E9CD@noaa.gov> Dave Reed wrote: > In the beta (limbo) The first line of > > /usr/share/printconf/util/printconf_gui.py > > is > > #!/usr/bin/python > > so it looks to me like the same problem will occur. AARRGGG!!! Perhaps we need to organise a mass mailing to RedHat to try to get them to change this before it is too late. It can't be hard for the Linux gurus at RedHat to figure out a way to replace all occurances of "#!/usr/bin/python" with "#!/usr/bin/python2.2" in the entire system. Does anyone know an appropriate contact at RedHat that we could mass mail to? -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From fredrik at pythonware.com Sat Jul 13 12:22:02 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 16:22:02 GMT Subject: Tkinter Menu command References: Message-ID: Raimo Tuisku wrote: > Is it possible to pass arguments to a method which is executed after > event? I am trying to do so with add_command method from Menu > widget to avoid writing separate method for every case. > #From class App: > self.mb = Menubutton(self.frame, text="Color") > self.mb.grid() > self.mb.menu = Menu(self.mb,tearoff=0) > self.mb['menu'] = self.mb.menu > self.colors=['red','green','blue'] > for item in self.colors: > self.mb.menu.add_command > (label=item,command=lambda :self.set_color(item)) > # Even this doesn't work. Apparently it always uses > # self.set_color('blue'). (self.label colors to blue) for item in self.colors: self.mb.menu.add_command (label=item,command=lambda :self.set_color(item)) when the lambda is called, its body will pick up the *current* value of the "item" variable. (it's a reference to something that lives in another namespace, not a reference to its value) to get the value it had when you created the lambda, you need to use explicit name binding: self.mb.menu.add_command( label=item, command=lambda item=item:self.set_color(item) ) From bbeck at REMOVE-THIS-TO-EMAIL-ME.austin.rr.com Tue Jul 2 23:23:19 2002 From: bbeck at REMOVE-THIS-TO-EMAIL-ME.austin.rr.com (Brandon Beck) Date: Wed, 03 Jul 2002 03:23:19 GMT Subject: Running scripts within scripts References: <3d2225d8$1@post.usenet.com> <7xznx9wwrg.fsf@ruckus.brouhaha.com> Message-ID: <3D226DEA.60701@REMOVE-THIS-TO-EMAIL-ME.austin.rr.com> Paul Rubin wrote: > "Todd" writes: > >>Is it posible for a python to call a second without importing a module? I >>don't really want to call os.system and have to include paths. Just call a >>second script in the same directory as the parent one. > > > You could say > > os.system("./other-script.py") > > which doesn't need to include any paths. Seems like this is exactly what execfile was written for. It does require a file object to work on though but it's not hard to get one try: # use open() to get a file object. In python 2.2 and # later, use file() instead. fin = open('other-script.py') except IOError: # print witty error message here # execute the code in the specified file execfile(fin) There are more advanced versions of execfile that take a globals and locals maps. See the python documentation at http://www.python.org for instructions on how to use them. Hope this helps, Brandon From gerhard.haering at gmx.de Sat Jul 20 09:50:52 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Jul 2002 13:50:52 GMT Subject: UnicodeError: ASCII decoding error: ordinal not in range(128) References: Message-ID: eugene kim wrote in comp.lang.python: > thx again.. > > i got PyGreSQL(pyPgSQL gave me error ImportError: No module named libpq) > i looked at >>>>help(pgdb) > that was about all docs i could get including from web > > python looks really clean(<->perl), and requires a lot less coding(<->java) > so i'm trying to learn python.. I agree that DB programming in Python generally works with less code than in Java. > by the way > > my last question about java was.. > is this form below also available in java? > --------------------------- > cursor.execute("insert into history (col1, col1, col3) values (%s, %s, %s)", >> (self.url, self.title, self.firsttime)) Well, this is normally off-topic here, but here goes an example for this in Java: import java.sql.*; /* Minimal JDBC example, no error checking for brevity */ public class pgjdbcex { public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "http://www.postgresql.org"; String title = "PostgreSQL"; int firsttime = 42; // Load driver Class.forName("org.postgresql.Driver"); // Get connection Connection db = DriverManager.getConnection("jdbc:postgresql://gargamel/gerhard", "gerhard", "sicrit"); // Get a prepared statement PreparedStatement pst = db.prepareStatement("insert into history (col1, col2, col3) values (?, ?, ?)"); // bind parameters pst.setString(1, url); pst.setString(2, title); pst.setInt(3, firsttime); // execute pst.executeUpdate(); pst.close(); db.close(); } } so you can see that the > cursor.execute("insert into history (col1, col1, col3) values (%s, %s, %s)", > (self.url, self.title, self.firsttime)) expands to four statements in Java. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From pyth at devel.trillke.net Fri Jul 12 16:16:00 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 12 Jul 2002 22:16:00 +0200 Subject: metaclass & __slots__ In-Reply-To: ; from smst@bigfoot.com on Mon, Jul 08, 2002 at 08:37:17AM -0700 References: Message-ID: <20020712221600.X10625@prim.han.de> Steve Tregidgo wrote: > phoebe_1 at att.net (Holden Caulfield) wrote in message news:... > > class MX(type): > > def __init__(cls,name,bases,dict): > > super(MX,cls).__init__(name,bases,dict) > > props = {} > > slots = getattr(cls,'__slots__', []) > > print slots > > for v in dict.keys(): > > vs = v.startswith > > if vs("_get_") or vs("_set_"): > > props[v[5:]] = 1 > > for v in props.keys(): > > fget = getattr(cls,"_get_%s" % v, None) > > fset = getattr(cls,"_set_%s" % v, None) > > setattr(cls,v,property(fget,fset)) > > slots.append("_%s__%s" % (name,v)) > > setattr(cls,'__slots__',slots) > > The indentation of the 'slots.append' line is such that the statement > falls outside of the preceding 'for' loop. In the example that you > gave, this would not have shown up whilst running the code. Wasn't python supposed to be much safer against off-by-one errors? :-) holger From phr-n2002b at NOSPAMnightsong.com Mon Jul 22 13:33:16 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 22 Jul 2002 10:33:16 -0700 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> Message-ID: <7xu1mr7jmr.fsf@ruckus.brouhaha.com> Stefan Schwarzer writes: > > Just to not have to say "foo.foo()" or "from foo import foo". > > If the main purpose of the module is to provide one function, I think > > it's cleaner to be able to import the module and call the function > > without special tricks. > > I consider it cleaner to be explicit, and import the module and call > its function. :-) Does that reasoning not also apply to class instances? Why should class instances be callable through the __call__ method? > How many actual cases do you know of where a module has a single function? > Aren't they rare? I've written several, there are several in the Python library, and remember that it's not necessary for the module to have a single function for a __call__ interface to be useful. __call__ makes sense if there's a most-important or most-frequently-used function in the module. It's ok if there are other functions too. From tempe at pp.inet.fi Mon Jul 29 15:50:10 2002 From: tempe at pp.inet.fi (Teemu Luojola) Date: Mon, 29 Jul 2002 19:50:10 GMT Subject: UnicodeError... Message-ID: <3D459AE0.5030509@pp.inet.fi> Hi, I'm running Python 2.2.1 on Windows 95 with IDLE 0.8. When trying to use Scandic letters ('???'), I get an expected error message: "UnicodeError: ASCII encoding error: ordinal not in range(128)." This problem is dealt in Python FAQ in chapter 4.102. and the following solution is given: > # Set the string encoding used by the Unicode implementation. > # The default is 'ascii' > encoding = "ascii" # <= CHANGE THIS if you wish > > # Enable to support locale aware default string encodings. > import locale > loc = locale.getdefaultlocale() > if loc[1]: > encoding = loc[1] > if encoding != "ascii": > import sys > sys.setdefaultencoding(encoding) > The problem is, that sys doesn't include setdefaultencoding(). Site.py knows the reason for this: > # On Non-Unicode builds this will raise an AttributeError... Tell me, please, how to get that Unicode build. When running Python in command line mode, there is no UnicodeError and print '???' returns the expected result: '???'. Why there is such a difference? - Teemu Luojola From a at b.com Tue Jul 2 16:29:03 2002 From: a at b.com (Thinkit) Date: Tue, 02 Jul 2002 20:29:03 GMT Subject: python decimal infection? Message-ID: How much has the cancer known as decimal infected python? Decimal is evil. From marklists at mceahern.com Fri Jul 12 16:41:20 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 12 Jul 2002 15:41:20 -0500 Subject: Is count supposed to still work? In-Reply-To: Message-ID: > Whether or not you explicitly import string, > count(mystring, substring) > isn't working ("NameError: global name 'count' is not defined") You wouldn't perhaps be making this mistake I occasionally make, would you? import foo x = bar() # forgetting to say foo.bar() >From what I can see, count works: $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> string.count("foo", "bar") 0 Cheers, // mark - From akhar at videotron.ca Thu Jul 25 23:10:26 2002 From: akhar at videotron.ca (akhar) Date: Thu, 25 Jul 2002 22:10:26 -0500 Subject: Jython newbie question References: <3D401577.65D61189@ingenta.com> <3D40409F.8BA9DDC8@ingenta.com> Message-ID: Try using jython 2.1 I have it and string works fine on it "Christopher Myers" wrote in message news:3D40409F.8BA9DDC8 at ingenta.com... > Aha -- I wasn't thinking about using Java string methods (Duh!) > Also, I didn't install Jython on my machine -- the interpreter comes > embedded in Maxq, so I don't really have the Jython interpreter to test > with. > > So, how about using Python's 're' module if string ops aren't > appropriate? Some of the string ops I need to do may require using > re's. Any comments on that? > > Thanks for the help. > > -Chris > > Martin Franklin wrote: > > > > On Thursday 25 Jul 2002 3:12 pm, Christopher Myers wrote: > > > I just downloaded Maxq (http://www.bitmechanic.com/projects/maxq/) > > > > > > (etc . . .) > > > > I forgot to add that as of python 2.0 (and Jython 2.0) you don't need the > > string module for anything apart from obscure (IMHO) methods as string > > objects have methods: > > > > >>> "aaaaa".upper() > > 'AAAAA' > > >>> _.lower() > > 'aaaaa' > > >>> ",".join('abcdefg') > > 'a,b,c,d,e,f,g' > > > > etc..... > > > > Martin > > -- > Christopher Myers, Graduate Software Developer > Ingenta, Inc. > 12 Bassett St. > Providence, RI 02903 > ph: 401.331.2014 x 102 > em: chris.myers at ingenta.com > aim: chrismyers001 From claird at starbase.neosoft.com Fri Jul 12 09:35:11 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 12 Jul 2002 08:35:11 -0500 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: Message-ID: <93DC3CC822A7272F.07F7EC43197B112B.AD4BC7C14A3B6591@lp.airnews.net> In article , Alex Martelli wrote: . . . >It is -- easily. My pet peeve is the idea of using XML files for >tasks that obviously need a real database, preferably a relational one. > >I think some people never really GOT relational databases, no matter >that they've been around for decades and are so widespread, and they're >now turning to *overusing* XML to cover up for that:-). . . . I know just what'll help you feel better, Alex--thoughts of the RDBMS vendors advertising that their datastores have magically become the best places in the world to keep all your tree-structured data. The part that might shock you is that I agree with them occasionally. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From glingl at aon.at Sat Jul 20 10:56:05 2002 From: glingl at aon.at (Gregor Lingl) Date: Sat, 20 Jul 2002 16:56:05 +0200 Subject: Tkinter and IDLE Message-ID: <3D397A05.1000605@aon.at> Hi! QUESTION 1: =========== It's possible (and sometimes convenient) to develop Tkinter-programs interactively with IDLE provided one doesn't write the mainloop() call into the file. Of course one can add this if one wnats to run the program standalone. I wonder if - and how - it were possible to use some test if a Tkinter.mainloop (in this case the one of IDLE) is already running, thus having a statement similar to if __name__ == '__main__': < stuff> at the end of the program: if not : app.mainloop() so one could run the program from IDLE as well as from the commandline. QUESTION 2: =========== Is there a special mailing list or something similar dedicated to Tkinter related stuff? Thanks in advance Gregor From marco.stagnoNOSPAM at libero.it Sat Jul 27 10:56:36 2002 From: marco.stagnoNOSPAM at libero.it (Marco Stagno) Date: Sat, 27 Jul 2002 14:56:36 GMT Subject: os.getlogin() raises OSError (errno 25) References: <12257ec4.0207231946.583a2e93@posting.google.com> <1027489223.157336@yasure> <12257ec4.0207241840.409ed7c2@posting.google.com> Message-ID: >All I did was replace os.getlogin() with pwd.getpwuid(os.geteuid()). even os.environ['USER'] works.. bye bye! MAS! From phoebe_1 at att.net Mon Jul 8 01:56:56 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 7 Jul 2002 22:56:56 -0700 Subject: Can raise only "classic" classes? Message-ID: Greetings, I have run into a slight problem. Is it true that you can only raise exceptions that are "classic" classes? I am trying to build a exception class tree for my project, with the root being derived from a "new" style class. But i cannot use it as an argument to raise!!!! class Err(object): pass >>> raise Err fails!! Thanks From joconnor at cybermesa.com Tue Jul 23 20:29:10 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 24 Jul 2002 07:29:10 +0700 Subject: Python Developer looking for work Message-ID: <3D3DF4D6.53C70048@cybermesa.com> All, I'm an experienced OO developer who favors Python and Smalltalk. I'm moving on from my current position (trapped in TCL H...won't say it) and I'd liek to get back into something with Python or Smalltalk. Rightnow I'm looking for either fulltime or parttime work; contracting would be good. The catch is that I cannot relocate so I'm looking for something either in the New Mexico area, or something with which I can telecommute, which I've done before. Thanks -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From mcfletch at rogers.com Mon Jul 15 13:25:19 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 15 Jul 2002 13:25:19 -0400 Subject: Radians vs. Degrees References: <3D33016C.8030804@cox.net> Message-ID: <3D33057F.5030000@rogers.com> DegToRad: Is just a simple multiplication. Your C code is likely doing a macro-expansion (something Python doesn't do) from DTOR( x ) -> x*degtorad. Here's the factor you're using for the multiplication... import math degtorad = math.pi/180 Auto-conversion between radians and degrees isn't possible, as they are untyped numbers, and both range over infinite values. (Should 360.0 be 1 full rotation, or 57.3 rotations?) For loops in Python: for x in range( 360): rad = x * degtorad do_whatever( rad ) For serious 3D work, you'd likely use the Numeric Python extensions and just use a float-range: for rad in arange( 0,2*math.pi, math.pi/180.0): do_whatever( rad ) but I don't recall if Quark provides the Numeric extensions, so you should probably stick with the range(360) loop above. HTH, Mike Jef wrote: > Hi All, > > I'm new to this NG so please bear with me :-) I'm writing an addon for > the Quake2 editor named QuArK and could use some advice from the > math/coding gurus out there. > > My problem is that I'm trying to create a torus (donut) and the C code > I'm looking at uses DTOR to convert degrees to radians and I see no > mention of it (DTOR) in Python. My question is whether I need this in > Python or does Python automatically convert to radians during > calculations? Also, do the FOR loops work the same as in C++ (e.g. > FOR(x=0, x<360, x++))? If not, any suggestions on how to do this? > > TIA > > -Jef > -- _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From eugene1977 at hotmail.com Sat Jul 20 16:35:52 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sat, 20 Jul 2002 15:35:52 -0500 Subject: correct syntax for db api.. Message-ID: i'm trying to find correct syntax for this sql statement.. import pgdb db=pgdb.connect(user='postgres',database='test') cursor=db.cursor() ----------------- cursor.execute('select url, visits from history where url= %s', (self.url)) ------------- or ----------------- sqlselect = 'select url, visits from history where url = %s ' cursor.execute(sqlselect % self.url) ---------------- didn't work thx From james.kew at btinternet.com Sat Jul 20 13:59:21 2002 From: james.kew at btinternet.com (James Kew) Date: Sat, 20 Jul 2002 18:59:21 +0100 Subject: args command line... References: <409a56e2.0207200133.35cdc06b@posting.google.com> <3D399A3D.1060002@usa.net> Message-ID: "Jim Jinkins" wrote in message news:3D399A3D.1060002 at usa.net... > Shagshag wrote: > > >i'm looking for a script able to handle/understand "common" command > >line options like : > > > >ascript.py -option this_is_a_directory/* > >ascript.py -another_option file1 file2 file3 -another_option2 > >this_is_another_dir > > > >i think that should exist somewhere... > > See module getopt in the standard library. ...subject to the limitations pointed out by other posters: getopt stops processing options after the first non-option argument, and it requires -- before long option names. The original poster might also find the standard library's glob module useful for expanding that "this_is_a_directory/*" argument into a list of files. I also quite like os.path.expandvars()... -- James Kew james.kew at btinternet.com From martin at v.loewis.de Sat Jul 27 18:13:17 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 28 Jul 2002 00:13:17 +0200 Subject: Guide to the python interp. source? References: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> <_UA09.310087$iX5.15590422@bin3.nnrp.aus1.giganews.com> Message-ID: "Tim Gahnstr?m /Bladerman" writes: > when it comes to calling functions it will look like this > > def setTo3(x): > x=3 > > a=2 > setTo3(a) Others have already suggested that this will be impossible to implement, but I guess I can't stop you from trying, so I won't. Instead, I suggest that this is already possible with a slightly different notation def setTo3(x): x.assign(3) a=Reference(2) setTo3(a) All this requires is class Reference: def __init__(self, value): self.value = value def assign(self, value): self.value = value Regards, Martin From ods at fep.ru Wed Jul 3 06:25:33 2002 From: ods at fep.ru (Denis S. Otkidach) Date: Wed, 3 Jul 2002 14:25:33 +0400 (MSD) Subject: GoTo considered missing In-Reply-To: <3D21ADD1.54775D25@anansispaceworks.com> Message-ID: On Tue, 2 Jul 2002, Terry Hancock wrote: TH> > Breaks and Continues are fine for single loops, but: TH> > What is the approved Python method for getting from the TH> bottom of a set of TH> > nested loops to the top? [...] TH> You should probably try to use an exception in this TH> case. TH> TH> class ImDone(Exception): TH> # ... I don't remember this bit because I remember TH> # the now-deprecated exceptions-are-strings syntax TH> pass TH> TH> try: TH> loop ... TH> loop ... TH> loop ... TH> loop ... TH> if TH> special-reason-I-need-to-bail-out-like-Im-finished-early: TH> raise ImDone TH> except ImDone: TH> # stuff I need to do after finishing I'd prefer to tell explicitly what loop to break/continue, something like this: loop...: loop...: ... if ...: : break elif ...: : continue ... (place your favourite character insted ":") where indention is used twice to describe current block and what block to return to on break/continue. P.S. Such nested loops aren't so widely used to worry about. From emile at fenx.com Tue Jul 9 19:04:26 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Jul 2002 23:04:26 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: Simon Foster > Emile > Bo > Matt > Huaiyu > > You seem to be mistaking me for an idiot. Oops... apologies. I must have missed the smiley on your first post. -- Emile van Sebille emile at fenx.com --------- From tjreedy at udel.edu Mon Jul 22 11:41:35 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Jul 2002 15:41:35 GMT Subject: how to delete or change... References: Message-ID: "Shagshag13" wrote in message news:ahh5h2$sp205$1 at ID-146704.news.dfncis.de... > > There are some unknown's here that would be helpful to know. You say > > it's a text file but then talk about opening in binary. Is it ASCII? > > yes, it's an ascii file (i try to open it in binary to do bytes operations instead of lines operations) The (main? only?) difference between text and binary mode on Windows is conversion between \r\n and \n (and none on *nix). > > Also, you say when you tried the binary seek you got an I/O error. > > Was there anything informative about that error that you can post? > > >>> f2 = file('d:/test.txt', 'rwb') > >>> f2.seek(-5, 2) > >>> f2.read(5) > 'TUR\n' > >>> f2.seek(-5, 2) > >>> f2.write('new') > Traceback (most recent call last): > File "", line 1, in ? > f2.write('new') > IOError: (0, 'Error') Not helpful at all. What OS and compiler? Standard distibution or one you compiled? Is your disk full? Did you try 'rw' mode? Or just 'w'? TJR From jonathan at onegoodidea.com Thu Jul 4 03:21:16 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 04 Jul 2002 08:21:16 +0100 Subject: metaclass & __slots__ References: Message-ID: On 3/7/2002 22:17, in article c2595393.0207031317.7d9bb013 at posting.google.com, "Holden Caulfield" wrote: > It looks like because the Metalcass statement is executed in the end > of the class statement, hence the class methods seems to have a > "early" binding to the __slots__ variable. Is this behaviour normal? The __slots__ stuff works at allocation rather than initialisation (along with lots of other magic). So you need to override __new__ instead of __init__ in your metaclass. I made the following changes to your code: ----- class MX(type): def __new__(cls,name,bases,dict): props = {} slots = dict.get('__slots__', []) print slots for v in dict.keys(): vs = v.startswith if vs("_get_") or vs("_set_"): props[v[5:]] = 1 for v in props.keys(): fget = dict.get("_get_%s" % v, None) fset = dict.get("_set_%s" % v, None) dict[v] = property(fget,fset) slots.append("_%s__%s" % (name,v)) dict['__slots__'] = slots return super(MX, cls).__new__(cls,name,bases,dict) class X(object): __metaclass__ = MX __slots__ = ['z'] def __init__(self): self.x = 1 self.z = 2 def _get_x(self): return self.__x def _set_x(self,v): self.__x = v def Test(): y = X() y.x = 4 print y.x if __name__ == "__main__": Test() ----- which gives me the desired result. Note that you do all your work on the dict in __new__ as the class hasn't been created yet (the 'cls' in the __new__ method is 'MX'), then you chain the type.__new__ to do the actual class creation. Jonathan From hst at empolis.co.uk Fri Jul 12 05:44:21 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Fri, 12 Jul 2002 10:44:21 +0100 Subject: making python on Solaris 8 Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220C75@hendrix.empolisuk.com> Although we've built Python before, we have problems building it on a new machine. Details are: Solaris 8 (64-bit) gcc ver 2.95.3 make ver 3.79.1 configure output and the make output with the error at the end are attached. Any ideas on what is wrong would be most welcome. TIA Harvey Thomas empolis UK Ltd <> <> _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: python_configure.TXT URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: python_make.TXT URL: From list-python at ccraig.org Mon Jul 29 00:25:59 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 29 Jul 2002 00:25:59 -0400 Subject: how to count lines in a file ? In-Reply-To: References: <7aU%8.139472$vm5.4528856@news2.tin.it> <1027656130.63094@yasure> Message-ID: bokr at oz.net (Bengt Richter) writes: > I like this, but I think I would rather see timely finalization > subsumed under a general event-handling mechanism for objects. Thus > ref count going to zero would be a standard event that you could > write a handler for. You're still assuming that the standard deals with such a thing as a reference count. One of the points of this whole thread (to my mind) has been that, though it is well known that CPython uses reference counts for garbage collection (and people mistakenly depend on this), the actual language standard does not require it. This means that any code that depends on reference counts, in any way, is not only not portable to Jython (or any other non-CPython compiler), it's not necessarily compatible with all future versions of CPython. So if Guido decides today that reference counts were a dumb idea and he would be better off with a simple mark-and-sweep GC, he can implement one and not lose too much sleep over the weeping and gnashing of teeth from those that depended on the behavior of the current compiler. <.8 wink> -- Christopher A. Craig The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense -- Edsger Dijkstra From cce at clarkevans.com Thu Jul 18 09:26:48 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Thu, 18 Jul 2002 09:26:48 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: ; from james.kew@btinternet.com on Wed, Jul 17, 2002 at 11:52:50PM +0100 References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <20020718092648.A2517@doublegemini.com> On Wed, Jul 17, 2002 at 11:52:50PM +0100, James Kew wrote: | > The information model fits documents well, but is a poor match | > for object serialization, which is 90% of the use cases | > programmers face. | | Um: 90%? What sort of use cases do you see programmers forcing XML into? | Just curious: I fall into the "XML as poor-man's database/parser" camp at | the moment but I'm finding that for a poor man's solution it does quite a | good job with not much programmer effort to glue it together. XML has its roots in structured document processing, and is a descendent of SGML. For example, the research reports by Gartner Group are primarly text, but there are specific tags to mark-up features of the report: chapters to generate a table of contents, keywords to make an index, vendor names to enable better searching, etc. The reports are highly structured with tags, each tag having a beginning and an ending. Furthermore, there is also information which must be attached to a particular series of characters, such as an editorial comment, but must not appear in print. All in all, structured document processing is a rather complicated beast and SGML set out to tackle this problem. SGML thus had many features which supported these requirements. It had attributes for out-of-band information which must be attached to a sequence of characters but not be printed. It allows for mixed content, so that a paragraph for instance can contain a series of untagged characters followed by a series of characters tagged bold. Also, SGML allows for named lists, so that a chapter could be defined, for example, as a series of tables, paragraphs and figures. SGML is also character based, since documents are in essence a large blob of characters "marked-up" SGML also had lots of features which enabled human-editing, it allowed you to skip end tags, it even allowed you to skip intermediate tags so that if a chapter couldn't contain characters directly (characters must be wrapped with a paragraph) the parser would implicitly include a paragraph anyway. These extra syntax features did wonders for SGML's flexibility and in no small way were responsible for HTML's success. However, the implicit and missing end tags required that a parser know the document type definition before it could parse an SGML text. Further, these implicit thingys made it hard to write parsers. Therefore, there was a simplification movement in HTML land where the strcutral features (attributes, mixed content, named list) components of SGML were kept but the features which required a DTD and made parsing complex (implicit tags, optional end tags, etc) were dropped. This simplified SGML was dubbed XML and was then markeded as HTML-next-generation. The marketing for XML has been enormous, but at it's core, it is still primarly a structured document markup language. Due to XML's popularity, lots of people have tried to get it to work for other things. A few people have made XML databases and others have used XML for object serialization and invocation (SOAP/XML-RPC) and it has had many other uses. However, most of these uses tend to use a vastly simplified subset of XML and indeed impose additional constraints on XML as far as particular attributes, etc. These additional attributes/constrains are often needed to model native datastructures of modern languages and they include: (a) a way to specify node type, (b) a way to express that a node occurs more than once in the graph-serialized-as-a-tree, (c) a manner to restrict mixed content which does not usually occur in modern languages, (d) restrictions on named list model are also common. However, even with these constraints and fix-ups, at its heart, XML is a much more complicated beast and this complexity is reflected in the DOM and SAX interface. Since this is the primary interface used by programmers, programmers must grapple with documentisms even if they don't need structured document features. In summary, I'm not saying that XML is bad. It's is fantastic for structured document processing (I have direct experience here). However, just beacuse it has had great success in this domain doesn't mean that this success will be long-lasting in other domains. I see people using XML for lots of purposes it was never designed for; certainly it is flexible enough to do it, but the question is: At what price? With XML the price is pretty steep, especially for "object serialization" requirements where attributes, mixed-content, and named-lists arn't needed and where other things such as typing, graph links, map/lists, and treating characters as a whole scalar (rather than as chunks of characters) is what you want. So, that said, YAML (YAML Ain't Markup Language, http://yaml.org) was designed to meet the needs of object serialization directly. In this domain, I must say, it is much much better than XML. Just like in the document serialization domain for which XML was designed, YAML would not work very well at all... YAML isn't markup. In YAML you have dictionaries, lists, and scalars; you don't have chararacters that are tagged. The difference may seem subtle, but the actual impact is huge. It's a completely different mid-set. For a programmer with serialization needs, YAML fits the bill perfectly while XML requires quite a bit of effort to make work. The only down side of YAML is that it isn't buzz-word compliant and the implementation's aren't quite mature yet. The implementations will come along (the native python one isn't bad at all). And hopefully buzz-word compliance will come along eventually, till then there is a subsetted XML mapping of YAML (http://yaml.org/xml.html) which you can use. I'll patch up the python parser to read/write from this XML format within a few more weeks. This way those team members which have to have to be buzz-word compliant can do so. For my day job, I'm more interested in getting the job done... Best, Clark From shalehperry at attbi.com Fri Jul 5 16:11:57 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 05 Jul 2002 13:11:57 -0700 (PDT) Subject: how to disable maximize button? In-Reply-To: <3D25D5BA000004FB@www.zipmail.com.br> Message-ID: On 05-Jul-2002 jubafre at zipmail.com.br wrote: > how i can disable de maximise button in tkinter, i don?t want the user > modific > the size of the window, i want a real size of window, how can i do it??? > > under the X Window system on UNIX/Linux the idiom is to specify the window's maximize size == minimum size in the window hints. From venkat_thoutam at tufts-health.com Wed Jul 10 15:44:56 2002 From: venkat_thoutam at tufts-health.com (vdba) Date: 10 Jul 2002 12:44:56 -0700 Subject: error: make_obcallback(): could not import mod_python.apache. Message-ID: <459ce672.0207101144.2de8fc88@posting.google.com> I am using the mod_python(Version. 2.2) to integrate python(Ver. 1.5.2) with apache(Ver. 1.3.24) web server and am geting the below error. make_obcallback(): could not import mod_python.apache. make_obcallback(): could not call init. I did the following modifications to the httpd.conf file. LoadModule python_module modules/mod_python.dll AddModule mod_python.c ScriptAlias /python/ "c:/Program Files/Apache Group/Apache/htdocs/python/" AddHandler python-program .py PythonHandler mptest PythonDebug AddHandler python .py Any help will be greatly appreciated. Venkat. From mfranklin1 at gatwick.westerngeco.slb.com Tue Jul 16 11:16:52 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 16 Jul 2002 15:16:52 +0000 Subject: Tkinter.create_dot() In-Reply-To: <200207161342.g6GDgf728898@helios.gatwick.geco-prakla.slb.com> References: <200207161342.g6GDgf728898@helios.gatwick.geco-prakla.slb.com> Message-ID: <200207161420.g6GEKX720663@helios.gatwick.geco-prakla.slb.com> On Tuesday 16 Jul 2002 2:39 pm, Martin Franklin wrote: > On Monday 15 Jul 2002 10:55 pm, Justin Shaw wrote: > > I'm using a Tkinter.Canvas to create a picture of thousands of dots. I > > am using > > Tkinter.Canvas.create_line() > > with a line of length one for each dot which really seems to bog down the > > computer. > > > > Is there a better way? > > Not really but you could use a PhotoImage like so:- > > > from Tkinter import * > root=Tk() > canvas=Canvas(root) > canvas.pack() > > pxmap=PhotoImage(width=10, height=10) > for x in range(10): > for y in range(10): > pxmap.put('red', (x, y)) > > canvas.create_image(10, 10, image=pxmap) > root.mainloop() > > > > This will create a red square at 10, 10 in the canvas. > > Following on if you are doing 'thousands' of dots you should check out tk3000 http://www.pythonware.com/products/tkinter/tkinter3000.htm Cheers Martin From dgallion1 at yahoo.com Thu Jul 18 23:21:58 2002 From: dgallion1 at yahoo.com (Darrell) Date: Fri, 19 Jul 2002 03:21:58 GMT Subject: Tkinter vs. wxPython References: Message-ID: I'm not a GUI expert... But today I needed to do a quick image viewer tool. This is what I found. Tkinter makes smaller exe's PMW which wraps Tkinter seems impossible to wrap as an exe. AFIK wxPython wants to display images from BMP's. They dont look very good. They were slow and crashed. My images are 40+ meg. Tkinter has some nice Photo image stuff. Although I haven't figured out how most of it works. So in the intrest of time I used wxPython for the UI and Tk for image display today. Made a 3.7meg exe and everyone is happy. --Darrell Gabe Newcomb wrote: > Ack! > I've been trying to get into wxPython, but I'm finding the lack > of documentation difficult. There's some, and I'm very grateful for > everybody who's contributed it, but I'm somebody who really likes having > a decent reference and more examples. > > My question is this: is there any compelling reason I shouldn't just go > with Tkinter instead? I work (for now) exclusively on Win32 boxes, by > the way. > > Thanks all, > > Gabe From nas at python.ca Thu Jul 25 13:03:55 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 25 Jul 2002 10:03:55 -0700 Subject: Speed up Python by up to 5% ? In-Reply-To: <3D4027BE.4000809@shinners.org>; from pete@shinners.org on Thu, Jul 25, 2002 at 04:30:15PM +0000 References: <3D4027BE.4000809@shinners.org> Message-ID: <20020725100355.A13615@glacier.arctrix.com> Pete Shinners wrote: > i was always under the impression that some sort of "layered" switch > statement could speed up execution. Probably not. I think a smart compiler generates a "computed goto" based on the opcode. In that case, switching twice would slow things down. Neil From aleax at aleax.it Fri Jul 12 13:30:59 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 12 Jul 2002 17:30:59 GMT Subject: newbie question: getting rid of space in string :( References: Message-ID: Martin Franklin wrote: ... > as a matter of taste I would use this:- > wholeString=wholeString+"<%s>%s" %(color, a, color) > but as I say this is a matter of taste! Building up a large string by + concatenation of many small ones is Python's main performance trap. If you want to build things up, build them up in a list instead, then at the end you can use sys.stdout.writelines to write it out or ''.join to make the big string. Alex From LogiplexSoftware1 at earthlink.net Fri Jul 12 16:23:50 2002 From: LogiplexSoftware1 at earthlink.net (Cliff Wells) Date: 12 Jul 2002 13:23:50 -0700 Subject: switch recipe? In-Reply-To: References: Message-ID: <1026505435.3406.46.camel@software1.logiplex.internal> On Fri, 2002-07-12 at 13:05, Mark McEahern wrote: > > out of curiosity, what happens when n reaches the end of the > > int/long/whatever that stores it? > > My guess is this will run forever--if you let it. > > Perhaps it should allow an optional sentinel? The assumption is the caller > is responsible for using it wisely. Or on your "generic" version (still untested - I just reinstalled my PC and don't have Python 2.2 yet): from __future__ import generators def make_switch(*args): """Return a generator that loops through args.""" if not args: raise RuntimeError("Missing parameter: args.") def switch(): i = n = 0 while True: i = n % len(args) yield args[i] n = min(n + 1, len(args)) return switch or possibly: def make_switch(*args): """Return a generator that loops through args.""" if not args: raise RuntimeError("Missing parameter: args.") def switch(): while True: for a in args: yield a return switch From gmfawcett at operamail.com Wed Jul 10 14:15:00 2002 From: gmfawcett at operamail.com (Graham Fawcett) Date: 10 Jul 2002 11:15:00 -0700 Subject: Pyrex and Distuils: an enhanced build_ext command References: <3D24FF3A.4010205@something.invalid> <3d799735.0207091153.258cc430@posting.google.com> <3d799735.0207100216.4eb8a9cd@posting.google.com> Message-ID: <3d799735.0207101015.6e895ba@posting.google.com> "Thomas Heller" wrote in message news:... > > 1. The 'official' way to replace a standard distutils command > class is done in the following way: Derive your class, say > 'my_build_ext', from the standard distutils command: > > class my_build_ext(build_ext): > .... > > and then pass a cmdclass parameter to the setup command: > setup(... > cmdclass = {'build_ext': my_build_ext}, > ...) Ironically, Thomas, you inspired the approach that I took -- I borrowed it from py2exe. ;-) But, all things being equal, "simple and explicit" always trumps "import hack". Thanks, I'll take this into account. > 2. Looking at distutils command.build_ext source, there is already > a method which 'precompiles' source files into .c files, it's the > swig_sources() method. Sound a little hackish, but probably we could > get away with just overriding this method in the my_build_ext class. > Maybe something like the swig_sources() command should be promoted > into an 'official' hook for precompilation? When I subclassed build_ext, I just cut out the swig_sources() method, assuming it was SWIG-specific. But I see the analogy and agree that this would be a clean place to put the "pyrexc" code. Thanks, Thomas, -- Graham From jdavis at empires.org Fri Jul 26 19:46:48 2002 From: jdavis at empires.org (Jeff Davis) Date: Fri, 26 Jul 2002 23:46:48 GMT Subject: performance problem in python 2.2 References: Message-ID: Tim Peters wrote: > [Jeff Davis] >> I wrote a small python program to help me solve a math problem. When I >> tried to run it with large values, > > What does "large values" mean? Please be specific. > If I run it with about 10 million for 'c', it works ok, but if it's about 100 million, it doesn't seem to work very well (although much better now that someone pointed out to use xrange() instead of range()). I think now that I am using xrange(), it is pretty much linear wrt the c value that I supply, like the C and perl versions. After using the other suggestions, my concern now has more to do with python just being about 5 times slower than perl (see time listings and code listings below). >> it ate all my RAM and I eventually had to kill it. I tried writing the >> same thing in C and it used almost no RAM (and had an upper limit) and >> finished much faster. > > When you wrote it in C, how did you declare p? In your Perl code $p is a > double-precision float, and in your Python code p is an unbounded integer > (a > data type Perl doesn't have natively). It's impossible to know what you > intended (although easy to guess ). > 'p' was an unsigned long long int. I slightly modified the algorithm in C because it doesn't have (native) support for > 64-bit ints. Since the number of possibilities is 2**64 that value will be slightly bigger than a 64 bit int could hold. So, I just basically multiplied twice by 2^32 and divided twice by 2^32. In other words, I basically treated 'p' as sqrt(p)*sqrt(p) and commuted the multiplication so that I would arrive at the same result (and the testing seemed to show the same results as my other algorithm). I have attached my c code below in case you'd like to know exactly what's going on. >> Then I was talking to someone who suggested that I try perl. I have the >> exact same algorithm in perl, and it doesn't eat my RAM, and executes >> much more quickly (same order of magnitude as the c program). It seems >> almost as if there's a memory leak in one of python's simple math >> operations, because it is so much worse than the other ones I tried. >> >> I have listed the two programs below. Does someone think I found a >> bug/memory leak? > > I don't, no. > Yeah, neither do I. I was mostly questioning python's RAM eating approach to my iterative algorithm that really shouldn't use very much memory. Someone else pointed out that I should use xrange() instead of range() (my fault, not python's), and that alleviated the boundless RAM usage, and comforted me quite a bit about python's computation ability. However, I later used the unix "time" command to test execution time, and the perl version was still about 5 times faster. >> Does someone know about something else that might be going on? > > You do, yes -- but you haven't told us what yet . > >> ... I hope this information is more specific/useful. Thanks very much for your reply (and others who also replied), it's helped me a lot. Regards, Jeff code listings: =============c======================== #include int main(int argc, char * argv[]) { unsigned long long int p,c,i; long double r = 1.0; p = 4294967296; c = 100000000; for(i = 1; i < c+1; i++) { r = (r*p)*p - (r*i); r /= p; r /= p; } printf("%.75Lf\n",1-r); } ==================perl================= #!/usr/bin/perl $p = 2**64; $c = $ARGV[0]; $n = 1; foreach $i (1..$c) { $n = ($n * ($p-$i)) / $p } print 1-$n, "\n"; =================python================ #!/usr/bin/python2.2 import sys n = 1.0 p = 2L**64 c = long(sys.argv[1],10) for i in xrange(1,c): n = (n * (p-i)) / p print 1-n ================time listings=============== ===========c============== jdavis at jeff:~/code/c$ time ./crunch 0.000271013814962212042265765621351647496339865028858184814453125000000000000 real 0m32.915s user 0m32.310s sys 0m0.030s =========perl============== jdavis at jeff:~$ time code/pl/crunch.pl 100000000 0.000271014079116894 real 2m12.835s user 2m8.400s sys 0m0.110s ===========python========== jdavis at jeff:~$ time code/py/crunch.py 100000000 0.000271014073697 real 13m19.242s user 12m53.200s sys 0m2.420s From gtalvola at nameconnector.com Wed Jul 17 09:32:30 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Wed, 17 Jul 2002 09:32:30 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty Message-ID: <61957B071FF421419E567A28A45C7FE514A5C8@MAILBOX.nameconnector.com> Tim Peters wrote: > [Geoffrey Talvola] > > Now that I think of it, maybe a Queue just isn't the right > > tool for this > > job. Queues are basically designed for the case where you want > > block on an empty queue. > > Also to block put() on a full Queue -- bounded queues are a > natural approach > to mediating between producers and consumers with different rates of > production and consumption. Yes, the app server does make use of a bounded queue to mediate the overall request handling, but not to mediate the doling out of _specific_ types of requests which is the code in question here. > > But for this use I never want blocking. Perhaps a simple > > combination of a list and a lock would be better, or even a > > list alone > > without a lock: > > > > try: > > instance = cachelist.pop() > > except IndexError: > > instance = new_instance() > > # use the instance > > cachelist.append(instance) > > > > As long as pop() and append() are atomic, which I believe > > they are, then > > this ought to work. > > They're atomic, yes. If the number of instances can't > outnumber the number > of threads, though, then a dead simple approach is to give > each thread its > own instance at start and skip all this queue fiddling. The appserver doesn't actually know what all the possible servlets are at startup -- they are just stored in the filesystem and can be added or modified while the appserver is running. And it seems wasteful to allocate 20 instances when 1 will do... I went with the cachelist solution above and so far it's working nicely. Thanks for the help! - Geoff From ny_r_marquez at yahoo.com Sat Jul 13 20:24:23 2002 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 13 Jul 2002 17:24:23 -0700 Subject: WeaselWeb Message-ID: <8a27e309.0207131624.6c73be50@posting.google.com> This may interest you if have a Palm Pilot, or if you are interested in custom parsing html files. Those of you with Palm Pilots may be familiar with Weasel reader (http://sourceforge.net/projects/gutenpalm/). I really like this reader because, besides being free software, it gives the best compression that I have seen, and it allows for bookmarks to be generated on the fly as it converts from txt format to its ztxt (pdb) format. The problem for me was that the converter did not know how to handle html files. So I wrote a little Python program to do this and I called it WeaselWeb. It is licensed as free software under the GPL. If you are interested, get it from here (eventually it will be under the main Weasel project page): http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/gutenpalm/gutenpalm/ There is a nice self installing package for Windows. However, the Linux version will need a little help since I do not yet have a usable Linux machine. I would like to eventually creaet a standalone version for Linux as well. (If some one would like to help with this, please be my guest.) Any way, I hope you enjoy it. -Ruben From bokr at oz.net Mon Jul 1 16:31:54 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2002 20:31:54 GMT Subject: How to get rid the new line References: <3D1AD534.A74EC9F4@ipm.fhg.de> <3D1B1A76.563E5394@engcorp.com> <3D1BA535.1EE16646@engcorp.com> <4phT8.45578$n4.10822996@newsc.telia.net> Message-ID: On Sat, 29 Jun 2002 12:06:24 GMT, "Fredrik Lundh" wrote: >Peter Hansen wrote: > >> > Could try this: >> > >> > def chomp(line): >> > if line[-1]=='\n': >> > line=line[:-1] >> > return line >> >> Just make sure you pass chomp() only lines that are not equal >> to the empty string ''. > >or add the single character needed to make chomp a >bit more robust: > > def chomp(line): > if line[-1:] == '\n': > line = line[:-1] > return line > Better yet, why not a .stripEOL() method for strings? Regards, Bengt Richter From aleax at aleax.it Tue Jul 9 13:30:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 17:30:37 GMT Subject: sorting many arrays from one... References: <%KCW8.60416$vm5.2194409@news2.tin.it> <3D2B0973.B553A25F@info.unicaen.fr> Message-ID: <15FW8.61099$vm5.2221340@news2.tin.it> Jerzy Karczmarczuk wrote: ... >> the same cmp that would be used anyway, you pay well more than an >> order of magnitude for the privilege of passing a compare function >> to the sort method!!! > > This was one of my principal griefs when I began to learn Python. I still > don't know why is it so costly. One may suppose that an interpreted user > function f which calls cmp may be the main reason, but xx.sort(cmp) is > also slow [in my rudimentary test about twice as fast as sort(f)]. > > Somebody cares about explaining this behaviour? Dynamic dispatching, > while sort() does not any dereferencing? Or what? Basically, sort needs to do O(N log N) comparisons -- if each comparison requires a function call, the time for those calls dominates sorting times even if each call does little -- the overhead is the same. If you pass nothing, sort knows to use built-in comparison methods, and its wonderful optimizations take hold. An interpreted function increases the overhead, of course, but the function call mechanism itself is costly. Indeed passing cmp directly in my test I see a slowdown of about 5 times, while f which calls cmp gives 10 times -- see, it IS all about function-call times. > For people coming from the Functional Programming Realm such slowdown > of parameterized functionals is hard to accept... Me, I'm not particularly perturbed by the fact that function calls have a cost. Sorting a randomly shuffled sequence of 300,000 items requires a bit more than 5 million comparisons (just checked this out with a suitable comparison function incrementing a global counter as a side effect:-). A slowdown of about 3.9 CPU seconds on my machine for that many calls works out at about 0.76 microseconds per call -- preparing the arguments tuple, unpacking it in the called function, etc. Doesn't feel wildly out of control to me -- it's just a LOT of function calls, using mechanisms studied for an intepreted, dynamic language's needs for flexibility, not to get superb performance. What makes it FEEL huge is sort's own superb performance -- 0.16 microseconds per comparison *everything included* when using the built-in comparison. So, it's all Tim Peters' fault, for making sort so incredibly fast -- let's all gang up against him!!! Oh, and, a warning when you try to do such measurements: if you mistakenly call sort on an already-sorted list, it only does 299999 comparisons (for a 300000 items list) and finishes in 0.04 seconds -- 0.78 with a comparison function, so the ratio gets even worse. If you have just one item out of order at the end, 300019 comparisons, and the same performances. This is truly intolerable -- we HAVE to slow this darn this down!!! >> Don't do it. Use D-S-U, as AMPLY explained in the searching and >> sorting chapter of the Python Cookbook > > I don't want to depreciate your helpful attitude addressed to a person > in need, nor say anything bad about something considered a "common idiom", > but the idea of Decorate-Sort-Undecorate, which begins by constructing > an additional list with fast-sortable keys is also something hard to > digest. May I suggest some Fernet-Branca or other Italian amaro to your liking? They do wonders to help you digest rich, too-abundant meals. Say I have to sort N items. Transforming each into something that's most rapidly comparable, or performing the actual comparison, will typically have a similar CPU cost "X". A comparison may often be closer to a cost of 2X, actually (two items to compute on), but let's forget that for now. Now, by preparing a list of N fastsortable items, I do N*X work To sort a list of N non-preprocessed items, I do N*logN*X work. Thus, preparing the list is logN times faster than not preparing it. Infinitely faster, as N grows...:-). Not quite, of course, because I STILL have some N*logN work to do even with DSU -- say N*logN*eps for some small eps < X. Even though eps is small, for large enough N the N*X term becomes irrelevant and the performance ratio approaches X/eps. So, if preparing fastsortable items takes about 10 times longer than the fastest possible comparison (and pointer swap), then DSU speeds things up by almost 10 times for substantial N. What's surprising, at all, about this...? Suppose there was no call overhead at all, just a very complicated comparison. The effect would be exactly the same, no? Appliying a complicated comparison function must happen N logN times; applying an equally complicated transformation function that makes the items rapidly comparable only must happen N times, and thus becomes irrelevant for large N. So, the X/eps ratio generalizes to just about any sorting task that can be represented with either complicated comparisons OR equally complicated transformations into a form that can then be compared quickly. The call-overhead only ensures that X is never less than (say) 0.8 microseconds/call in Python (typically more, as you don't JUST have the call...). sort's excellent own optimization only ensures that eps can be as low as 0.16 microseconds/comparison-and-swap on the same machine. So, a ratio of 5 can be achieved even with the simplest comparison function, 10 with one not much more complicated, and so on. But the same effect will apply in ANY language for the appropriate kind of sorting task if the comparison op you need grows rich and complicated enough to matter. Assuming the language's sort has perfect optimization and the language makes it very easy to build, handle and dismantle sequences of tuples, of course:-). But these are hardly DEFECTS, are they?-) > The author of the original question had 300 000 items. I had > once five times more, and I found it a bit ridiculous to pollute the > memory with an ephemeric sequence just because there is something lousy > with parametrized sort (and possibly other H. O. functions?) > What do you think? I think you're using loaded language, presumably reflecting loaded and not-well-considered sentiments. There's nothing "lousy" with functions in Python -- they just take measurable time to call, that's all. Most often one doesn't care all that much about performance. Sorting large datasets is most often an exception -- one DOES care, and there's a neat way to minimize the amount of effort spent in comparison, including function-call overhead. DSU, and more generally the possibility of preprocessing data (with linear cost O(N)) to speed up further processing to come (with higher O() costs), is an excellent technique to keep in mind in any language, and Python makes it very easy to use. That's not "polluting the memory with an ephemeric sequence" -- it's investing some memory (not much -- O(N) memory, peanuts!) to reduce computation. A hallowed, time-honored approach, you know. Besides, in case you hadn't noticed, the OP needed to use DSU anyway as the most effective way to sort *ANYWAY* -- he's sorting several "parallel" arrays based on the values in just one of them. If the "basing" needs complicated functions to either compare or preprocess the sort keys, that just needs one extra slot in each of the tuples he'd need *anyway*.... Alex From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 23:38:30 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 20:38:30 -0700 Subject: Linux clock-setting script References: Message-ID: <7x8z4mubwp.fsf@ruckus.brouhaha.com> "David LeBlanc" writes: > "Set Your Clock Via Internet" > http://www.boulder.nist.gov/timefreq/service/its.htm > > This particular page focuses on Windows, but the ftp site has sources in C. I know there's a full blown NTP pckage on that ftp site but I didn't want to spend hours reading documentation and configuring some hairy monstrosity. I don't need millisecond accuracy; I just want my computer to know what time it is within a few seconds. Apparently the C package has a program called ntpdate that maybe does the right thing, but I haven't examined it. From max at alcyone.com Fri Jul 12 05:23:27 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Jul 2002 02:23:27 -0700 Subject: A better self References: <3D2CEDA1.4ACA69FE@engcorp.com> <110720021224320303%pecora@anvil.nrl.navy.mil> <3D2E508C.DBDF9E52@engcorp.com> <3D2E8F10.B9B4EFD2@alcyone.com> <3D2E91ED.B061D0EB@engcorp.com> Message-ID: <3D2EA00F.582923B3@alcyone.com> Peter Hansen wrote: > It always helps when the smileyless posts contain actual humour, > no matter how subtle. Like yours, unlike the other. Sheesh. Even with a smiley, you still get pissy. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From charleshixsn at earthlink.net Tue Jul 9 13:51:07 2002 From: charleshixsn at earthlink.net (Charles Hixson) Date: Tue, 09 Jul 2002 10:51:07 -0700 Subject: Why self? References: <3D29CE9D.4000802@onsitetech.com> <080720021458067296%pecora@anvil.nrl.navy.mil> Message-ID: Lou Pecora wrote: > ... > You know, as much as I LOVE Python I got to agree this one bugs me, > too. I wish the scoping rules could be changed to default to self >... This is a mistake that I make frequently. But it's one that's easy to fix. The one that I really dislike is that there is no demarkated form of the language. Indentation is good, and improves readability, but I always indent with tabs, and IDLE insists that tabs are 8 characters wide, where my standard is 3. This is bad enough, but there are editors out there that will convert tabs to spaces, and vice versa, without warning you. And there is one that even interprets tabs as being an absolute amount of spacing rather than a "space to the next tab mark". None of these warn you about what they are doing, so depending on tabs as a lexical identifier is ... fragile. This has bitten me more than once, and is the primary reason why I find IDLE to be unuseable. A lexical marker would solve this. When I've though of doing an auto-convert script, however, I've always been stymied by one thing... Python already uses all of the punctuation that's readily typeable (the marker should only be one character wide). A specialized editor could adapt curly quotes for this purpose, though it would look a bit wierd, but they don't seem to display well on Linux systems (i.e., many programs do things like rendering a close curly double-quote as either '' or &rdquot; , neither of which work well in a program context. So I tend to accept the non-lexical divisions as a permanent design flaw, and accept it as a reasonable trade for the good features. But this doesn't make me like it. In contrast, the self argument actually makes sense as a distinction between locally bound routine names and class methods (not that I've yet had a use for locally bound routine names, but ...). -- -- Charles Hixson Gnu software that is free, The best is yet to be. From a.clarke11 at pop.ntlworld.com Fri Jul 26 03:22:05 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Fri, 26 Jul 2002 08:22:05 +0100 Subject: Just starting out References: <1763824.4DULROvNVE@CoReKill@localhost> Message-ID: <3D40F89D.25757301@pop.ntlworld.com> Hi Apart from www.python.org, a good site is http://www.awaretek.com/plf.html. It links to lots of other useful sites. Good luck! CoReKiLL wrote: > Hi > > Iam just starting out programming in python and wondering if anyone knows a > good site for guides etc ? Also is it best just to use python fron a > command line in linux or is there a gui front end for it ? > > Thanks From tanzer at swing.co.at Fri Jul 5 11:51:33 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Fri, 05 Jul 2002 17:51:33 +0200 Subject: Why self? In-Reply-To: Your message of "Fri, 05 Jul 2002 10:40:07 EDT." Message-ID: Roy Smith wrote: > Other than in an obfuscated python contest, I can't think of any reason > why anybody would *ever* use any variable name other than "self" as the > first formal parameter of a method. > > Have you ever seen an example that does? Here's an example that should use another name than `self`: >>> class Test(object): ... def __new__(self): ... print "__new__", self ... return object.__new__(self) ... def __init__(self): ... print "__init__", self ... >>> t = Test() __new__ __init__ <__main__.Test object at 0x8153734> IMHO, the first parameter of `__new__` should be called `cls`. Similarly, for normal methods of a metaclass I'd call the first parameter `cls` and the first parameter of `__new__` `meta`... -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From vovka_foreverREMOVE_THIS at hotmail.com Mon Jul 29 10:03:12 2002 From: vovka_foreverREMOVE_THIS at hotmail.com (Vladimir Cherepanov) Date: Mon, 29 Jul 2002 18:03:12 +0400 Subject: Newbie question about dictionaries Message-ID: I've read that dictionaries are implemented as hash tables. Is there any way to specify a hash function? From robin at jessikat.fsnet.co.uk Mon Jul 8 05:13:21 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 8 Jul 2002 10:13:21 +0100 Subject: replacing instance __setattr__ References: Message-ID: In article , Alex Martelli writes >Robin Becker wrote: ...... >This doesn't impede your abilities to customize an instance, without >affecting other instances of the same class: > >def changeSpecial(inst, name, function): > class Customized(inst.__class__): pass > setattr(customized, name, function) > inst.__class__ = Customized > > yes I figured out I need to provide a dummy class to do this sort of thing. >Alex > -- Robin Becker From imcmeans at telus.net Sat Jul 13 17:37:49 2002 From: imcmeans at telus.net (Ian McMeans) Date: Sat, 13 Jul 2002 21:37:49 GMT Subject: numeric References: Message-ID: Nevermind, I figured it out. I reinstalled and the problem went away. "Ian McMeans" wrote in message news:iN0Y8.7171$K6.352620 at news2.telusplanet.net... > I was wondering - what's the status of the Numeric module? > > I want to experiment with FFT, but I can't get Numeric working. I'm running > python 2.2 > > After running the installer, I get this: > >>> from Numeric import * > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named Numeric > > I noticed that the /site-packages/Numeric/ directory doesn't have an > __init__ file. > > I tried installing numarray, but it doesn't have an __init__ file either, > and also can't be imported. > > From franke at ableton.com Wed Jul 3 12:02:26 2002 From: franke at ableton.com (Stefan Franke) Date: Wed, 03 Jul 2002 18:02:26 +0200 Subject: Web templating/db tool with best designer/coder separation? References: <0663iuskkqrjui7rg4ut5b80vmo556jo8k@4ax.com> Message-ID: <4s76iu4vfbprgirk01oe1c9ejvhsepcj6d@4ax.com> On 2 Jul 2002 13:28:53 -0700, paul at boddie.net (Paul Boddie) wrote: [...] >This is what Enhydra's XMLC does, and one uses a DOM-like API to >access the elements marked in this way in the document. Thank, Paul, for this interesting reference! * * * On Wed, 03 Jul 2002 11:11:02 +0100, Richie wrote: [...] >The biggest problem I can see is that I'm using object attributes to >represent both HTML tag attributes and child objects. So 'form.name' >could refer to an attribute of the
tag or to an input control on >the form. I don't think this really is a big problem. A HTML document has to be checked only once if an Id of a son element collides with one of its attributes (e.g. when modified as a Zope document). During processing, only the add_attribute() function has to check for son elements of the same name accordingly. Name collisions could also be avoided with naming conventions or by allowing structured names for elements itself (id="attr.color") >Note that all these classes, Template.Table, Template.Form, etc. etc., >would probably be created on the fly - there wouldn't really be a chunk >of code in the Template module for every HTML tag. Here I don't (yet) see the advantage of having different classes mirroring the different HTML tags. Ok, the table object in your example offers add() and remove() methods, OTOH ZPT shows us that a set of uniform operations replacement operations is sufficient. The XMLC Paul mentioned seems to use a single class for this as well (org.enhydra.xml.xmlc.html.HTMLObject, as far as I interpret http://webreference.com/xml/column23/3.html). I would try to keep things even more simple: Is there really a need for a DOM-like access where each tag and sub-tag of interest has to be tree-like identified? If there's only one place where substitution should happen, it's not necessary to mark more than one tag, even if this one is deeply nested. Thus, the document tree would fall apart into a forest of sparse subtrees, each of which usually not more than 2 or 3 levels deep. This help a lot to keep the addressing simple, and allows more abstration between the HTML documents and the templating scripts - in case the same script is used with multiple documents, only the 'abstract' document structured, as given by the identified tags, has to match. In a perfect world, we had even two layers of template substitutions: A 'low-level' one based one a Python API (like yours above), and a higher level one that specifies the substitutions in a more condensed way, (a little context-specific, mayve Quixote-like language). Since the latter one is restricted to a few operations, it could be pre-compiled together with the HTML documents for maximum performance. Stefan From akuchlin at ute.mems-exchange.org Tue Jul 16 14:32:28 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 16 Jul 2002 18:32:28 GMT Subject: there's no DefaultHandler References: Message-ID: In article , a64bs4$1oo$1 at newsreader.mailgate.org wrote: > [eugene at eugene python]$ python firstxml.py > Traceback (most recent call last): > File "firstxml.py", line 6, in ? > class FindIssue(xml.sax.DefaultHandler): > AttributeError: 'module' object has no attribute 'DefaultHandler' This example comes from the XML HOWTO, and assumes you also have the PyXML package installed. You can download a copy from pyxml.sf.net. However, if this is your first attempt at writing Python code, the Python tutorial at http://www.python.org/doc/tut/ will be a much gentler introduction to the language than trying to do XML processing right off the bat. --amk (www.amk.ca) Humour is a tricky thing. Some people can't even get the spelling right. -- Richard Brodie, 30 Oct 2000 From eay at oclearnet.com Mon Jul 15 20:23:01 2002 From: eay at oclearnet.com (Eric Yohanson) Date: Mon, 15 Jul 2002 17:23:01 -0700 Subject: how can I do this? References: Message-ID: <9np6juoci9apecroqpoqorjq9b21to4bbv@4ax.com> On Mon, 15 Jul 2002 18:28:06 -0500, John Hunter wrote: >>>>>> "Eric" == Eric Yohanson writes: > > Eric> I would like to know if it is possible in python 2.21 to > Eric> make a text entry widget that initially show nothing but > Eric> when the user type the first character displays a template > Eric> like "00#00:01+2" for the previous I have only enter the > Eric> numbers 1 & 2. the numbers would need to enter from right > Eric> and travel to the left as more are entered replacing the "0" > Eric> place holders. How difficult would this be to do and what > Eric> should my approach be to this. Any help wuld be great. > >Getting sinlge chars in python is platform and GUI dependent (search >for getchar on groups.google.com in comp.lang.python for some >suggestions). > >But assuming you can get the chars, here is some code that will do the >template substitution. I use a list of chars as input. I found it >easier to do this by first flipping the template string from left to >right and using python's index function, which searches from the left. > >import string > >def fliplr(s): > "flip the string s from left to right" > out = '' > for i in range(len(s)-1, -1, -1): > out += s[i] > return out > >def replchars(template, chars, token='0'): > "replace the kth instance of token in template with chars[k]" > out = map(None, template) # out is a list of chars in template > for c in chars: > ind = out.index(token) > if ind==-1: > raise ValueError, 'Could not find token %s in template' > out[ind] = c > > return string.join(out, "") > >template = "00#00:00+0" >chars = ['1', '2', '3', '4', '5', '6', '7'] > >rtemplate = fliplr(template) >for i in range( len(chars) ): > rchars = fliplr( chars[0:i+1] ) > print fliplr( replchars( rtemplate, rchars) ) > > > >The output is: >00#00:00+1 >00#00:01+2 >00#00:12+3 >00#01:23+4 >00#12:34+5 >01#23:45+6 >12#34:56+7 > > >Here's a shorter, but possibly more obscure version: > >import string > >def rsub(template, chars, token='0'): > out = map(None, template) > # get the indicies of the tokens in reverse order > inds = [ i for i in range(len(template)-1, -1, -1) if template[i]==token] > N = len(chars) > for i in range( len(chars) ): > out[inds[i]] = chars[N-i-1] > return string.join(out, "") > >template = "00#00:00+0" >chars = ['1', '2', '3', '4', '5', '6', '7'] > >for i in range( len(chars)) : > print rsub(template, chars[0:i+1]) > >HTH, >JDH Thanks for the quick help. I never thought about reversing the string (I guess I was just looking at this thing to long) . This should work just fine. I search for the getchar info. Once again thanks Eric From cliechti at gmx.net Wed Jul 24 16:34:37 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Jul 2002 22:34:37 +0200 Subject: Strange Queue error References: <4378fa6f.0207241120.1876187b@posting.google.com> Message-ID: mnations at airmail.net (Marc) wrote in news:4378fa6f.0207241120.1876187b at posting.google.com: > I was attempting to use the Queue and came across a strange error. Why > is Python wanting a Queue instance as an argument and not accepting > the tuple. I was simply trying to put this on the queue: > qlist.put( (sleep, 5) ) > > Here is the error. > > C:\Python22\CAP v1.0\queue>python temp2.py > File "security.py", line 35, in uid_gen_format > qlist.put( (sleep, 5) ) > TypeError: unbound method put() must be called with Queue instance as > first argument (got tuple instance instead) > > Does anyone know what this means? looks like your qlist is a class an not an instance. did you forgot the "()"? qlist = Queue.Queue() ^^ if its not that, please show the definition of qlist. chris -- Chris From aahz at pythoncraft.com Mon Jul 29 12:02:57 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Jul 2002 12:02:57 -0400 Subject: What is a glue language? References: Message-ID: In article , Jens Kubieziel wrote: > >the word 'glue language' is mentioned in the FAQ. I have no clue :-) >what this could mean. Could someone explain this (also a german >translation is appreciated)? Glue is used to stick things together (such as two pieces of wood). Similarly, a glue language is used to stick software components together. Unix shell programming is an excellent example of a glue language because of the way output from Unix programs is designed to be piped. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From whisper at oz.net Tue Jul 23 20:50:42 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 23 Jul 2002 17:50:42 -0700 Subject: list to string In-Reply-To: <15677.53702.74096.508808@12-248-11-90.client.attbi.com> Message-ID: To all who replied - many thanks! Skip surmized correctly that I just wanted a big string (with embedded newlines) instead of the list of lists that readlines() returns. Regards, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Skip Montanaro > Sent: Tuesday, July 23, 2002 15:00 > To: David LeBlanc > Cc: Python-List at Python. Org > Subject: Re: list to string > > > > David> fn = file('foo.txt') > David> txt = fn.readlines() > David> str = ?something?(txt) # or txt.?something?()... > > Assuming what you really want is to get the contents of the file in one > gulp, this should work: > > fn = file('foo.txt') > str = fn.read() > > -- > Skip Montanaro > skip at pobox.com > consulting: http://manatee.mojam.com/~skip/resume.html > > -- > http://mail.python.org/mailman/listinfo/python-list From andreas at kostyrka.priv.at Sat Jul 27 16:11:10 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 27 Jul 2002 22:11:10 +0200 Subject: Webmin-alike cgi script and security In-Reply-To: <20020722141318.GD2610@software.plasmon> References: <20020722133609.GB2610@software.plasmon> <20020722141318.GD2610@software.plasmon> Message-ID: <1027783225.19639.44.camel@vaio2> Am Mon, 2002-07-22 um 16.13 schrieb Dave Swegen: > On Mon, Jul 22, 2002 at 06:08:26PM +0400, Denis S. Otkidach wrote: > > Adding webserver default user to sudoers is a bad thing anyway. > > It's better to use suexec with unique user, that will be used for > > this script only. > > Thanks, this is exactly the sort of info I'm looking for. Also, depending if "local-attackers" are a likely scenario, you might think about using marshal: + does not execute code upon load - loads code objects - supports only basic data structures. Experience shows that for this kind a marshaled dictionary is usually ok. You should consider also if the filebased approach is best. For example AF_UNIX sockets support authentication. You could also pipe the data into the sudo process, and read the answer back from it. Should you go with the file based approach, you should check: -) that the file is only writeable and readable by the "webuser". (or somebody else might be tricking us into doing the wrong thing.) -) that the file is in a directory only writeable by the "webuser". (again, somebody might fool as with a symlink) Basically be as paranoid as you can be. Andreas From fperez528 at yahoo.com Mon Jul 8 15:17:00 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 08 Jul 2002 13:17:00 -0600 Subject: Numarray vs Numpy References: <080720021452508286%pecora@anvil.nrl.navy.mil> Message-ID: Lou Pecora wrote: > >> numarray is a rewrite of numpy. As such it will address some flaws of > numpy's >> design which have been understood over the last few years of its extensive >> use in science. But beware that in order to do that, numarray's designers >> will be forced into breaking compatibility with numpy. So while most numpy >> code will work with numarray, some critical things will not. >> > > Are these compatible with the Numeric module? > Numpy is just a common-lore name for Numeric. f. From see_reply_address at something.invalid Thu Jul 4 20:53:53 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 12:53:53 +1200 Subject: Syntax Error at end of file References: <3D22E6FE.9070705@thomas-guettler.de> Message-ID: <3D24EE21.1090500@something.invalid> Skip Montanaro wrote: > In a similar thread which occurred just a few days ago it was observed (by > Tim Peters, I think) that the set of acceptable characters at any particular > point in the parse is big, so enumerating them in the error message would be > counterproductive and would just serve to confuse the issue in most cases. But in the case of an unclosed triple quote, the scanner surely knows (or could remember) where the beginning of it was! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From duncan at NOSPAMrcp.co.uk Wed Jul 17 05:00:20 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 17 Jul 2002 09:00:20 +0000 (UTC) Subject: Common list in distinct objects' References: <3d331fa9.361390031@news.byu.edu> <3d332491.362646438@news.byu.edu> <3d3427bf.428996374@news.byu.edu> Message-ID: otijim at yahoo.com (Jake R) wrote in news:3d3427bf.428996374 at news.byu.edu: > I just wonder what is the preferred result. IMO each call should > return a new and distinct list (to me this makes sense since in my > case each call creates a new and distinct object. But other than PHP > I have never used a language that allows default parameter values so > maybe this is an already established standard that I'm not familiar > with. > Not a standard, AFAIR C++ gets around the issue by requiring default arguments to be constant expressions. Likewise Visual Basic requires default arguments to be constants (effectively strings, numbers or Empty). I think that the important thing is to remember that in Python 'def' is a statement executed at runtime. In effect: def myFunction(a, b=something): ... is the same as an assignment statement: myFunction = new.function(, globals(), 'myFunction', (something,)) This opens up a whole host of possibilities that simply aren't present in more static languages. For example you could put the 'def' inside a for loop and create a list of functions: adders = [] for i in range(100): def adder(x, increment=i): return x+increment adders.append(adder) To be able to do this, the default arguments simply have to be evaluated when the 'def' is executed, in the scope where the def is executed. That 'scope' issue is important as well: def fn(x=x+1): pass The 'x' in the default argument is the variable 'x' in scope when the function is defined, not the parameter 'x'. There is a tradeoff here, sometime you might want a default value to depend on another parameter and as with your list, the only way to do this is to put in a placeholder value and test for it. e.g. I want two arguments and the second one is usually twice the first: def fn(x, y=2*x): # doesn't work, looks for 'x' outside the function. def fn(x, y=None): if y is None: y = 2*x As I said, the way I look at this is to always remember that 'def' is executed at runtime and the default values are evaluated when 'def' executes. 'class' and its baseclasses are similar, except that the body of the class statement is also executed when the class is defined, whereas the body of the function doesn't execute until called. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From max at alcyone.com Wed Jul 10 02:25:31 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Jul 2002 23:25:31 -0700 Subject: A better self References: <3D2B6EFB.4DA9A4DB@alcyone.com> <3D2BBBB5.1030209@something.invalid> Message-ID: <3D2BD35B.802F3D4D@alcyone.com> Greg Ewing wrote: > Or it could be a shorthand for .attribute, > so you could still call the first arg something else. Right, that's actually what I intended to get across, though obviously I didn't do a very good job. (I wouldn't do anything so perverse as name the self argument anything other than `self'.) > But I tend to agree that a leading "." is a bit > *too* unobtrusive! It doesn't bother me too bad. I wouldn't mind it being done, but I wouldn't fight for it either. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From aleax at aleax.it Mon Jul 8 03:26:40 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 07:26:40 GMT Subject: A hack to let Pyrex 0.3.x users build extension classes on Win32 References: <3D24FF3A.4010205@something.invalid> Message-ID: Matthias Baas wrote: ... > However, I don't know if the distutils can also be used for other > compilers than Visual C++ on Windows. Yes, with some preliminary work -- see (single long URL, may be split): http://www.python.org/dev/doc/devel/inst/tweak-flags.html#SECTION000620000000000000000 This covers Borland and GNU compilers (both cygwin and mingw32) and summarily mentions the preliminary work you have to perform, too. Alex From cliechti at gmx.net Tue Jul 23 12:49:26 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 18:49:26 +0200 Subject: how to count lines in a file ? References: Message-ID: "Shagshag13" wrote in news:ahk020$tl4ue$1 at ID-146704.news.dfncis.de: > i need to count lines in a file (that i *can't* keep in memory, so > can't use readlines()) but you can use xreadlines, or a bit nicer in Py2.2 where "file" is an iterator. lines = 0: for line in file("countme.txt"): lines += 1 (you can substitute file(...) with open(...).xreadlines() in older Py's) chris -- Chris From whisper at oz.net Fri Jul 26 14:20:10 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Jul 2002 11:20:10 -0700 Subject: Python Internals Doc Message-ID: There was, at one time, a website describing Python's internals - anyone know if it's still available and, if so, where it can be found? David LeBlanc Seattle, WA USA From gumuz at looze.net Wed Jul 3 09:29:58 2002 From: gumuz at looze.net (Guyon Morée) Date: Wed, 3 Jul 2002 15:29:58 +0200 Subject: what's up with 'patterns'? References: <3d22f275$0$230$4d4ebb8e@news.nl.uu.net> <3D22F5FF.9070408@mxm.dk> Message-ID: <3d22fb61$0$235$4d4ebb8e@news.nl.uu.net> aha, thanx a lot! is this something i should really look into or is it something that only is usefull when i am designing large systems and such? thanx, Guyon "Max M" wrote in message news:3D22F5FF.9070408 at mxm.dk... > Guyon Mor?e wrote: > > > > i've seen several topics referring to 'patterns'. > > i am unfamiliar with this. could someone explaint to me what this is all > > about? > > > Well people have been doing object oriented programming for several > years by now, and some programmers have noticed that patterns are > starting to emerge in how they use objects to reach their goals. > > That is as they try to solve different problems they often use the same > method of solving their problem. > > These patterns has been described and named in litterature, so that > programmers can refer to them under their pattern names. > > Try to google on "Programming Patterns", that will most likely turn up > more info than you care to shake a stick at ... > > regards max M > From shagshag13 at yahoo.fr Mon Jul 29 07:00:06 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Mon, 29 Jul 2002 13:00:06 +0200 Subject: Size in byte of a string ? Message-ID: hello, i had the folowing problem : i had huge files > 1,5 go. each of theses files contain some other small files and they are separate by a header. i need to do some kind of random access to the small files so i wish to write a script which would build some kind of a table of content for theses huges files. i will have something : samllfile0 : 0 : 3854 From aleax at aleax.it Sat Jul 20 16:43:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 22:43:12 +0200 Subject: unloading imported modules In-Reply-To: References: Message-ID: On Saturday 20 July 2002 10:26 pm, Fran?ois Pinard wrote: > [Alex Martelli] > > > xeon wrote: > > > Is it possible in python intepreter to unload imported modules? or are > > > > No. > > Hello, Alex. > > Suppose we reload, and reload and reload the same module, are the previous > copies freed from memory? If not, then, sigh, I guess, this is it... When you reload(x), the module object x (another reference to which is in sys.modules['x'], and possibly others yet in other modules) is altered so that its contents is "just as if" you had just imported it. There are no "copies": there's only one module object involved. Try -- id(x) is always one and the same. Any *attribute* of the module that may not be referenced any more would have its reference count drop to 0 and be garbage-collected (at once in classic Python, perhaps-later in Jython). > Otherwise, if I remove the module from sys.modules and from the module > namespace having imported it, what would keep it in memory? References to the module are going to be in all modules that imported it, plus one in sys.modules, plus any other reference you may have taken e.g. via assignment statements. Use sys.getrefcount(x) to know how many references there are to object x, be it a module or any other kind of object. When the reference count of an object drops to 0, the object is freed (at once, or eventually). One way to keep something in memory forever is to involve it in a reference loop with an instance of a class that defines __del__ -- a good reason to avoid __del__ in most cases:-). Built-in modules are different, of course -- e.g., no way you can get rid of module sys, nohow:-). Alex From baos at oss.com Sat Jul 20 20:36:17 2002 From: baos at oss.com (Bancroft Scott) Date: 20 Jul 2002 17:36:17 -0700 Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <7x65zj60ku.fsf@ruckus.brouhaha.com> Message-ID: <96062545.0207201636.18457888@posting.google.com> Jonathan Hogg wrote in message news:... > And to answer Fran?ois' earlier point about not being able to use > "standardised" meaningfully with regard to XML. I consider XML to be > "standardised" not because the W3C said so, but because parsing, validating, > querying, and transforming frameworks are available for nearly any language > off-the-shelf, editors support it, and database and data manipulation tools > support it. > > I'm afraid Pickle doesn't come close in this regard (and isn't human > readable anyway). CSV is probably closer but it doesn't support complex > enough structure for me. ASN.1 might be a contender but also isn't human > readable and doesn't have the same availability of tools. And certainly, any > random syntax I might come up with will have support no further than I > write. ASN.1 now defines the XML Encoding Rules. You will find that ASN.1 tools such as those from OSS Nokalva, uniGone, Objective Systems, ATOS, among others, now generate not only the very compact binary encodings that are typically associated with ASN.1, but human-readable XML encodings as well. Some of these tools even generate default stylesheets and DTD's from the ASN.1 input that make it easy to work with other XML tools. By using ASN.1 as the schema language, it becomes easy to generate very compact encodings (e.g., ASN.1 PER-encoded messages) for transmission, then upon receipt easily convert the message from binary to XML for use with common XML tools such as browsers. As far as tool availabilty goes, see http://asn1.elibel.tm.fr/en/links/index.htm#tools. Bancroft From gerhard.haering at gmx.de Tue Jul 23 00:15:10 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 23 Jul 2002 04:15:10 GMT Subject: distutils cygwin bdist_wininst References: <3D3CD77B.1040102@ims.u-tokyo.ac.jp> Message-ID: Michiel Jan Laurens de Hoon wrote in comp.lang.python: > Is it possible to create a Windows installer with distutils using the > Cygwin/mingw gcc compiler? $ python setup.py --compiler=mingw32 $ python setup.py bdist_wininst 'python' must be the win32 Python, *not* the Cygwin Python. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From b.maryniuk at forbis.lt Wed Jul 24 09:33:34 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 24 Jul 2002 15:33:34 +0200 Subject: how to count lines in a file ? In-Reply-To: References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: <200207241533.34302.b.maryniuk@forbis.lt> On Wednesday 24 July 2002 13:20, James Kew wrote: > > i need to count lines in a file (that i *can't* keep in memory, so can't > use readlines()) Arhhh!.. I've missed this point somehow. Therefore to use smallest code, shagshag13 should buy more RAM. :o] > > Now, why on earth would you use that monstrosity instead of: > > > > for line in open(filename): > > count += 1 In anyway this example probably does not work: looping over not sequence and you probably should use xreadlines(). -- Sincerely yours, Bogdan M. Maryniuck >Ever heard of .cshrc? That's a city in Bosnia. Right? (Discussion in comp.os.linux.misc on the intuitiveness of commands.) From amuys at shortech.com.au Thu Jul 25 22:04:26 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 25 Jul 2002 19:04:26 -0700 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> <3D3EA54C.3EF009A@lfpt.rwth-aachen.de> Message-ID: <7934d084.0207251804.29645af8@posting.google.com> Lars von Wedel wrote in message news:<3D3EA54C.3EF009A at lfpt.rwth-aachen.de>... > Hi Jay, > > Sure, there's many applications using distributed functionality. > However, you should consider that technologies like CORBA or > Web Services have similar goals, so check out these before > duplicating work! > > omniORB (http://omniorb.sourceforge.net) and fnorb (don't know where) > are CORBA implementations with Python support. Fnorb can be found at http://www.fnorb.org of course ;). Fnorb's been opensourced, and now also lives at http://sourceforge.net/projects/fnorb. Andrae Muys From missive at frontiernet.net Mon Jul 1 19:49:48 2002 From: missive at frontiernet.net (Lee Harr) Date: Mon, 01 Jul 2002 23:49:48 -0000 Subject: How to triger a timer/signal to a running program References: Message-ID: In article , nicholas wang wrote: > Hi,all > My task is to kill a program when it runs more than a limited time. > My plat is Linux7.1; I've tried Csh to make it using ps ... ; then kill > this program. But it will get extra messages to stdout. Of course, use > "limit" command also works. But both are not perfect. > I know Perl get a command "alarm" will do such a job > I'm searching a Python counterpart. Does anyone know what it is? > My idea about this job is: ( in a python shell ) > 1. mark a signal to a specific program. > 2. run this program > 3. if time exceeds limit(set before run), the shell will kill it. > 2. continue to run the remained commands. > Maybe something in the signal library can help. signal is a module in the standard library. From emile at fenx.com Fri Jul 5 20:40:37 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 06 Jul 2002 00:40:37 GMT Subject: dynamic path to a method ??? References: <51a64474.0207051007.19cb0441@posting.google.com> Message-ID: <90rV8.248438$nZ3.113077@rwcrnsc53> Roger Ineichen > Can anybody tell me how I can construct a dynamic path to a method in > an other python class? > > my situation is: > I get the classname, methodname and attributes by a dynamic form. They > are strings and the names and attributes are dynamic. I do a iteration > over the request an split the names and attributes. > Example after iteration over the request: > > class (instance) = 'personManager' > method = 'addPerson(firstname='', lastname='')' > attribute1, firstname = 'max' > attribute2, lastname = 'miller' > > how can I construct a dynamic path like: > personManager.addPerson( firstname='max', lastname='miller') #So, you have a class with a method something like: class personManager: def __init__(self): pass def addPerson(self, firstname='', lastname=''): self.firstname = firstname self.lastname = lastname #and you end up with strings in variables like: classvar = 'personManager' method = 'addPerson' attribute1 = "firstname = 'max'" attribute2 = "lastname = 'miller'" # then, put attributes 1 & 2 into a dict: kwargs = {} for k,v in [x.split(" = ") for x in [attribute1, attribute2]]: kwargs[k] = v # create an instance instance = globals()[classvar]() # call the method getattr(instance, method)(**kwargs) # and take a look print instance print instance.firstname print instance.lastname HTH, -- Emile van Sebille emile at fenx.com --------- From cliechti at gmx.net Mon Jul 22 18:58:16 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 00:58:16 +0200 Subject: Problem with diferences in executinion References: Message-ID: samschul at pacbell.net (Samuel Schulenburg) wrote in news:d7fcf8b4.0207221430.37c26071 at posting.google.com: > If I execute the following code snipit from Python it executes the way > I expected it. If I build a standalone exe with McMillan's installer > the function call to startscsi() function in MaxPTI's __init__() is > not in scope. > > Maxscsi.py is a file that initializes and loads MaxSCSI.dll which > contains startscsi(). This DLL and Maxscsi.py have been used in other > McMillan installer programs without any problems. This is the first > time I have tried to use a class to instanuate the DLL. The whole idea > behind this program is the desire to embed Python in an exe with some > added methods to allow non programmers to write an external script > file and execute it with the exe with the following call: > > "MaxPTI MyTest" > > Any Help would be appreciated > Sam Schulenburg > > ======================= MaxPTI.py/MaxPTI.exe contains =============== > > from Maxscsi import * # import scsi library > from sys import * don't do import *. it's fine for some packages spcially designed for such use. generally it's a source of problem if a module defines names that conflict with an other module's names. don't do it with sys and _never_ with os. > class MaxPTI: > > def __init__(self,Headless=0): > startscsi(1,Headless) # Start scsi initializtion setting > # Genericflag = 1,and Headless > initscsi("MaxPTI","physicaldrive",1) # Locate drives > setshowcdb(0) > setlogerror(1) > setpauseonerror(0) > ..... > ..... > def Function1() > .... > .... > > def Function2() > .... > .... > > if __name__ == '__main__': > a = MaxPTI(1) > exec("from %s import MyScript"%(argv[1])) you could do this with "__import__('filename')", "exec" smells bad... > print 'Start Script' > MyScript(a) so you require a function MyScript.MyScript... i would use "execfile(sys.argv[1])" is executed in the current namespace, so your class is available right away. no need to have a special named function neither. > =================== End MaxPTI.py ============== > > ================== MyTest.py =================== > def MyScript(a): > print a.DeviceTable > for i in range(a.DeviceTableLength): > print a.DeviceTable[i] > print a.DeviceTable[2][a.pSERIALNUM] > print a.DeviceTable[2][a.pVENDOR] > you don't provide detailed information about the failure you experience. please paste a traceback in such cases. often that says more than a tousand words ;-) chris -- Chris From aleax at aleax.it Fri Jul 26 13:43:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Jul 2002 19:43:31 +0200 Subject: how to count lines in a file ? In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E201922151DC@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E201922151DC@admin56.narex.com> Message-ID: On Friday 26 July 2002 07:08 pm, Bjorn Pettersen wrote: ... > If you make it a little more special purpose, I could propose syntax > like e.g.: > > let a = open('a'): > process(a) That's basically what Microsoft proposes to add in some future C# with the same semantics, except the keyword they have in mind is 'using' ('let' has strongly different connotations for VB users). Not sure what you mean by "more special purpose", though. But if you're opening and processing 3 files, it seems to me we're back with the deep-nesting problem. > being equivalent to: > > a = None > try: > a = open('a') > process(a) > finally: > del a > > assuming a's __del__ was guaranteed to close the file, although it would I think relying on a special method (__del__ or other) may be OK. MS, for their 'using', propose to rely on their finalizers, of course. > probably be safer to create a new statement like: > > close a > > which would call a.__close__ which would "do the right thing". Something > like 'let' also works well with Python indentation. > > For a different approach you can look at Ruby which only has M/S GC, but > also can guarantee file object lifetimes. Guess I'll definitely have to check that -- I had missed this tidbit when studying Ruby. Alex From none at none.com Sat Jul 6 22:08:58 2002 From: none at none.com (John) Date: Sat, 6 Jul 2002 22:08:58 -0400 Subject: python & web services Message-ID: <6pNV8.24555$2w.1181063@news20.bellglobal.com> What is currently available for the development of web services in python? Does Zope provide a complete solution? (I am new to both and plan to learn them together) Thanks. J. From edream at tds.net Fri Jul 26 16:17:18 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 26 Jul 2002 20:17:18 GMT Subject: Guide to the python interp. source? References: Message-ID: I am writing this post on the theory that teaching something is the best way to learn it myself. If I have made any blunders I'm sure the wizards will let me know gently :-) Section 18, Python Language Services, of the Python Library Reference contains information related to the interpreter and the compiler. http://python.org/doc/current/lib/language.html The primary documentation for opcodes appears to be in the documentation of the dis (disassembler) module, section 18.10.1 of the Python Library Reference: http://python.org/doc/current/lib/bytecodes.html Although it seems very low level, I agree that looking at disassemblies is actually very useful because you'll see what gets pushed and pulled from the interpreter's stack by various constructs. That in turn makes the interpreter code much easier to figure out. Python/ceval.c contains the interpreter proper. The cases for various opcodes call two kinds of routines: local (static) helper routines in Python/ceval.c and routines of the C API. Therefore, an intimate knowledge of just about everything in http://python.org/doc/current/api/api.html would be good :-) The quick way to get the documentation for the public routines is via the P index page of the C API: http://python.org/doc/current/api/genindex.html#letter-p For example, PyDict_GetItemString is called early in one of the interpreter's import cases. The documentation is accessible from the index page, and clicking on the link takes us to Section 6.1, Object Protocol, of the C API: http://python.org/doc/current/api/object.html#l2h-165 However, "internal" C API routines (routines not meant to be used by the general public) are not documented in the index. For these, you must go to the source. The Include, Object, Modules and Python directories are the first places to look for sources. It's usually not too difficult to guess where code is. An earlier draft of this posting actually went step-by-step through the interpreter code for the import cases. I've eliminated it because it was loooooong. But that's where you might start: just dive into the code and figure out what every line does for some case you are interested in. Don't take shortcuts: really understand every line of code--where it is defined, where it is documented and what it really does. As you get more experience, you might be able to shortcut this step-by-step process, but at first I recommend absolute thoroughness. Anyway, that's what I am doing :-) For the IMPORT_NAME case you'll end up at builtin___import__ in Python/bltinmodule.c which in turn takes you to PyImport_ImportModuleEx in Python/import.c. The actual work is done in a helper routine called import_module_ex. I suspect that if you understand import_module_ex you will understand everything there is to know about this kind of import. Indeed, the leading comment for import_module_ex is /* The Magnum Opus of dotted-name import :-) */ Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From wilk-spamout at flibuste.net Sun Jul 14 06:05:59 2002 From: wilk-spamout at flibuste.net (William Dode) Date: Sun, 14 Jul 2002 12:05:59 +0200 Subject: web hosting with python cgi Message-ID: <20020714120559.46e0a1f2.wilk-spamout@flibuste.net> hi, In France it's not very easy to find web hosting supporting python cgi... They think only about php/mysql... Even the compagny who support python doesn't show it. So we are not sure they will continue. When zope seems to be too much for little projects, i think cgi in python is a very good alternative between php and zope. How is it in the other country ? How can we change this ? bye ps: if you know about somes compagny who really support python cgi (and follow it) in france, please say me -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From mwh at python.net Wed Jul 3 11:04:13 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 3 Jul 2002 15:04:13 GMT Subject: Compilation error - no module named os References: Message-ID: "Michal Cernoevic" writes: > Excuse my question, but I am unable to compile Python 2.2.1 on Linux > 2.4.9-31. > > I only did tar, cd Python-2.2.1; ./configure; make > > and the compilation finished so: > > *-s*) CC='gcc' LDSHARED='gcc -shared' > OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q > build;; \ > *) CC='gcc' LDSHARED='gcc -shared' > OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py > build;; \ > esac > Could not find platform independent libraries > Consider setting $PYTHONHOME to [:] > 'import site' failed; use -v for traceback > Traceback (most recent call last): > File "./setup.py", line 6, in ? > import sys, os, getopt > ImportError: No module named os > make: *** [sharedmods] Error 1 > > Thanks for some ideas. Something is pretty broken. Try $ ./python -E -v and see what happens. Cheers, M. -- For every complex problem, there is a solution that is simple, neat, and wrong. -- H. L. Mencken From spam at ingoblank.com Thu Jul 11 21:31:12 2002 From: spam at ingoblank.com (Ingo Blank) Date: Fri, 12 Jul 2002 03:31:12 +0200 Subject: Accessing stack (context) frames Message-ID: Hi, I wonder how it is possible, to access the current context (stack) frame in Python. In Smalltalk, there is (mostly) a "thisContext" method, from which one can retrieve informations like the of the currently executed method. And that's exactly what I need. Retrieving the of the method, currently executed. def someFunction(): myName = ... # How ? Thanks --ingo voy NG arktb QBG qr [ rot13 ] PGP PublicKey http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x18B44974 From whisper at oz.net Tue Jul 9 21:50:45 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 9 Jul 2002 18:50:45 -0700 Subject: writing python extension modules In-Reply-To: <20020710010052.GA1461@lilith.my-fqdn.de> Message-ID: And the python source distribution contains an extension example for windows in python22\PC\example_nt David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Gerhard H?ring > Sent: Tuesday, July 09, 2002 18:01 > To: python-list at python.org > Subject: Re: writing python extension modules > > > * Adonis [2002-07-09 20:53 -0400]: > > is there a simple hello world style program that can show me the > > extreme basics on writing python extensions, [...] > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509 > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda > x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) > > > -- > http://mail.python.org/mailman/listinfo/python-list From tdelaney at avaya.com Mon Jul 15 18:39:25 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 16 Jul 2002 08:39:25 +1000 Subject: isA function? Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > have the right signature is inadequate in this circumstance, though > it may be acceptable for you when doing traditional unit testing, > writing tests after the fact. Lovely indirect insult there Peter. Incorrect (beyond the fact that in Java, which my current project uses, you need a minimal amount of code written before the unit test can be completely written) but lovely nonetheless. Agreed - in the factory case, a single test of each input -> output is necessary (one case where a type check is a good idea - immediately knowledge that you haven't got what you expect). Apart from that one location though, I stick by not doing typechecks in unit tests - objects should pass behaviour tests. It's actually a lot easier to write unit tests that do this, rather than checking for type - it means that your class heirarchy (if any) can change as required and your unit tests still ensure that the behaviour is correct. Tim Delaney From bogus@does.not.exist.com Mon Jul 29 19:47:08 2002 From: bogus@does.not.exist.com (chris) Date: Mon, 29 Jul 2002 19:47:08 -0400 Subject: pretty basic: get variable name from list of strings? References: Message-ID: <34kbku4j76104d193oevjfi83mk3olvsbt@4ax.com> Thanks Andrew, I'll definitely look up how to use dicts. Will they also help in iterating other "treat string like code" situations like wxPython object creation, here where I want to create 100 radioboxes? for j in range(1,100): varname = 'self.Box'+str(j) varname = wxRadioBox(self, ID_j, name, wxDefaultPos, wxDefaultSize, TeamList[j], 1, wxRA_SPECIFY_COLS) EVT_RADIOBOX(self, ID_j, self.EvtRadioBox_j) Surely there's a way to have a string like 'FileCount = 6' and tell python to execute it. Wait a minute... execute... Aha, >>> exec('horse = 9') >>> horse 9 I'll still look into dict for general usefulness... Chris On Mon, 29 Jul 2002 22:35:31 GMT, Andrew Koenig wrote: >The first question to answer is why you want to have a whole bunch >of variable names instead of using a dict. From renzo.tomaselli at tecnotp.it Wed Jul 17 08:35:20 2002 From: renzo.tomaselli at tecnotp.it (Renzo Tomaselli) Date: 17 Jul 2002 05:35:20 -0700 Subject: inheriting from C types References: Message-ID: <878dc260.0207170435.67b7fb77@posting.google.com> Tim Peters wrote in message news:... > [Martin v. Loewis, out of context] > > What is k.__mro__? > > [Greg Ewing] > > I believe it stands for Method Resolution Order, and > > it contains a flattened list of all the base classes, > > in the order they should be searched for methods. > > All correct, except that it also contains the class itself first (unless you > create a really weird custom metatype that defines a bizarre resolution > order for its instances). But Martin knows that. In context, if we knew > the *value* of k.__mro__, that would help in answering the OP's question. I finally solved it and indeed k.__mro__ contained all base classes. It's a matter of filling in slot tp_methods of a C type, instead of relying upon tp_getattr(o) and alike. Then I discovered that PyType_Ready does the magics of creating/filling in tp_dict from tp_methods, tp_members and others. Once a tp_dict is ready for each base class, we can find any symbol though the mro-flattened base hierarchy of any derived class. Thanks, Renzo From tim.one at comcast.net Tue Jul 30 17:23:35 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 30 Jul 2002 17:23:35 -0400 Subject: Console Installation In-Reply-To: Message-ID: [Mathieu Belanger] > We have many PC installed everywhere in the entire country (Canada) and > we want to install python 2.2 on each one. The only way for now to do > that is to log into each PC with PCAnywhere and run the Wise installer. > It is a way too slow. > > Is there a console installer that don't have to be interactive?? > I've search for that everywhere and didn't find anything! > > All our PC run WinNT4. I really don't know. Here are the docs for the command-line switches the PythonLabs installer purportedly accepts (I've never tried them; the docs come from the Wise manual): """ /T Install in Test mode. /X pathname Extracts files to pathname. /Z pathname Extracts files to pathname, then reboots. /M Runs installation in manual mode, prompting for system directories such as Windows, System, etc. /M=filename Specifies a value file for installation. See Set Variable on page 293 for more information on reading variables /M1 Displays the name of each self-registering OCX or DLL as it is registered /M2 Reserved for internal use by Wise Installation System during debugging sessions /S Slent mode, automatic mode with no user choices """ If that (particularly /S) doesn't do the trick, I'd suggest contacting ActiveState. Their installer (well, at least one of them) is built on MSI technology, which may be more friendly to remote admin-driven installation. Or you could try the more minimal PythonWare installer, which seems to amount to an automated unzip (and doesn't muck with the registry at all): http://www.pythonware.com/products/python/index.htm They're still (according to what the page says) on 2.1.1, though. From brueckd at tbye.com Tue Jul 30 16:43:40 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 30 Jul 2002 13:43:40 -0700 (PDT) Subject: global interpreter lock not working as it should In-Reply-To: Message-ID: On Tue, 30 Jul 2002, Jonathan Hogg wrote: > I think the main problem is that you're trying to do something with Python > threads that they just weren't designed for: CPU intensive work. > > Even if you "fix" Python to force a re-schedule, the GIL means you still > only have one thread executing at a time and get NO CONCURRENCY. When you get right down to it, there's really *little* difference between Python threads and C threads, so the above statement doesn't make too much sense to me. Sure the GIL makes sure that Python object internals are fiddled with one thread at a time, but if you have only 1 CPU, there's only one thread running at a time anyway, regardless of whether your program is in C or Python. IOW, the GIL has no real effect on the applicability or usefulness of threads (assuming a single CPU). > Python threads just aren't any good for parallelism. Remove the word 'Python' and your statement is more correct. Threads themselves aren't all that good for parallelism, which is fine because that's not what they're for anyway. If you're doing CPU-intensive work on a single CPU, making the program multithreaded (regardless of language used) has a good chance of slowing the program down. > They're mainly useful as a communication abstraction. Sorry, but that's just plain wrong. Python threads are useful for the exact same things threads are useful for in Java, C, etc. (handling multiple blocking tasks simultaneously, doing "stuff" while waiting for user input, etc.). > You can browse the archives of this group for many (many) discussions on > "fixing" the GIL, but you aren't going to get a solution. That discussion typically revolves around multi-CPU systems, but the OP didn't mention having multiple CPUs. -Dave From imcmeans at telus.net Sat Jul 13 17:17:02 2002 From: imcmeans at telus.net (Ian McMeans) Date: Sat, 13 Jul 2002 21:17:02 GMT Subject: numeric Message-ID: I was wondering - what's the status of the Numeric module? I want to experiment with FFT, but I can't get Numeric working. I'm running python 2.2 After running the installer, I get this: >>> from Numeric import * Traceback (most recent call last): File "", line 1, in ? ImportError: No module named Numeric I noticed that the /site-packages/Numeric/ directory doesn't have an __init__ file. I tried installing numarray, but it doesn't have an __init__ file either, and also can't be imported. From billintucson at yahoo.com Sat Jul 27 14:04:29 2002 From: billintucson at yahoo.com (Bill Gillespie) Date: 27 Jul 2002 11:04:29 -0700 Subject: Newbie - help request with serial line (termios?) setup in Python 2.2 Message-ID: <4860ce4f.0207271004.4cbc8880@posting.google.com> Hi, I'm trying to open a serial line on a SunOs using python 2.2. I'm new to programming, and fairly new to unix/linux. I have the two pink Oreilly Python books and have read a couple of tutorials - but I am a newbie. After much googling (there is not a lot of novice python/unix/termios info out there) - this is what I think? I should be doing.... Open the line Configure the line? termios?? Communicate with the line (ASCII charachters < > at 4800) Close the line ----------------------- 1) Open the serial line ----------------------- I do the following: >>> import os >>> os.open('/dev/ttyC43', 0600) Is the serial line actually open now? No exceptions are raised - but I do not believe the line is actually open - because I can open it via another terminal witha "tip" command to the controller that uses the line. What is the 0600 integer value and what is it for? --------------------------------------------------------------- 2.) Next I've read that I have to set up the line using termios. --------------------------------------------------------------- Can someone possibly walk me through the basics of setting up termios for a serial line with python 2.2. I just want to read ASCII characters off - and write ASCII charachters to this serial line - Is termios even needed? Or can the whole intration be done with out "the termios low level" - level of interaction? Some supplemental notes: ------------------------ The serial line accesses a controller that controls two other devices. The normal way to interact with the controller is to use the commands: sun> tip oftc (the controller is programmed in Fourth I think) That sets up the communication so that you can ask the device for current settings - it telle you the values, and you can issue commands to change them if you like. To close I use "$." as the EOF. Thanks for any help! Bill From vonWedel at lfpt.rwth-aachen.de Wed Jul 24 09:02:04 2002 From: vonWedel at lfpt.rwth-aachen.de (Lars von Wedel) Date: Wed, 24 Jul 2002 15:02:04 +0200 Subject: Distributed Python References: <20020724.064941.722308542.1589@cybermesa.com> Message-ID: <3D3EA54C.3EF009A@lfpt.rwth-aachen.de> Hi Jay, Sure, there's many applications using distributed functionality. However, you should consider that technologies like CORBA or Web Services have similar goals, so check out these before duplicating work! omniORB (http://omniorb.sourceforge.net) and fnorb (don't know where) are CORBA implementations with Python support. For web services in Python, have a look at http://pywebsvcs.sourceforge.net/ Lars Jay O'Connor wrote: > > A while back, as part of a code sample I submitted for a job, I developed > a basic framework for distributed Python. This is a tool that allows one > Python application to communicate with another, whether on the same > machine or on remote machine(s) > > Being that it was just a sample, I never fully fleshed it out. I've been > contemplating developing it further but first I was wondering if such a > tool would be of interest to anyone else > > -- > Jay O'Connor > joconnor at cybermesa.com > http://www.r4h.org/r4hsoftware -------------- next part -------------- A non-text attachment was scrubbed... Name: vonWedel.vcf Type: text/x-vcard Size: 323 bytes Desc: Card for Lars von Wedel URL: From fredrik at pythonware.com Tue Jul 9 19:17:01 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 09 Jul 2002 23:17:01 GMT Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: Simon Foster wrote: > You seem to be mistaking me for an idiot. mistaking? From max at alcyone.com Sun Jul 7 00:30:19 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Jul 2002 21:30:19 -0700 Subject: structs in python References: Message-ID: <3D27C3DB.A0C81721@alcyone.com> Kevin O'Connor wrote: > What if a syntax like the following were permitted: > >>> p = ( .x = 10, .y = 11, .color = 'blue') > >>> print p.x > 10 This kind of thing is why you have slots. Check the documentation for the __slots__ class attribute. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From zopestoller at thomas-guettler.de Thu Jul 4 04:57:54 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 04 Jul 2002 10:57:54 +0200 Subject: creating XML elements References: Message-ID: <3D240E12.70405@thomas-guettler.de> so very tired wrote: > Hi, > I've been using python for parsing XML, but I need to now create > and add elements with subelements, attributes and text. How do I do this > using the DOM libraries assuming I just have an XML document with a root > node? If you want to create an xml file it might be easier to use print(). string.encode() might help, too thomas From see_reply_address at something.invalid Mon Jul 22 20:53:32 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 23 Jul 2002 12:53:32 +1200 Subject: ANN: Pyrex 0.3.4 References: Message-ID: <3D3CA90C.80003@something.invalid> Robin Becker wrote: > Why do we need the prototype immediately before the actual > specification? > > in the non win32 output > > void initprimes(void); /*proto*/ > void initprimes(void){ > ....... > } > > the first line seems completely redundant. When I'm compiling C/C++ code with CodeWarrior on the Mac (which is what I'm developing Pyrex on) I like to have the "Require Function Prototypes" option turned on. The apparently redundant line is necessary to keep the compiler happy under those conditions. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kai at keliikuli.com Wed Jul 31 21:33:42 2002 From: kai at keliikuli.com (Kai Keliikuli) Date: Thu, 01 Aug 2002 01:33:42 GMT Subject: html forms, dicts and lists Message-ID: hi, I'm wanting to do more with html forms and their processing than I'm able to using the cgi module, but I've had no luck RTFMing or googling. I want to interpret the following html form inputs like so form: interpreted: d = {'a':{'b':'foo'}} form: interpreted: x = [['bar']] Does anyone know where I can find something like this. thanks, kai From shagshag13 at yahoo.fr Tue Jul 30 06:13:31 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 30 Jul 2002 12:13:31 +0200 Subject: signature for a file ? References: <7xeldlh6o8.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" a ?crit dans le message de news: 7xeldlh6o8.fsf at ruckus.brouhaha.com... > You don't say what OS you're running. kro$oft > Anyway if two files have the > same MD5 checksum, it's basically certain that the files are > identical. thanks for this, (so no need to use SHA or CRC ?) > So your basic strategy is: > > for each file in your system: > c = md5 checksum of the file > print c and the pathname leading to the file > > Then take the output of the above and sort it so all the identical md5's > end up next to each other in the output. > > Then find all the sets of files with identical md5's and print out their > paths so you can investigate further, get rid of one copy, etc. yes, i would like to do something like that ! From amuys at shortech.com.au Sun Jul 28 20:18:37 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 28 Jul 2002 17:18:37 -0700 Subject: How to detect the last element in a for loop References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: <7934d084.0207281618.376c67e@posting.google.com> Tom Verbeure wrote in message news:<49S09.13011$9U4.7618 at nwrddc01.gnilink.net>... > > For a simple solution, how about: > > > > for a in myList[:-1]: > > do_stuff(a) > > special_stuff(myList[-1]) > > No, I still want to do 'do_stuff' for the last element also. This may be, > say, 10 lines of code. Too much to duplicate it outside the loop, not > enough for a separate function... > Now this comment I find strange, as personally I consider 10 lines of code about the perfect length for a function. If your functions are consise they become self documenting. As an added bonus, similar functions appearing in different sections (often unrelated) of code, can often suggest powerful abstractions that can make your code more flexible and more maintainable. I personally prefer a function to do one thing. If I find myself needing more then 15-20 lines to describe 'one thing' I stop and ask myself why I'm having so much trouble describing 'one thing' consisely. Is the function actually doing multiple things? Do I really understand what the functions trying to do? Am I trying to use the wrong programmign-paradigm to describe 'one thing'? Maybe the function's in the wrong place, and working too hard to obtain the data it needs? Whatever the problem, I find a function of >20 lines a symptom that there is something wrong. 5-10 lines + error handling. that's-my-general-target-ly yours Andrae Muys From brueckd at tbye.com Fri Jul 19 16:51:00 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 19 Jul 2002 13:51:00 -0700 (PDT) Subject: A better self In-Reply-To: <190720021507121883%pecora@anvil.nrl.navy.mil> Message-ID: On Fri, 19 Jul 2002, Louis M. Pecora wrote: > > Certainly, copying a global or builtin method to a local for > > repeated use is a standard Python speedup trick. > > I learn something every day. We should have a collection of speedup > tricks listed somewhere. We do, but we keep it fairly hidden because consulting the list too early or too often is worse than not having a list. <0.5 wink> -Dave From dpinol at hotmail.com Wed Jul 3 12:24:59 2002 From: dpinol at hotmail.com (=?ISO-8859-1?Q?Daniel_Pi=F1ol_Laserna?=) Date: 3 Jul 2002 09:24:59 -0700 Subject: COM component implementing custom interfaces Message-ID: <46585325.0207030824.7a22dfa1@posting.google.com> I tried to write a simple COM component with the code below. I'm able to correctly instantiate from VB (createinstance), but when trying to cast it to interface ICapeUnitEdit (QueryInterface( , it always fails. any idea? from win32com.gen_py.CAPEOPEN093 import ICapeUnitEdit import win32com.gen_py.CAPEOPEN093 class HyCOGentsUnit: _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] # _com_interfaces_ = ['ExtnUnitOperation','ExtensionObject'] _com_interfaces_ = [win32com.gen_py.CAPEOPEN093.ICapeUnitEdit.CLSID] #, pythoncom.IID_IDispatch] _reg_clsid_ = "{1C4697A2-6673-11D6-8DE9-0000865F4838}" _reg_desc_ = "HYSYS COGents Proxy" _reg_progid_ = "HYSYS.COGentsProxy" _public_methods_ = ['Edit'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Edit(self): self.noCalls = self.noCalls + 1 def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + str(who) if __name__=='__main__': # ni only for 1.4!.'4A5E2E81-C093-11d4-9F1B-0010A4D198C2' import win32com.server.register, win32com.gen_py win32com.server.register.UseCommandLine(HyCOGentsUnit) This is my interface class ICapeUnitEdit(DispatchBaseClass): """ICapeUnitEdit Interface""" CLSID = pythoncom.MakeIID('{678C0A9A-0093-11D2-A67D-00105A42887F}') def Edit(self): """Displays the graphic interface""" return self._oleobj_.InvokeTypes(0x1, LCID, 1, (24, 0), (),) _prop_map_get_ = { } _prop_map_put_ = { } This is the error I get: >>> Registered: HYSYS.COGentsProxy >>> Dispatch("HYSYS.COGentsProxy") Traceback (most recent call last): File "", line 1, in ? File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\client\__init__.py", line 92, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\client\dynamic.py", line 81, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "d:\dani\AppDev\python\APython22\Lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147467259, 'Unspecified error', None, None) From boud at valdyas.org Thu Jul 11 06:37:56 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 11 Jul 2002 12:37:56 +0200 Subject: Python in the enterprise: Pros and cons References: <33e8a47f.0207101302.1bd3d902@posting.google.com> Message-ID: <3d2d64c2$0$12295$e4fe514c@dreader4.news.xs4all.nl> Bo M. Maryniuck wrote: > On Thursday 11 July 2002 11:03, Armin Steinhoff wrote: >> These applications are system independent and are working under >> QNX6.2, Linux and Windows. > > BTW, can You explain how to use QT/Python under Windows for non-commertial > soft? I've tried and I've fault... What I should download from TrollTech > to make my hello_world.py run QT widgets on Bill's platform? :/ > > Note, that I have only Windows OS (no VisualBasic, no VC++, no Borland > stuff etc). Only notepad.exe :) In other hand, I successfully use > wxWindows on M$ Windows and Linux OS. And no problem tu run Python / QT > 3.0 on Linux box. So seems that QT is quite hard to install on Windows. :| > You can _only_ use Qt 2.x on Windows without buying a Qt license. You can either buy BlackAdder, which includes everything you need, or download the non-commercial Qt for Windows, and the pre-compiled PyQt bindings (if Phil still makes these available). There are a few nasty bugs in the non-commercial version of Qt, though. Links: ftp://ftp.trolltech.com/qt/non-commercial http://www.riverbankcomputing.co.uk/download/PyQt/ -- Boudewijn Rempt | http://www.valdyas.org From b.hall at irl.cri.nz Mon Jul 8 17:50:52 2002 From: b.hall at irl.cri.nz (Blair Hall) Date: 8 Jul 2002 21:50:52 GMT Subject: COM client and exceptions Message-ID: <01c226c5$ac44d480$d708cb83@hallb.irl.cri.nz> I am not sure how to handle Python exceptions when Python is using Excel as a client. At present, if Python raises an exception while it has an active reference to Excel, then the behaviour of Excel is damaged until I close Pythonwin and start all over again (worse it is sometimes necessary to reboot). For example, using the class defined below, I can write >>> xl = Excel('test') and then to provoke the problem type >>> xl.problem() After which Excel does not operate properly. So for example, typing >>> xl = Excel("test2") does not open Excel properly: only part of the Excel toolbar on screen. I am using win95 with the latest version of Python and the windows extensions. What should I be doing to keep Excel happy? Indeed, where should I be looking (documentation?) to find out how to write more stable Com-Python code? ######################################### import win32com.client import pythoncom def comExceptionHandler(hr,msg,exc,arg) : print 'COM call failed: %s' % msg if exc is not None: wcode, source, text, helpFile, helpID, scode = exc print 'Error source:',source print text print 'See also: %s (id=%d)' % (helpFile,helpID) class Excel: def __init__(self,filename,visible=1): """ Create a new file in the current working directory and save a new Excel workbook in it. """ import os filename = os.path.join( os.getcwd(), filename ) try: self.app = win32com.client.Dispatch("Excel.Application") wb = self.app.Workbooks.Add() wb.SaveAs(filename) wb.Activate() self.app.Visible = visible except pythoncom.com_error, (hr,msg,exc,arg): comExceptionHandler(hr,msg,exc,arg) def __del__(self): wb = self.app.ActiveWorkbook wb.Save() self.app.Quit() def problem(self): raise "something" # Just raise an exception to show problem From jdhunter at ace.bsd.uchicago.edu Tue Jul 30 10:26:29 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Jul 2002 09:26:29 -0500 Subject: Instant Messenger In-Reply-To: ("Chris"'s message of "Tue, 30 Jul 2002 01:17:18 GMT") References: Message-ID: >>>>> "Chris" == Chris writes: Chris> My biggest problem is storing the sockets that recv() the Chris> username and password, for now. What about a dictionary? s1,s2,sn are the socket connections m = {} m['user1'] = s1 m['user2'] = s2 m['user3'] = s3 If you want to share this dictionary across modules and or threads, you could use a Borg http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 And see the previous thread 'Newbie: How to touch "global" variables' Also, you may want to look at *Python Web Programming* by Steve Holden and David Beazley, which has bountiful examples of all kinds of client/server programming in python. The source code is available for a free download. John Hunter From see_reply_address at something.invalid Thu Jul 4 21:10:55 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 05 Jul 2002 13:10:55 +1200 Subject: Forward Declaring Py_complex References: Message-ID: <3D24F21F.7020106@something.invalid> Mark Charsley wrote: > Is there any way to forward declare Py_complex in C++ headers? I'm trying > to create a C++ function that returns a Py_complex, and would really > prefer not to have to pull in all of Python.h in the header file. If you just want an opaque definition, this seems to work: typedef struct TAG_Py_complex Py_complex; The fact that there isn't really any TAG_Py_complex shouldn't bother it if you never include the real definition from complexobject.h. (If you are, presumably you don't need the opaque definition anyway.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Mon Jul 1 18:08:56 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Jul 2002 22:08:56 GMT Subject: Where is Source for Node Class? References: Message-ID: On Mon, 1 Jul 2002 14:18:34 -0700, "Harvey Frey" wrote: > I'm trying to convert a C program which makes extensive use of pointers > and lists. I assume that dictionaries would be the corresponding python > method, but I'd like to see an example. > > I see that minidom uses a node class, apparently subclassed from a node > class in xml.dom. > I searched through the other .py files in xml/dom, but I can't find the > original node class that minidom is importing. > Is class Node in \Python22\Lib\xml\dom\__init__.py what you are looking for? Re importing and Hierarchical module names, http://www.python.org/doc/current/ref/import.html#l2h-359 may help. > I am a rank beginner in python, so don't hesitate to mention obvious > blunders and misunderstandings. > That one wasn't so obvious ;-) Regards, Bengt Richter From uwe.schmitt at procoders.net Wed Jul 24 05:20:57 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 24 Jul 2002 09:20:57 GMT Subject: wxPython and wxLocale Message-ID: Hi, I have the problem, that in a self written application dialog buttons are labled in german instead of english. How can I change this behavior ? I found a class wxLocale but I do not know how to import it... I tried several import statements but did not succeed. Can anybody help me ? ( I posted my problem some days ago in the wxwindows newsgroup but got no answer ) Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt python, php, c++, codes, tips, tutorials at uwe.schmitt at procoders.net http://www.procoders.net From shagshag13 at yahoo.fr Tue Jul 30 12:14:41 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 30 Jul 2002 18:14:41 +0200 Subject: signature for a file ? References: Message-ID: "John Hunter" a ?crit dans le message de news: mailman.1028039084.20956.python-list at python.org... > I never intended this for distribution, but it seems close enough to > what you are talking about that I thought it might give you some > ideas. Thanks for this, it will help a lot ! and also thanks to the other repliers ! s13. From h_schneider at marketmix.com Mon Jul 15 10:37:07 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Mon, 15 Jul 2002 16:37:07 +0200 Subject: Write \x1a to binary file Message-ID: Hi, I've got a problem with writing "\x1A" to a binary file on Win32 platform. I think due tue an issue wiht popen() this terminates the output stream. Is there any solution for this ? All the best, Harald From jblazi at hotmail.com Sat Jul 13 16:32:32 2002 From: jblazi at hotmail.com (JB) Date: Sat, 13 Jul 2002 22:32:32 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> Message-ID: <3d308c96_8@news.newsgroups.com> Fran?ois Pinard wrote: > Of course, I presume that `f' is efficient itself, > probably based on a > dictionary of some sort say. dictionary lookup is > slightly more than O(1), > but I hope it is O(1) enough for your purpose. Else, you > have to implement > another way. If `f' is more than O(1), your problem > cannot be solved. Thx. f will be *slow*. The list entries are tuples and the tuple entries are strings. Then f is "in" for strings, that is it checks, if one string contains another one. What I want to implement, is a list view with incr4emental search. There will be up to 250000 entrie in the list view at the moment (for example all headers of the news group alt.binaries.mp3.classical) and this number is going to increase in the future as news servers become bigger and bigger. I thought that when f is slow, then at least the merging should be as fast as possible. J.B. > All in all, I think that you will pay a high multiplicator > price for being strictly O(n), and you could achieve > something much faster _in practice_ by relaxing this > constraint. I thought that as have many entries, O(n) should mean "as fast as possible". -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From donn at u.washington.edu Thu Jul 25 18:15:42 2002 From: donn at u.washington.edu (Donn Cave) Date: 25 Jul 2002 22:15:42 GMT Subject: [Re] euid/egid eaten up by os.popen References: Message-ID: Quoth janeaustine50 at hotmail.com (Jane Austine): | >I bet you're running Linux. My suggestion is to try popen2, and | | Yes, Red Hat 7.3 | |> specify the command as a list of arguments. For example, if you |> have been writing |> fp = os.popen('id') |> then try |> fp, ignore = popen2.popen2(['id']) | | Have done that and it didn't work still. ... | It seems like when popen forks for a new shell, euid is all cleared. Yes, I think it's the shell, all right. All I can say is, popen2() works for me - *IF* I use the list of parameters as above. It doesn't help to just use popen2 instead of popen, and give it the same command string. Donn Cave, donn at u.washington.edu From phsdv.remove at earthlink.net Sun Jul 21 02:00:17 2002 From: phsdv.remove at earthlink.net (Paul) Date: Sun, 21 Jul 2002 06:00:17 GMT Subject: maximum recursion depth References: <3D3A42C6.EB9EA9A@engcorp.com> Message-ID: Thanks Kalle and Peter. I've added: sys.setrecursionlimit(3000) and my application is doing what I want it to do :-) (2200 recursions...) Now I can start optimizing my code. Paul "Peter Hansen" wrote in message news:3D3A42C6.EB9EA9A at engcorp.com... > Paul wrote: > > > > My question to you: Is there a way to change the limit of the recursion > > depth? > > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > >>> import sys > >>> dir(sys) > [ ...snippety snip, 'setcheckinterval', 'setprofile', 'setrecursionlimit' ... ] > >>> print sys.setrecursionlimit.__doc__ > setrecursionlimit(n) > > Set the maximum depth of the Python interpreter stack to n. This > limit prevents infinite recursion from causing an overflow of the C > stack and crashing Python. The highest possible limit is platform- > dependent. > >>> sys.setrecursionlimit(2000) > >>> > > :-) > From jdhunter at nitace.bsd.uchicago.edu Tue Jul 23 20:39:28 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Jul 2002 19:39:28 -0500 Subject: NEWBIE: for statement in "dive into python" gives syntax error. References: <3D3DB42D.3080404@earthlink.net> Message-ID: >>>>> "Mack" == Mack writes: Mack> I started reading some tutorials on python because I've just Mack> read SAMS "Teach Yourself Perl in 21 days". Seems to be a Mack> really powerful language and looks just about what I need. I Mack> do not really like the complex syntax though so I thought Mack> that I'd look into Python as well. I programmed in perl for about 4 years before I started with python, and I was skeptical (that's why I waited so long). I figured perl did just about everything I needed, why another scripting language? But I was dead wrong, and rarely work in perl anymore except to keep my old modules plugging along. I read Damian Conway's *Object Oriented Perl* with awe -- the man is a perl genius. But to make OO work in perl is labor intensive and syntactically cumbersome. In python, it just is. If you have any inclinations to crunch numbers, you can write in c, c++ or fortran, and use a host of automated tools (SWIG, boost) to make python interfaces. So you can code the CPU intensive parts in a compiled language, and do the rest (dbase interface, web interaction, distributed objects, parameter management) in python. perl still has more comprehensive third party libraries (eg WWW:Search) but python has libraries to do most everything you want (eg pygoogle, who really wants to search lycos anyway). And although python has no equal to cpan, it has a hell of a lot more built in, so you're more likely to be able to do what you want out of the box with a standard python without needing to go off in search of additional libraries. For example, for web retrieval, python's urllib is builtin, perl's LWP is a cpan module that has to be installed separately (though it probably is already installed with your redhat distro). Stepping off of soapbox, I just wanted to catch you while you were still young and impressionable. Learn both if you have the time and inclination. John Hunter From jdavis at empires.org Fri Jul 26 20:14:36 2002 From: jdavis at empires.org (Jeff Davis) Date: Sat, 27 Jul 2002 00:14:36 GMT Subject: performance problem in python 2.2 References: <7xn0sedslz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Fernando Perez writes: >> #!/usr/bin/perl >> >> $p = 2**64; >> $c = $ARGV[0]; >> >> $n = 1; >> foreach $i (1..$c) { >> $n = ($n * ($p-$i)) / $p >> } >> print 1-$n, "\n"; >> >> But again, there's NO WAY you are going to write perl code to do this at >> C speed (short of a trick like inlining C in perl). > > Does > > $c = 0.0 + $ARGV[0]; > > making $c a float instead of a string help? > > > Also: > > $p = 2**64; > $c = $ARGV[0]; > $n = exp(-($c*$c) / (2*$p)); > print 1-$n, "\n"; > > should give a pretty close approximation faster than any of the > iterative methods listed. Very nice! unfortunately, when I started to solve the problem I didn't understand the relationship to e with my algorithm. Upon further mathematical analysis (after seeing a little pattern develop), I realized the relationship. Of course, that still left me with my python questions :) I learned to never underestimate the usefulness of mathematics in programming. Lucky for me, I had a teacher to ask and he gave me a lot of good info as well. After giving me some advice (including CS related tips that mostly boiled down to "Use assembly, or maybe C if you can about getting an answer"), he pointed me to Sterling's Theorem, which seems similar to what you did. Thanks! Regards, Jeff From mhammond at skippinet.com.au Fri Jul 19 03:41:40 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 19 Jul 2002 07:41:40 GMT Subject: win32com: makepy causes ie problems. References: Message-ID: <3D37C2B7.5010007@skippinet.com.au> David LeBlanc wrote: > While trying to figure out how to make the recently posted (by Paul Rubin) > ie navigation example work, I had occasion to run makepy.py on "Microsoft > Internet Controls". After doing this, the sample would fail on "ie.visible = > 1". Removing the generated file would return the sample to working order. > > Sample: > from win32com.client import DispatchEx > import time > > ie = DispatchEx('internetexplorer.application') > ie.visible = 1 > ie.navigate('http://www.w3.org') Was the problem "AttributeError: visible"? If so, the problem is simply that the correct name for the property is "Visible". makepy is case sensitive. > I'm also interested, as the comment suggests, on how to wait for a browser > to finish navigating before I query it's state? Come to think of it, is > there any way to get back an error status like "403"? :) The best way is to hook IE events. See the docstring for DispatchWithEvents, and the examples in the win32com\test directory. Mark. From max at alcyone.com Thu Jul 18 20:45:12 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 Jul 2002 17:45:12 -0700 Subject: Percent sign in format string? References: Message-ID: <3D376118.F030BCF1@alcyone.com> Ron Levine wrote: > How can I put a "%" sign in a format string? > > For example, x=98 and I want to output > "x = 98%" > > The statement > print "x = %d%"%x > produces a ValueError: incomplete format string > > So does the statement > print "x = %d\%"%x You want: print "x = %d%%" % x -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From kseergobin at sympatico.ca Tue Jul 2 20:16:36 2002 From: kseergobin at sympatico.ca (Ken Seergobin) Date: Tue, 2 Jul 2002 17:16:36 -0700 Subject: Splitting Text files References: <%XnU8.4057$aJ4.853781@news20.bellglobal.com> Message-ID: Thanks. Csplit makes the task much easier! The extraction of the critical data lines plus relevant fields was never an issue. With your suggestions though I can now write batch or shell scripts to do most of the work. However, python offers unlimited possibilities when analysing/visualizing the data. As such, I was looking for an easy way to abandon the use of mulitple unix(like) tools. Part of what I was looking for was the ability to use the root of the bitmap name as the output name. I can extract the bitmap name, but don't know how to redirect data to a file with a similar name (e.g., bitmap1.txt). Anyway, csplit saves a great deal of time. Ken "William Park" wrote in message news:aft3np$h9lhc$1 at ID-99293.news.dfncis.de... > Ken Seergobin wrote: > > "William Park" wrote in message > > news:aft0r5$go61b$3 at ID-99293.news.dfncis.de... > > > >> Perhaps, you should remove 'X-No-Archive'. Most people won't give > >> answers, let alone reply, to such posts. > > > > Personally, I'm not thrilled by every scrap of information being > > recorded. However, if the no-archive option makes getting information > > easier the content of the original post will be repeated in this message. > > (That said, I do understand why posts like these should be archived.) > > > > Original Post: > > > > I've looked around, but have been unable to locate a good example of how > > to split a text file. Specifically, I have datafiles with an > > identification line marked with the name of a BMP file followed by many > > lines of data. This repeats a number of times for each datafile. Within > > the data lines I'm only interested in extracting the those with a > > specific keyword. Ultimately, I'd like to have a datafile for each BMP > > listed in the original file. > > > > Suggestions would be appreciated. I really couldn't make sense of the > > regular expression notes I found. > > > > Thanks, > > Ken > > I'm guessing that your data file looks something like > file1.bmp > ...... > ... > file2.bmp > ...... > ... > file3.bmp > ... > > 1. In shell, you'd do like > csplit file '/\w*\.bmp/' '{*}' --> xx00, xx01, ... > mv xx00 file1.bmp > mv xx01 file2.bmp > ... > > 2. However, since you're only interested in those data lines with certain > keywords, simply do > egrep -e '^file[0-9]\.bmp$' -e 'your_search_pattern' file > or > for x in xx[0-9][0-9]; do > egrep 'your_search_pattern' $i > done > > Translating these to Python is left as exercise for readers. ;-) > > -- > William Park, Open Geometry Consulting, > 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From fperez528 at yahoo.com Mon Jul 22 16:30:30 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 22 Jul 2002 14:30:30 -0600 Subject: Python and weave question. References: <14d3c801.0207221209.197171b9@posting.google.com> Message-ID: Russell Cecala wrote: > Weave is suppose to supply Inline::C and Inline::C++ > functionality. > > The question i have is that when I execute the Python > commands like so ... >>>> import weave >>>> weave.test() > > ... it appears the test fail because either Python > or weave are using the wrong gcc command. > > I have and need to keep several versions of gcc around > so just removing the "wrong gcc" is not a solution. > > How can I get Python or weave to use a differenct gcc. > > I am using Cygwin on a Windows XP system. I suggest you post this to the scipy mailing list. The weave developers are there and they typically answer these queries very promptly. Sorry I can't help you, but for me it works out of the box (under Linux). Regards, f. From rjones at ekit-inc.com Wed Jul 10 02:16:45 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Wed, 10 Jul 2002 16:16:45 +1000 Subject: Lunar lander example In-Reply-To: References: Message-ID: <200207101616.45806.rjones@ekit-inc.com> On Wed, 10 Jul 2002 4:12 pm, Sean 'Shaleh' Perry wrote: > On 10-Jul-2002 Michael Bauers wrote: > > I wrote a simple Lunar Lander program in Python, and I thought it > > demonstrated a lot of basic Python features. > > > > I was wondering if there was a place for example programs for new > > Pythoneers to look at? > > "useless python" and "python cookbook". Do not have the URL handy but a > search should answer it fast enough. Maybe pygame.org would like it too? Richard From spam at ob_scure.dk Mon Jul 8 04:47:27 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Mon, 08 Jul 2002 10:47:27 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> <3D282FF8.6040602@ob_scure.dk> <7x3cuvsnc7.fsf@ruckus.brouhaha.com> <3D2864DE.6030608@ob_scure.dk> Message-ID: <3D29519F.5030406@ob_scure.dk> William Park wrote: > Thomas Jensen wrote: > >>We already have 2 DB Servers, a master replicating changes to a slave. >>Our analysis shows that most database operations are/will be SELECTs. >>Adding more DB servers is trivial, especially if we migrate to MySQL >>(well, cheaper at least :-) > > As I and others have said, deal with algorithm issues first. Especially, > since you already have something that is working. Simply rewriting the current job to be distributed has never been the plan. I am very grateful for all the kind advices regarding algoritm design. I will assure You that a considerable amount of time has gone into algoritm design already. > It may be that you are getting killed by overheads. For example, if your > situation goes something like > Given table of (a, b, x, y, z), > select a=1, b=1; then do something with x, y, z; insert it back. > select a=1, b=2; then do something with x, y, z; insert it back. > ... > select a=2, b=1; then do something with x, y, z; insert it back. > select a=2, b=2; then do something with x, y, z; insert it back. > ... > (1 million lines) > Then, you have > 1e6 x 2 x (connect time, search time, load time, disconnect time) > > Can you dump the whole thing as text file in one-shot, do whatever with > (a,b,x,y,z), and load it back in one-shot? It's something like that, actually it's more like this: select a from T_A; select b from T_B; select c from T_C; calculate and update c; The problem is, that most of the job is build around this model (there's also T_D, T_E, T_F, etc some alike, some not) so changing the general approach would require rewriting most of the program anyways (touching at least 75% of the code I estimate). The current model looks more like this (this is a very simplified example that only shows a very small part of the calculation): select date, value from T_A where unitid = x order by date; calculate T_B values from T_A and perhaph external values select date, value from T_B where unitid = x order by date; update T_B where it differ from the calculated values We are aware that there may be other models which would be faster, however apart from being fast, the calculations must *always* be correct. This is the model we have chosen to achieve this (since other factors than T_A may affect the value of T_B). I don't think dumping anything to a text file will be nessesary, however I will consider it should there be problems. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From opus at value.net Wed Jul 3 06:25:57 2002 From: opus at value.net (Opus) Date: Wed, 3 Jul 2002 03:25:57 -0700 Subject: Syntax Error at end of file In-Reply-To: <3D22C1C6.1020109@thomas-guettler.de> Message-ID: <3D226EC5.16002.2D6024E@localhost> I find it helpful to use an editor that does color coding. Many will color code with strings as well. Would have helped you in this case. On 3 Jul 2002 at 11:20, Thomas Guettler wrote: > Thomas Guettler wrote: > > > > > Hi! > > > > I get the following error-message: > > > > """ > > File "", line 254 > > > > ^ > > SyntaxError: invalid token > > """ > > > > This wrror occurs at the end of the file. I think > > it is because a left a (, ' or " open. > > > > Is there a tool which can give me the line of the opening > > character? I programmed a lot and don't want to scan > > a lot of lines for an not closed paranthesis > > > Found the error: It was an open >'''<. Would it be very difficult > if the error message could say what it was suspecting (''') and > tells me where the matching start is? > > thomas > > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- Dictatorship (n): a form of government under which everything which is not prohibited is compulsory. -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From koko9991 at compuserve.de Thu Jul 25 05:41:35 2002 From: koko9991 at compuserve.de (Konrad Koller) Date: Thu, 25 Jul 2002 09:41:35 GMT Subject: GUI toolkits References: Message-ID: <3d3fc5e5.11320658@news.compuserve.de> On Wed, 24 Jul 2002 10:58:38 GMT, Stefano Vedovelli wrote: >Hello all > >in my spare time I am writing a tool in python, with the intention of >deliver it under GPL. > >I am now starting to approach the GUI part. I have read a lot about Tkinter, >PyQT and wxWindows, but I am now actually even more confused. > >As the interface will be "quite" rich, I'd like to know the opinions of >people who already faced this decision, which tool they have chosen and >why. > >Tia >Regards >Stefano Vedovelli May I draw your attention to the excellent book "Python und Gui-Toolkits" by Michael Lauer. mitp-Verlag Bonn ISBN 3-8266-0844-5 Regards Konrad Koller From "gkrohnXvolucris.8m.com".replace Wed Jul 31 13:57:00 2002 From: "gkrohnXvolucris.8m.com".replace (Greg Krohn ("X", "@")) Date: Wed, 31 Jul 2002 12:57:00 -0500 Subject: win32: execute a file just like a double-click References: Message-ID: "Bob Roberts" wrote in message news:c4e6b17d.0207310941.72463497 at posting.google.com... > From within python, is there any way to "execute" a file just like you > double-clicked on it? For example, if you "execute" a .mp3, winamp > plays it. If you "execute" a .txt, it opens in notepad. os.system('start python_theme_song.mp3') Greg From akuip at yahoo.com Mon Jul 22 18:46:32 2002 From: akuip at yahoo.com (aaron) Date: 22 Jul 2002 15:46:32 -0700 Subject: read-only character buffer, list Message-ID: <85cee405.0207221446.750c36e3@posting.google.com> Ths following message is from a previous question.....my question is what if l = [0,1,2,3,4] is not a sequence...for example l=[.2,.009,.008,.05] how do I handle this? >>> l=[0,1,2,3,4] >>> f=open('e', 'w') >>> f.write(l) Traceback (most recent call last): File "", line 1, in ? TypeError: read-only character buffer, list One could, of course, do the below: >>> l = [0,1,2,3,4] >>> f = open('e','w') >>> f.write(''.join(map(str,l))) From TomH at optiscan.com Tue Jul 23 21:24:36 2002 From: TomH at optiscan.com (Tom Harris) Date: Wed, 24 Jul 2002 11:24:36 +1000 Subject: Mastering Regular Expressions 2nd Ed. Message-ID: >Regular expressions work much better if you use them for lexical >analysis rather than for parsing. > Neil Massive regular expressions are certainly difficult to maintain, and I sometimes wonder if they are the best solution to some problems. Your comments above seem to bear on the correct usage of them. Could you expand a bit? Lexical analysis is tokenisation, parsing is making sense of the tokens, is that correct? Is the moral to leave logic to the programming language, not try to use regexes to di it? Tom Harris, Software Engineer Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168, Australia email tomh at optiscan.com ph +61 3 9538 3333 fax +61 3 9562 7742 This email may contain confidential information. If you have received this email in error, please delete it immediately,and inform us of the mistake by return email. Any form of reproduction, or further dissemination of this email is strictly prohibited. Also, please note that opinions expressed in this email are those of the author, and are not necessarily those of Optiscan Pty Ltd. From wweexxsseessssaa at telusplanet.net Thu Jul 4 16:02:39 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Thu, 04 Jul 2002 20:02:39 GMT Subject: Q: Status of MySQL & Python? References: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> Message-ID: OK now, Gerhard, thanks. Once I realised I had got the windows installer that requires compiling _mysql, it became obvious. Then I found your Binary installer, and now all is well. -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From max at alcyone.com Fri Jul 5 15:34:45 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 05 Jul 2002 12:34:45 -0700 Subject: shallow copy's References: Message-ID: <3D25F4D5.BD66C0AD@alcyone.com> Rajarshi Guha wrote: > I have some code: > > a = [1,2,3,4] > b = a > > Do some operations on a > Will the contents of b mirror a? Or will b remain unchanged? b will change as well, because a and b are both bound to the same object (the list). Note that the Subject of your message reads "shallow copies," but this is not a copy operation at all, it is merely a rebinding. The way to tell if two objects are the same is with the `is' operator; a is b will evaluate to true if a and b refer to the same object. This would be a shallow copy: import copy a = [1, 2, 3, 4] b = copy.copy(a) or just this: a = [1, 2, 3, 4] b = a[:] -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From nextronix at yahoo.de Wed Jul 31 09:49:12 2002 From: nextronix at yahoo.de (Oberon) Date: 31 Jul 2002 13:49:12 GMT Subject: small tkinter problem References: Message-ID: <3d47ead8$0$30455$afc38c87@sisyphus.news.be.easynet.net> Martin Franklin wrote in news:mailman.1028120685.22262.python-list at python.org: > > IOW > > self.results = Listbox(frame,yscrollcommand=self.rescroll.set) > self.results.grid(row=4,column=0,sticky=W+E,columnspan=2) > > > binding the name self.results to the Listbox NOT the return value of > the grid method of the Listbox will give you the desired result > > > Regards > Martin > > thank you for the quick help ! From spyglass106 at yahoo.com.au Wed Jul 24 07:53:10 2002 From: spyglass106 at yahoo.com.au (Jolly Roger) Date: 24 Jul 2002 21:53:10 +1000 Subject: GUI toolkits References: Message-ID: <85r8htibq1.fsf@axis.localdomain> Stefano Vedovelli writes: > in my spare time I am writing a tool in python, with the intention of > deliver it under GPL. > > I am now starting to approach the GUI part. I have read a lot about Tkinter, > PyQT and wxWindows, but I am now actually even more confused. Without commenting on the other toolkits you've mentioned, I have found PyQt to be very good. Qt has a good selection of fairly slick-looking widgets, it's well documented, its performance is fast and robust, and it isn't all that difficult to learn (compared with other systems of comparable size and functionality). It comes with a visual GUI designer that can save you a lot of time and hassle. The Python bindings are always up to date with Qt releases too. The other toolkits may be just as good for all I know, but I've never had cause to regret using PyQt. From phr-n2002b at NOSPAMnightsong.com Tue Jul 9 23:20:03 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 09 Jul 2002 20:20:03 -0700 Subject: Linux clock-setting script References: <7xfzyx5i7s.fsf@ruckus.brouhaha.com> <7xu1nb59qu.fsf@ruckus.brouhaha.com> Message-ID: <7x1yacjml8.fsf@ruckus.brouhaha.com> William Park writes: > I've seen it, but it's a tarball which you have to download and compile. > Whereas, 'netdate', 'ntpdate', and 'telnet 13' are ready to run on all > Linux distribution. Why do people keep saying that? Netdate and ntpdate are not on either of the Red Hat boxes I use (one is RH 7.2 and one is 7.3). From spam at oblomov.org Wed Jul 10 08:16:41 2002 From: spam at oblomov.org (oblomov) Date: Wed, 10 Jul 2002 14:16:41 +0200 Subject: How can I retrieve the ID of the last record I added? References: Message-ID: <20020710141641.1fbadb68.spam@oblomov.org> On Wed, 10 Jul 2002 18:34:43 +0900 Ian Parker wrote: > In article , Brian > writes > >Oops. I just realized you're accessing both MySQL as well as MSSQL. > >My comment about @@IDENTITY applies to MSSQL. I haven't been exposed > >to MySQL yet. :) > > On MySQL there's a function LAST_INSERT_ID([expr]) to return the value > of the last auto-increment field on that connection. The correct way would (of course?) be to retrive the OID of the last inserted record on the connection and then SELECT the data you are looking for. karl From peter at engcorp.com Mon Jul 8 08:37:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 08:37:00 -0400 Subject: Linux clock-setting script References: <7x7kk691g0.fsf@ruckus.brouhaha.com> <7xr8ieu0f3.fsf@ruckus.brouhaha.com> Message-ID: <3D29876C.9DACB7F8@engcorp.com> Paul Rubin wrote: > > Dmitri I GOULIAEV writes: > > Or you can have just one line of shell command, like > > > > # ntpdate host > > > > which is (most probably) already in your distribution. > > Do you have it in your distribution ? (just curious) > > No, not in Red Hat 7.2 or 7.3. It's probably in the big NTP package > that's downloadable/installable, but as I said, I didn't feel like > figuring all that stuff out. I agree. Besides, the Python version is easier to make portable, which I just did for my Windows 98 machines. (Thanks Paul!) I changed the core of the "--set" conditional to this: if os.name == 'posix': os.system("/usr/sbin/hwclock --set '--date=%s'"% ct) elif os.name == 'nt': tt = time.localtime(t - TIME1970) # warning: assumes M-D-Y (American) date format here! winDate = '%s-%s-%s' % (tt[1], tt[2], tt[0]) winTime = '%s:%s:%s' % tt[3:6] os.system("date %s" % winDate) os.system("time %s" % winTime) else: print 'Unsupported OS %s, cannot set time.' % os.name I also had to add a hash-bang line to the start, and change the Linux path to /sbin/hwclock for my Linux boxes... Not sure that's good, bad, or whether one should just rely on PATH to find the executable. -Peter From fperez528 at yahoo.com Fri Jul 26 12:43:51 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 26 Jul 2002 10:43:51 -0600 Subject: AttributeError in re.findAll ? References: Message-ID: Shagshag13 wrote: >>>> p.findAll(t2) > Traceback (most recent call last): > File?"",?line?1,?in?? > p.findAll(t2) > AttributeError: findAll > In [1]: p = re.compile("<[^>]*>") In [2]: p.f p.findall p.finditer spelling. f From tjreedy at udel.edu Sat Jul 20 11:28:20 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Jul 2002 15:28:20 GMT Subject: Lists & two dimensions References: Message-ID: "Pichai Asokan" wrote in message news:bed1f696.0207200546.2bca2e34 at posting.google.com... > I thought > board = [[-1] * 3 ]*3 > should give me a list of 9 elements; > but ... List 'multiplication' is NOT associative. You get list with three references to (one) list with three references to int -1. TJR From comcol at ukmail.com Tue Jul 9 05:13:00 2002 From: comcol at ukmail.com (Comcol) Date: 9 Jul 2002 02:13:00 -0700 Subject: Making computer into server for free References: Message-ID: <1b8c5fe1.0207090113.79c03593@posting.google.com> > I would like to know how to make my computer into a web site host with which > I can use python for making my website. Please Reply. Thank You. Python does have SimpleHTTPServer and CGIHTTPServer which may be of use to you - see the global module index for more info. I've never used them myself, so I don't know how good they are or whether they're suitable for your purposes. From phr-n2002b at NOSPAMnightsong.com Mon Jul 8 16:40:06 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 08 Jul 2002 13:40:06 -0700 Subject: List assignment, unexpected result References: Message-ID: <7xd6tyoswp.fsf@ruckus.brouhaha.com> steve.coates at talk21.com (Steve Coates) writes: > grid = [['.'] * 4 ] * 4 This is the same as saying: x = ['.' * 4] grid = [x, x, x, x] That is, the 4 elements of grid are all the same list. If you now > grid [0][0] = '0' > grid [1][1] = '1' This is like: x[0] = '0' x[1] = '1' so now all 4 elements of grid are ['0','1','.','.'] > The intent is clear i.e. fill the diagonal with 0,1,2,3; but the > result is somewhat different. Could anyone explain why this doesn't > work as expected - and even better, come up with an assignment for > 'grid' that would work. grid = [['.' * 4] for i in range(4)] is one way. IMO this issue should be in the Python warts list (I'm not sure if it's currently on the list or not). From anton.wilson at camotion.com Tue Jul 30 13:09:02 2002 From: anton.wilson at camotion.com (anton wilson) Date: Tue, 30 Jul 2002 13:09:02 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207301708.NAA03182@test-area.com> On Tuesday 30 July 2002 04:55 am, Martin v. L?wis wrote: > Just writes: > > I can see it on MacOSX, three different Linux boxes and a FreeBSD box. > > Various Python versions. The output is always sequential. > > As Aahz explains, that can indeed happen (and, depending on the thread > implementation of your operating system, might be even likely to > happen). It is in no way "wrong". I would disagree. In the Python documentation it states: "In order to support multi-threaded Python programs, the interpreter regularly releases and reacquires the lock -- by default, every ten bytecode instructions " What's the purpose of releasing an reaquiring the lock if no other threads can run? It's easy to say that one can't assume about the order of running on different platforms as a scapegoat, but the main problem is that the GIL is NOT implemented properly with pthreads. So nearly every system that uses pthreads will show this kind of queue behaviour. I have a feeling that there is a hidden race condition between when the thread wakes up the other thread and tries to reaquire the lock. It really should be fixed, or else what's the point of threads? Threads are for concurrency! Anton >Please replace the for statement > with a while 1: loop - even on systems where my script produces > sequential output, I find that the operating system will eventually > switch threads. > > Regards, > Martin From walter at livinglogic.de Fri Jul 19 13:09:17 2002 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Fri, 19 Jul 2002 19:09:17 +0200 Subject: Dpulicating "class Foo:" in C References: Message-ID: <3D3847BD.2060901@livinglogic.de> Mark Charsley wrote: > In article , > mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote: > > OK got a little further. The following seems to work fine > > PyObject* newModule = PyImport_ImportModule("new"); > > PyObject* new_classobj = PyObject_GetAttrString(newModule,"classobj"); > PyObject* args = Py_BuildValue("s(){}","Configure"); > > PyObject* ConfigClass = PyEval_CallObject(new_classobj,args); > > However the following crashes nastily whenever I try to do anything with > ConfigClass... > > PyObject* types = PyImport_ImportModule("types"); > > PyObject* classType = PyObject_GetAttrString(types,"ClassType"); > > PyObject* ConfigClass = _PyObject_New((PyTypeObject*)classType); > > Is there any way to create a new Class Object from C without having to > call into new.classobj? In Include/classobject.h there's a PyObject *PyClass_New(PyObject *, PyObject *, PyObject *); Arguments seem to be: * tuple of base classes * class attribute dictionary * class name But PyClass_New isn't documented, so I wonder, if it's part of the official API. At least, the function name does indicate that it is. Bye, Walter D?rwald From sholden at holdenweb.com Tue Jul 2 07:44:58 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 2 Jul 2002 07:44:58 -0400 Subject: New style classes as exceptions (Was: exception handing) References: <7V%T8.69851$F16.33443@atlpnn01.usenetserver.com> Message-ID: "Jonathan Hogg" wrote in message news:B9467E62.D435%jonathan at onegoodidea.com... > On 1/7/2002 18:02, in article > 7V%T8.69851$F16.33443 at atlpnn01.usenetserver.com, "Steve Holden" > wrote: > [...problems subclassing Exception and using object as an additional base...] > > I think it's obvious that the answer is Well Don't Do That. But ... > > > I think it's currently a feature, but it will doubtless become a bug if this > > situation continues for too long... > > ... as you say, if new-style classes are the future, and certainly the > present now, then it doesn't make much sense to not be able to raise them. > I'm sure they'd welcome a patch on python-dev ;-) and I believe it's Guido's intention that new-styles will eventually include Exception. In fact, new-style classes will probably be all there is eventually but-they'll-look-so-like-old-style-ones-we-won't-notice-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From martin at v.loewis.de Mon Jul 8 00:03:35 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 08 Jul 2002 06:03:35 +0200 Subject: sys.platform on UNIX References: <85bs9jfm4n.fsf@hilbert.ingoblank.com> Message-ID: User & writes: > I need a boolean function isUnix(), which returns true, > if executed on a UNIX OS. Can you elaborate why you need this? Such a test sounds inherently wrong. Regards, Martin From tdelaney at avaya.com Thu Jul 25 18:51:03 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 26 Jul 2002 08:51:03 +1000 Subject: how to count lines in a file ? Message-ID: > From: Michael Gilfix [mailto:mgilfix at eecs.tufts.edu] > > So, out of curiosity, if I define a metaclass on top of some > file object, is this still considered broken code? Is the > __del__ semantics meaningless? Would this object ever become > part of garbage collection? > > class file: > def __init__ (self, path): > self.file = open (path) > def __getattr__ (self, name): > return getattr (self.file, name) > def __setattr__ (self, name, value): > return setattr (self, name, value) > def __del__ (self): > self.file.close () First of all, you shouldn't use the name "file" for your class (file is a builtin name, and is an alias for open). Secondly, you're using the term "metaclass" incorrectly here (at least in respect to python) - the term you are looking for is "proxy", "delegate" or even "adaptor". There are no problems with the above. You have created a normal delegation class. If an instance does not participate in a cycle (in CPython) it will be collected as soon as the last reference to it goes away. If it does participate in a cycle, it will probably be collected at some later stage. In Jython, all objects participate in garbage collection. Tim Delaney From mwarden22 at hotmail.com Tue Jul 30 18:37:36 2002 From: mwarden22 at hotmail.com (nealj) Date: 30 Jul 2002 15:37:36 -0700 Subject: Win32api,sleep() oddity References: <13bf971.0207301012.3af0d16@posting.google.com> Message-ID: The resolution of the Sleep function is controlled by the multimedia timer (I know it doesn't make sense) somewhere in your program's initialization put: timeBeginPeriod( 1 ); don't forget to call timeEndPeriod when your program is exiting.. I was never able to find any decent documentation on why this is - but it works, right now, Sleep is returning with whatever resolution the system is set to which I've seen as high as 200ms. It appears that this only applies to NT/2K/XP based systems. Good Luck! Christopher.Cox at honeywell.com (Chris) wrote in message news:<13bf971.0207301012.3af0d16 at posting.google.com>... > I use Python embedded in a testing utility on Windows NT4. We > recently switched PCs to a faster system because of the volume and > intensity of the tests we were running. The old system was a > PIII-550MHz system and the new is a PIV-1.5GHz system. We've noticed > that when calling the following funtction: > def wait(Seconds): > loop = Seconds * 50 > for i in range (0,loop): > win32api.Sleep(20) > if win32ui.PumpWaitingMessages(0,-1): > win32api.PostQuitMessage() > raise exceptions.SystemExit > > on the PIV system, the actual wait is 50% longer than we had requested > (a 10 second wait actually waits 15.55 seconds, 100 seconds waits > 155.5 seconds). IS there some implementation detail in win32api that > might cause this error to arise? Any help would be appreciated. > > Chris From donnal at donnal.net Wed Jul 31 15:05:19 2002 From: donnal at donnal.net (Donnal Walter) Date: 31 Jul 2002 12:05:19 -0700 Subject: A generic question: idiom for a paramterized base class? References: Message-ID: <918bc22f.0207311105.50a33dba@posting.google.com> "Sean 'Shaleh' Perry" wrote in message news:... > > > > That might do what you want. To me, though, the whole thing seems vague > > and maybe there's another approach that avoids some of these > > complexities. > > > > indeed ugly hierarchies often indicate to little or too much thought. Does this do what you want? ################################################## class AbstractBase(object): def __iadd__(self,other): return self.TAdd(self,other) def __add__(self,r): return AbstractBase.__iadd__(self,r) def __radd__(self,l): return AbstractBase.__iadd__(l,self) class TAdd(object): pass class MyClass1(AbstractBase): # One type of TAdd: class TAdd(AbstractBase): def __init__(self,l,r): print "TAdd instance 1" class MyClass2(AbstractBase): # Another type of TAdd: class TAdd(AbstractBase): def __init__(self,l,r): print "TAdd instance 2" ################################################## >>> x = MyClass1() >>> y = MyClass2() >>> t = x + y TAdd instance 1 >>> u = y + x TAdd instance 2 Donnal Walter Arkansas Children's Hospital From xeon at dacreations.cjb.net Sat Jul 20 15:04:38 2002 From: xeon at dacreations.cjb.net (xeon) Date: 20 Jul 2002 12:04:38 -0700 Subject: unloading imported modules Message-ID: Hi, Is it possible in python intepreter to unload imported modules? or are there ways to refresh the loaded functions if ever the module is updated, other than restarting the intepreter? TIA From mwh at python.net Mon Jul 22 07:23:16 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 22 Jul 2002 11:23:16 GMT Subject: Lists & two dimensions References: Message-ID: asokanp at virtusa.com (Pichai Asokan) writes: > I am a trainer and in a training session a participant came up with a > problem that stumped me: > > Here is the code snippet that isolates what I want: > -------------------- > board = [[-1] * 3 ]*3 > print board > board[1][2] = 'x' > print board > -------------------- > Output > ----------------------- > [ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ] > [ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ] > ----------------------- > > I thought > board = [[-1] * 3 ]*3 > should give me a list of 9 elements; > but ... > > What is going on? I hope others have explained that. > Where can we read more to understand what is goingg on? This page: http://starship.python.net/crew/mwh/hacks/objectthink.html talks about a different problem, but may help. Cheers, M. -- To summarise the summary of the summary:- people are a problem. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From b.maryniuk at forbis.lt Wed Jul 10 05:31:18 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 10 Jul 2002 11:31:18 +0200 Subject: A better self Message-ID: <200207101131.18147.b.maryniuk@forbis.lt> On Wednesday 10 July 2002 00:51, Sean 'Shaleh' Perry wrote: > .size = .r + .l > is even worse. I still can't catch why people raise and reply to this really nonsense thread ("self" vs. "dot" or "this" or "pumpkin" or whatever)? Just go and design + develope your own language... This is more worse example, if somebody like use a dot, instead "self": .__.foo = .o .__.__doc__ = .__.foo.__doc__ This is more like Morse language... bo at oberon:(~) morse -s '.__.foo' .-.-.-, .-.-.-, ..-., ---, ---, What we will do if some Perl-hooked folk starts bite us "Use "->" instead ".", and use @$% symbols with variables": .$__->$foo = .$o .$__->$__doc__ = .$__->$foo->$__doc__ Damn!.. -- Sincerely yours, Bogdan M. Maryniuck "Whip me. Beat me. Make me maintain AIX." (By Stephan Zielinski) From LogiplexSoftware1 at earthlink.net Fri Jul 12 16:31:53 2002 From: LogiplexSoftware1 at earthlink.net (Cliff Wells) Date: 12 Jul 2002 13:31:53 -0700 Subject: Executing outside command In-Reply-To: <3YGX8.82020$eF5.2553773@twister.austin.rr.com> References: <3YGX8.82020$eF5.2553773@twister.austin.rr.com> Message-ID: <1026505914.3406.51.camel@software1.logiplex.internal> On Fri, 2002-07-12 at 13:26, David Noriega wrote: > How would I have python execute a command like ogg123? > David M Noriega > -- > http://mail.python.org/mailman/listinfo/python-list os.system() Cliff From rs at onsitetech.com Fri Jul 26 16:10:06 2002 From: rs at onsitetech.com (Robb Shecter) Date: 26 Jul 2002 20:10:06 GMT Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: <3D41AC9E.6080103@onsitetech.com> Alex Martelli wrote: > Britt A. Green wrote: > > >>So I know what lambda functions are, they're syntax and how they're used. >>However I'm not sure *why* one would use a lambda function. What's the > > > No idea, really. Maybe something to do with shocks in one's childhood. Well put - ( reminds me of many conversations I've had with many perl programmers over the years: substitute 'lambda' for one of any hundred _neat_ perl features :-). But to really answer you - I like lambdas and think lambdas can add clarity because their scope directly reflects their 'scope'. (Make sense?) Robb From brian at sweetapp.com Mon Jul 8 12:39:28 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 8 Jul 2002 09:39:28 -0700 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <1026117888.10684.43.camel@lestat.howden.press.net> Message-ID: <000601c2269e$09050f50$bd5d4540@Dell2> > OK, I apologise in advance for appearing dense. I've added the code > that was supplied by Brian, and the server script appears to run OK. > However, the client script displays the following error: > > Traceback (most recent call last): [snipped] > xmlrpclib.Fault: OK, it looks like the server is rejecting the client's IP address. > The server script: > > import sys, os, SimpleXMLRPCServer, string > > class AuthenticatingSimpleXMLRPCRequestHandler > (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): > def _dispatch(self,method,params): > self.UnknownIP = "UnknownIP" > if not (self.client_address == "144.178.234.189" or > self.client_address == "localhost" ): > raise self.UnknownIP, "Client IP Is Not Authorised" > else: 1. The IP check would be more readable if you wrote it like: if self.client_address not in ["144.178.234.189", "localhost"]: .... 2. For debugging purposes, try adding the following line: def _dispatch(self, method, params): + print 'client_address: %r' % self.client_address Then rerun your server and client to see why your server is rejecting your client's address. Cheers, Brian From SSchukat at dspace.de Mon Jul 22 09:56:18 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Mon, 22 Jul 2002 14:56:18 +0100 Subject: Python to Excell Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B239@PDC-DSPACE> Search for [PYTHON_ROOT]\Lib\site-packages\win32com\test\testMSOffice.py Stefan -----Original Message----- From: pixie888 at hotmail.com [mailto:pixie888 at hotmail.com] Sent: Monday, July 22, 2002 1:46 PM To: python-list at python.org Subject: Re: Python to Excell Thank you, Do you have any suggestion/clues on how to use that module, there is quite some functionality in it. Some sample code to get started would be great. I am not a very experienced programmer... Henk From walter at livinglogic.de Wed Jul 24 08:12:39 2002 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 24 Jul 2002 14:12:39 +0200 Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: <3D3E99B7.9000509@livinglogic.de> Alex Martelli wrote: > [...] > ...would you please share your uses for metaclasses? I can use > all the good examples I learn about -- it's hard to teach people > how to use metaclasses without actual motivation, and the more > real-life examples I can collect and quote, the more likely I > can help people achieve that motivation! The upcoming release of XIST (http://www.livinglogic.de/Python/xist/) has several uses of metaclasses (see http://www.livinglogic.de/viewcvs/index.cgi/LivingLogic/xist/_xist/xsc.py?rev=2.117.2.25&content-type=text/vnd.viewcvs-markup for the source code. The first example is a customized repr for nested classes, that shows the class nesting: class Base(object): class __metaclass__(type): def __new__(cls, name, bases, dict): dict["__outerclass__"] = None res = type.__new__(cls, name, bases, dict) for (key, value) in dict.items(): if isinstance(value, type): value.__outerclass__ = res return res def __repr__(self): return "" % (self.__module__, self.__fullname__(), id(self)) def __fullname__(cls): name = cls.__name__ while 1: cls = cls.__outerclass__ if cls is None: return name name = cls.__name__ + "." + name __fullname__ = classmethod(__fullname__) class foo(Base): class bar(Base): class baz(Base): pass print foo print foo.bar print foo.bar.baz this prints: Another example is the following: A base class implements a classmethod. Most subclasses that want to overwrite this classmethod want to implement a version which returns a constant value. Instead of defining: def method(cls): return constant method = classmethod(method) the subclass can simply say: method = constant and the metaclass will wrap this in an appropriate method. The metaclass looks like this: class __metaclass__(Base.__metaclass__): def __new__(cls, name, bases, dict): if dict.has_key("method"): method_value = dict["method"] if not isinstance(method_value, classmethod): def method(cls): return method_value dict["method"] = classmethod(method) return Base.__metaclass__.__new__(cls, name, bases, dict) There are several more examples in the code, but they are really application specific. Bye, Walter D?rwald From jonathan at onegoodidea.com Thu Jul 25 07:36:02 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 25 Jul 2002 12:36:02 +0100 Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <16Q%8.116512$Jj7.2728704@news1.tin.it> Message-ID: On 25/7/2002 11:07, in article 16Q%8.116512$Jj7.2728704 at news1.tin.it, "Alex Martelli" wrote: > If you think that supplying unrequested infrastructure is good, then > it's quite consistent that you like __call__. > > I prefer simplicity. "Do the simplest thing that can possibly work". > As you're showing, __call__ encourages tossing simplicity away. Hah. You've got me there :-) Yes, I believe in adding infrastructure that I know the-day-after-tomorrow, I'll be glad I did ;-) 'repr' is one of those things. I do a lot of work at the prompt and being able to examine objects is a critical part of that for me. In a similar vein I implement 'toString' for my Java classes as I do my Java testing and debugging from the Jython prompt. > It's peculiar that Python as it stands feels pretty good to people > with such totally divergent underlying philosophies of what software > development is all about. I guess, in a way, that's a tribute to > Python's pragmaticity. Warts such as N divergent ways to perform > a task (lambda, instance with __call__, closure, etc) will no doubt > remain due to both backwards compatibility constraints AND the > different constituencies pulling in opposite directions, helping > GvR to keep making his own decisions free from unbalanced "popular > opinion" push in one direction or another. Good thing, too:-). I guess we'll just have to agree to disagree on what counts as a "wart" and "rare and weird" ;-) Jonathan From cyberflash at netzero.net Mon Jul 15 23:40:56 2002 From: cyberflash at netzero.net (Flash Callahan) Date: Tue, 16 Jul 2002 03:40:56 GMT Subject: Fakes... References: Message-ID: approximately 6 billion(+or-6) of us fakes tend to disagree with your contention that you and your ally are the only self-aware sentient creatures on the planet. From spam at ob_scure.dk Mon Jul 8 19:51:34 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Tue, 09 Jul 2002 01:51:34 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7xwus7n5q4.fsf@ruckus.brouhaha.com> <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> <3D2A078A.7040502@ob_scure.dk> <06F2E275AA053281.30FCDA468DD949D2.9ED8D7E798995448@lp.airnews.net> Message-ID: <3D2A2586.5070302@ob_scure.dk> Cameron Laird wrote: > In article <3D2A078A.7040502 at ob_scure.dk>, > I call SQL noodling "scalable" in the sense that good > SQL queries can be hosted on bigger and bigger servers. > We know how to do that--it's a commercial reality. Ok, I understand. I think it's often a question of choosing the right tool for the job. Consider the following example: find the average of a series of values found in a table. Of course(?) doing a "SELECT AVG(value) FROM T_MyTable WHERE ..." would be much faster that retriving all the values and doing the calculations on the client/app-server side. However if, for some reason, the contents of T_MyTable was already in the clients memory (perhaps it was calculated there), calculating the average on the client would perhaps be faster. Be assured though, that for each calculation, both SQL and Python(/C++/VB or wathever it ends up being) solutions will be written and the fastest chosen. As it have been noted, the result might be that the SQL approach is the fastest, only time will tell. > I *like* distributed computing. I've spent much of the > last eighteen months promoting SOAP, XML-RPC, and CORBA. > Your mention of Linda and its descendants, including > T-Spaces, thrilled me. HOWEVER, I rarely recommend > distribution for performance objectives, for reasons > that have mostly appeared already in this thread. Com- > mercial applications (as opposed to scientific ones) > just don't find success that way. Well, you might be rigth, I don't know. I'm a little scared though about using SQL too extensivly. I might be too much of an SQL newbie, but there's just some stuff that's hard to write in (portable) SQL. For example I've done some quite fancy calculations using multiple "DECLARE CURSOR", etc in MSSQL. However, trying to run these thru MySQL is, well problematic. > Your situation might be an exception. It's hard to know. > The computations you describe--DB retrievals, elementary > statistics, ...--sound to me like ones that I've seen > most successfully hosted on conventional architectures. I think I'm currently planning on a 90% conventional with possibility of later expansion to distributed computing :-) The last 6 months I've been working almost exclusivly on a (commercial) project heavily based on SOAP (not for performance objectives though :-). That part really doesn't scare me :-) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From aleax at aleax.it Thu Jul 11 16:01:32 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 11 Jul 2002 20:01:32 GMT Subject: writing output to file References: Message-ID: Allan Wermuth wrote: ... > instead of writing the result to the screen, I would like to write output > to a another file. > > #!/usr/bin/python > for line in open('/etc/passwd').readlines() : > if line.strip()[0] == '#': continue > > temp = line.split(':') > if int(temp[2]) > 100 : > print "%10s %30s" % (temp[0], temp[4]) > > How can I do that? My personal suggestion: flout = open('/tmp/otherfile', 'w') for line in open('/etc/passwd').readlines() : if line.strip()[0] == '#': continue temp = line.split(':') if int(temp[2]) > 100: flout.write("%10s %30s\n" % (temp[0], temp[4])) flout.close() An alternative: flout = open('/tmp/otherfile', 'w') for line in open('/etc/passwd').readlines() : if line.strip()[0] == '#': continue temp = line.split(':') if int(temp[2]) > 100: print >> flout, "%10s %30s" % (temp[0], temp[4]) flout.close() As you see, the difference boils down to using a variant of the print statement (with the clause >> flout , to direct output elsewhere) versus using the write method of the file-object flout (which, differently from print, just takes whatever string you give it and puts it out to the file without alterations). My personal opinion is that print is good for simple quick & dirty output for debugging purposes, while using formatting operations to prepare strings and then the write method of file objects to emit them is the best way to go for "production" code. But, if you disagree, the >> flout , clause in the print statement lets you use the print statement to write to a file, too. Alex From mwh at python.net Fri Jul 26 06:27:50 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Jul 2002 10:27:50 GMT Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: Michael Hudson writes: > "David LeBlanc" writes: > > > I may be wrong about this, but I don't think regular expressions > > qualify as turing complete. No branching for one thing... > > Somewhere you can find a (perl) regexp that matches prime but not > composite numbers, I found it here: http://montreal.pm.org/tech/neil_kandalgaonkar.shtml and think it's sufficiently clever to post a link to. Here's it at work in Python: >>> def isprime(num, prog=re.compile(r"^1?$|^(11+?)\1+$")): ... return prog.match('1'*num) is None ... >>> isprime(10) 0 >>> isprime(13) 1 (you can see I got the above description slightly wrong) Cheers, M. -- Well, you pretty much need Microsoft stuff to get misbehaviours bad enough to actually tear the time-space continuum. Luckily for you, MS Internet Explorer is available for Solaris. -- Calle Dybedahl, alt.sysadmin.recovery From ajw126NO at SPAMyork.ac.uk Wed Jul 3 13:19:29 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Wed, 3 Jul 2002 18:19:29 +0100 Subject: SSE With Swig References: Message-ID: Just in case anyone else comes up against this problem, here's the solution. You need to override the new and delete operators so they use the _aligned_alloc and _aligned_free functions to align the _m128 variables on a 16 byte boundy. Andrew -- "Andrew Wilkinson" wrote in message news:uhs5g8hos5og51 at corp.supernews.com... > Hi, > > I'm trying to develop a Vector class that uses Intel's SSE extension. It > works very well when called using c or c++, but when I wrap the class with > Swig I get a privileged instruction exception error (this is under Windows > 2000 using MSVC++ 6sp5 with the processor pack installed). > > I've included the code below, any suggestions would be greatly appreciated > Andrew Wilkinson > > swig.i > %module Vector > %{ > #include "Vector.h" > %} > class Vector > { > public: > Vector(); > virtual ~Vector(); > Vector* operator+(const Vector *other); > float x; > float y; > float z; > float w; > }; > __ > vector.h > class Vector > { > public: > Vector(); > virtual ~Vector(); > > Vector* operator+(const Vector *other); > > __declspec(align(16)) union { > __m128 v; > struct { > float x; > float y; > float z; > float w; > }; > }; > }; > --- > vector.cpp > #include "Vector.h" > #include > > Vector::Vector() > { > x = 0.0f; y = 0.0f; z = 0.0f; w = 0.0f; > } > > Vector::~Vector() > { > > } > > Vector* Vector::operator +(const Vector *other) > { > Vector* r = new Vector; > > r->v = _mm_add_ps(v, (other->v)); // The exception occurs here. > > return r; > } > > -- > --- > Ditch The Decimal System! > Lets Use Hex - http://www.intuitor.com/hex/switch.html > > From raims at dot.com Fri Jul 19 17:44:51 2002 From: raims at dot.com (Rhymes) Date: Fri, 19 Jul 2002 23:44:51 +0200 Subject: Python 2.3 Message-ID: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> When Python 2.3 will be released? I've read the "what's new" and i'm waiting generators and true division :-) -- Rhymes rhymes at myself.com " ride or die " From gerhard.haering at gmx.de Sun Jul 7 20:37:42 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 8 Jul 2002 02:37:42 +0200 Subject: Getting IDLE 0.8 to recognize Pyhthon 2.2.1 In-Reply-To: <115W8.7627$Xg%.3561@news01.bloor.is.net.cable.rogers.com> References: <115W8.7627$Xg%.3561@news01.bloor.is.net.cable.rogers.com> Message-ID: <20020708003742.GA1944@lilith.my-fqdn.de> * Brad Fonseca [2002-07-08 00:28 +0000]: > Hi! > > I've upgraded to python 2.2.1 but when I start IDLE it still starts > Python 2.1.1. How do I get IDLE to start Python 2.2 Two possibilites. 1) Preferrable: Install the IDLE that comes with your Python 2.2.1. On Debian: apt-get install idle-python2.2. Other distributions like the KRUD RPMs from jafo available on python.org have idle in a seperate package (in python2-tools-2.2.1-1.i386.rpm, IIRC). 2) A little more hackish: Find your idle: "which idle". Then change the first line from #! /usr/bin/python to #! /usr/bin/env python2.2 Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 16.0 ?C Wind: 1.1 m/s From scrutinizer at gmx.at Wed Jul 24 14:23:09 2002 From: scrutinizer at gmx.at (Francesco S.) Date: Wed, 24 Jul 2002 18:23:09 GMT Subject: Which gui for slow (133 Mhz) pc References: <3d3b9eaa.7275472@news.utanet.at> <9Z%_8.3000$uh7.206@sccrnsc03> Message-ID: <3d3eefb4.4802490@news.utanet.at> On Mon, 22 Jul 2002 22:48:37 GMT, Jeremy Bowers wrote: >On Sun, 21 Jul 2002 06:46:21 -0500, Francesco S. wrote: > >> Hello, >> >> What gui can you recommend for my slow pc (win95). > >I've tried Python + (wxWindows, Tk, PyGTK) and a couple of others, too, >and they're all about the same in speed. Either learn to live with it (as >I have), or move to a non-interpreted environment, which has its own >problems. No, I don't like to turn back to compiled language :) (I can save the compiler waiting times and I like the concept of python) I just want to learn and write a few simple programs. Maybe I have to buy a new computer, this will be the best solution. > >Alternatively, you may be able to largely develop your app outside of the >GUI and just put a GUI together last... That is a good idea! Thanks and regards, -- Francesco From prema at prema.co.nz Sun Jul 21 04:18:40 2002 From: prema at prema.co.nz (Mike MacDonald) Date: Sun, 21 Jul 2002 08:18:40 GMT Subject: Accessing MS Outlook CDOs Message-ID: Hi All ! I'd be very interested in some tips on how to access the CDO's accessed through the MAPI interface to Outlook 2000. So far with mainly Mark Hammond's assistance plus a bit of common sense, I can access Message Subjects Message Count Message Text The one that I am really after at the moment is to understand how to access the raw html text of a mail message Does anyone have any ideas?? Please let me know if you want the snippets so far and I will post them Thanks in advance Mike From paul at prescod.net Wed Jul 24 13:48:27 2002 From: paul at prescod.net (Paul Prescod) Date: Wed, 24 Jul 2002 10:48:27 -0700 Subject: xml processing : too slow... References: Message-ID: <3D3EE86B.14C1AA4D@prescod.net> Alex Martelli wrote: > >... > Clearly not everybody agrees, or Paul Prescod, a great XML as well > as Python expert, wouldn't have developed xml.dom.pulldom, but then > I guess variety is the spice of life. I'm very used to thinking in > event-driven terms (the only way to go for GUI's, the fastest for > networks, the one supported by SGMLParser and HTMLParser too) so > SAX feels as comfortable as a pair of Mephisto shoes to me (I'd > wear no other brand under any condition I can imagine -- I don't > want my feet to hate me, after all). It is somewhat difficult to use an event-driven process when you already have a reason to structure your code in some way other than callbacks. For instance I was talking yesterday with a developer of Jabber. Based on what they get in a callback they may make a network call which might trigger another callback. My basic stance is that you should be able to use any control flow mechanism in your XML programs. Pull parsing allows that, push doesn't. -- Come discuss XML and REST web services at: Open Source Conference: July 22-26, 2002, conferences.oreillynet.com Extreme Markup: Aug 4-9, 2002, www.extrememarkup.com/extreme/ From mgilfix at eecs.tufts.edu Wed Jul 31 10:14:05 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 31 Jul 2002 10:14:05 -0400 Subject: Python equivalent to 'which'? In-Reply-To: ; from shalehperry@attbi.com on Tue, Jul 30, 2002 at 10:36:14AM -0700 References: <20020730132124.D7503@eecs.tufts.edu> Message-ID: <20020731101404.A26901@eecs.tufts.edu> On Tue, Jul 30 @ 10:36, Sean 'Shaleh' Perry wrote: > I wrote that in about a minute and a half. Yes, and I could hack together a version in a minute as well. But someone else couldn't. And it seems like a fairly common and useful function. A full implementation is another story. > Note it has a large assumption that PATH is defined and it is separated by > colons. This makes it only truly useful on a UNIX box. of course 'which' is a > UNIXism as well. My point is, the python library is for the most part OS > agnostic so I do not see this fitting in too well. I didn't mean for the function to go in as is. I meant the general functionality. Perhaps the starship version in the other thread is the best solution. -- Mike -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From jdhunter at nitace.bsd.uchicago.edu Thu Jul 18 11:21:55 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 18 Jul 2002 10:21:55 -0500 Subject: raw_input References: <3D36C5F1.9C966A8F@millfilm.co.uk> Message-ID: >>>>> "Eric" == Eric Texier writes: Eric> It's there anything better than raw_input to query a string Eric> input from the user in a console window. Thanks, Eric x = input('Enter a value: ') Your welcome, John Hunter From shalehperry at attbi.com Wed Jul 17 17:34:04 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 17 Jul 2002 14:34:04 -0700 (PDT) Subject: 'capwords' is not a string method In-Reply-To: Message-ID: On 17-Jul-2002 thehaas at binary.net wrote: > > Here is something I very recently discovered . . . "capwords" are not > included as a method of the string type, but "upcase" is: > my guess is the implementation for Unicode was not straight forward. Or perhaps they felt that not every method of the string library needed to be implemented on the new objects. From andreas at kostyrka.priv.at Fri Jul 26 02:49:39 2002 From: andreas at kostyrka.priv.at (Andreas Kostyrka) Date: 26 Jul 2002 08:49:39 +0200 Subject: setting the screen resolution In-Reply-To: <6edeb2ff.0207220845.86b6ebd@posting.google.com> References: <6edeb2ff.0207220845.86b6ebd@posting.google.com> Message-ID: <1027666178.8773.140.camel@vaio2> Am Mon, 2002-07-22 um 18.45 schrieb Chad Haynes: > i am currently working on a program using wxPython which requires the > screen resolution to be 1024x768. is there a way to set this from > python? Not really. Under Windows you might play around with the Win32 API, but under practically all other OSes this is not even possible. Andreas From pixie888 at hotmail.com Wed Jul 10 07:20:42 2002 From: pixie888 at hotmail.com (pixie888 at hotmail.com) Date: Wed, 10 Jul 2002 11:20:42 GMT Subject: Deriving from Exception References: <3d2bf4b6.183387921@news.skynet.be> Message-ID: <3d2c1758.192254296@news.skynet.be> On Wed, 10 Jul 2002 09:51:14 GMT, "Fredrik Lundh" wrote: >"pixie888 at hotmail.com" wrote: > >> I have some classes which derive from Exception, however in the >> __init__ function I do not call the __init__ function of Exception >> itself, allthough I think I should. The reason I don't do it is >> because I see that in all the tutorials about Python the tutors >> themselves don't do it either. >> >> Can anybody tell me why? > >The Exception baseclass provides an __init__ method which >takes all arguments and puts them in an args attribute. > >It also provides default __str__ and __getitem__ methods, >so you can print the exception, and use the v[x] notation >to access the members. > >In Python, the class would look something like this: > >class Exception: > > def __init__(self, *args): > self.args = args > > def __str__(self): > if not self.args: > return '' > elif len(self.args) == 1: > return str(self.args[0]) > else: > return str(self.args) > > def __getitem__(self, i): > return self.args[i] > >If this behaviour is fine for your exception subclass, there's >no need to override anything. Example class CMyException(Exception): def __init__(self,ID): self.ID = ID I do NOT call the __init__ function of Exception in the __init__ function of CMyException: how does that relate to the explanation you gave above? Will those args (what are they anyway, is args a reserved word?) be copied then? I tought that *not* calling the __init__ of Exception in the __init__ of CMyException resulted in not running the code provided in that base __init__ function. Did I miss something here? > > > > From derek at wedgetail.com Fri Jul 5 04:46:20 2002 From: derek at wedgetail.com (Derek Thomson) Date: Fri, 05 Jul 2002 08:46:20 GMT Subject: sprites in Tkinter? References: <3D2463B3.A7CA6E1D@ipm.fhg.de> Message-ID: <3D255CDA.9030908@wedgetail.com> Markus von Ehr wrote: > Hi out there, > > is there a possibility to create some sort of sprites in TkInter? > Try moving objects around on a Canvas. Regards, Derek. From jepler at unpythonic.net Thu Jul 11 19:43:22 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 11 Jul 2002 18:43:22 -0500 Subject: pygame question In-Reply-To: References: Message-ID: <20020711184316.A1008@unpythonic.net> On Thu, Jul 11, 2002 at 05:58:18PM -0500, Michael Bauers wrote: > I was curious as to why 'is K_SPACE' worked, but 'is K_r' did not. I had to > change the test for 'r' to ==. > > * code snippet * > elif (event.type is KEYDOWN and event.key is > K_SPACE): > # DO SOMETHING > elif (event.type is KEYDOWN and > event.key == K_r): > # DO SOMETHING ELSE If these are just ints, you should use ==, not 'is'. 'is' will work sometimes, and more often for small positive ints (they're special). >>> x = 1000 >>> x is 1000 0 >>> x = 1 >>> x is 1 1 Jeff From justin at iago.org Tue Jul 9 12:03:07 2002 From: justin at iago.org (Justin Sheehy) Date: Tue, 09 Jul 2002 12:03:07 -0400 Subject: 8 Queens Problem References: <00172807.C22236@smiths-aerospace.com> Message-ID: Simon.Foster at smiths-aerospace.com writes: > Would this solution qualify as tail-recursive? Yes. The only recursive call that you make is in tail position. (Not that it matters even the slightest bit in Python, of course.) > What's a closure? A closure is a function body together with an environment giving values for the function's free variables. In other words, a function's definition combined with the relevant part of the environment in which it was defined. > A continuation? A continuation is a representation of the future of a computation. If I leave you with just that definition, though, you probably won't be much better off than when you started, so... At any given time in program flow, the current continuation can be thought of as "the rest of the program", with a hole in it for the thing currently being executed. For instance, in the code segment: f(g(x)) g's continuation could be thought of as being f(_) where "_" is to be filled in when the continuation is run. Think of your continuation as a function of one argument that will take your return value as its argument. It represents everything that will happen in the program onward from the time that you return. Even in languages that provide the programmer with direct access to continuations, it is rare for continuations to be used directly for something other than implementation of a scheduling system or a new control-flow construct. However, implementing such things can be pretty cool. Some of the sorts of things that can be done with continuations: backtracking coroutines threading systems generators cross-tree searches recursion exits If you get really interested in continuations for some reason, you should probably read up on the papers produced by all of the Scheme folks at or from the University of Indiana over the past 20 years. (Dan Friedman, Mitch Wand, Will Clinger, Kent Dybvig, Chris Hanyes, Bruce Duba, Eugene Kohlbecker, Matthias Felleisen...) Enjoy, have fun, and good luck. -Justin From charleshixsn at earthlink.net Tue Jul 9 14:48:01 2002 From: charleshixsn at earthlink.net (Charles Hixson) Date: Tue, 09 Jul 2002 11:48:01 -0700 Subject: Why self? References: <3D2A07DE.10303@onsitetech.com> Message-ID: Alex Martelli wrote: > Robb Shecter wrote: > > >>Brian Quinlan wrote: >> >>>... Actually, private instance >>>variables are uncommon in general. >> >>Sounds like a difference in design philosophies. In my code, private >>everything is the norm, with a very thin/small public API. ... > Alex > If you are subclassing a class that someone else has written, you don't want to accidentally redefine an internal name. Sorry. I can accept that you should be able to explicitly access it, but to be able to change it by accident is (would be?) a misfeature. I didn't believe that this happened in Python. It does, and it seems a significant flaw. My understanding is that if you define a variable in a class that subclasses another class, then unless you take definite steps to cause things to happen otherwise, you are defining a new variable that is local to the scope of the class that you are currently defining, and will not impact routines that you call from parental classes. Experiment shows that this isn't what happens. from __future__ import nested_scopes does not fix this problem, as I assumed that it would. Let's be explict: from __future__ import nested_scopes class A: def ma(self): print "ma, ma" def pa(self): self.ma() class B(A): def ma(): print "hello, world" tst = B() tst.pa() Testing this produces the message, "hello, world" This seems to be the wrong message. The version of pa that was called was the version defined in class A, so the routine called should have been the routine defined in class A. Or, to me more accurate, for libraries to have maximal portability, I would want the message to have generated "ma, ma", and I had been assuming that nested_scopes would result in that being the message that was produced. -- -- Charles Hixson Gnu software that is free, The best is yet to be. From aleax at aleax.it Tue Jul 9 11:38:41 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 15:38:41 GMT Subject: sorting many arrays from one... References: Message-ID: <5sDW8.60685$vm5.2202022@news2.tin.it> Shagshag13 wrote: > > "Alex Martelli" > > it's ok for everything. but i should have writed DISK storage :o) that's > why i use the int id - string mapping... If your string are so many that you need to hold them on disk, then a memory-based string<->id map will still be of no use. bsddb, gdbm or some relational DB may be closer to what you want! Alex From justin at iago.org Wed Jul 10 11:37:20 2002 From: justin at iago.org (Justin Sheehy) Date: Wed, 10 Jul 2002 11:37:20 -0400 Subject: 8 Queens Problem In-Reply-To: (Jonathan Hogg's message of "Tue, 09 Jul 2002 18:08:28 +0100") References: <00172807.C22236@smiths-aerospace.com> Message-ID: Jonathan Hogg writes: > I'd say no - because the algorithm relies on continuing execution after > return of the recursive call (the outer for loop continues). True. Oops. -Justin From aleax at aleax.it Wed Jul 24 04:34:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 24 Jul 2002 08:34:33 GMT Subject: A better self References: Message-ID: Michael Chermside wrote: ... > shouldn't be using Python. Yes, Python is a nice language, and yes, it > can be sped up by recoding key portions of an application in C/C++, but > it is never going to be as fast as an algorithm hand coded in assembly. It may happen to be just as fast (that would be a rare coincidence) and it may well be (more likely:-) *much faster*. That's because more often than not you won't be coding the SAME algorithm in Python or assembly. In the time it takes you to code and debug the one algorithm in assembly, you've been able to invent and try a dozen different ones in Python, and quite likely come up with one that beats the pants off the one you first thought of. The fallacy of thinking that "coded in Python" means "slower than if coded in assembly" comes from the unspoken assumption that the program will have exactly the same structure in both cases. Most often, it won't. A similar fallacy is frequent in laypeople's economics thoughts, and known for example as "the fallacy of the lump of labor" -- where some people intuitively think that (e.g.) immigrants "steal jobs from natives". The fallacy here comes from imagining that there's a predefinite, fixed, total amount of things to do, a pie of a fixed size, and all that matters is how the pie is sliced up. Reality just doesn't work that way. The pie can grow (or shrink due to restrictive protectionist legislation), better algorithms can be and are devised and deployed. Only when you're SURE you have the best possible algorithms (and the most perfect, developed economy) and you're STILL too slow (or, still too poor) should coding in lower levels be considered (on the other hand, protectionist legislation shouldn't be considered even then, but that's another issue:-). Alex From rs at onsitetech.com Wed Jul 3 14:09:14 2002 From: rs at onsitetech.com (Robb Shecter) Date: 03 Jul 2002 18:09:14 GMT Subject: GoTo considered missing References: Message-ID: <3D233D8C.2030104@onsitetech.com> David LeBlanc wrote: >...if you're writing python > code that uses nested loops like that, it's possible you're not taking good > advantage of Python's features. Care to share what you're working on?... I'd like to know too. I can't really think of an example where I'd need a goto statement. Robb From jdhunter at nitace.bsd.uchicago.edu Tue Jul 16 15:55:40 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 16 Jul 2002 14:55:40 -0500 Subject: map del efficiency python2.2 and 2.1 References: Message-ID: >>>>> "Jonathan" == Jonathan Hogg writes: Jonathan> Ignoring the numbers, how does the program actually seem Jonathan> to you? With the runtime in the region of 10 to 27 Jonathan> seconds you should be able to gauge where the time is Jonathan> going by just counting in your head as it runs. Does it Jonathan> look like it's spending many seconds finishing up? Thanks for the detailed info on the time output. I was referring to the wall clock time and yes, the script does just sit there and tick away doing nothing after the last print statement before my prompt returns. I cleared up one mystery. The reason my CPU % usage was so low is that I was running the script on an NFS client and some of the lost time was due to the executable loading over the network. But I still can't explain why I am seeing the difference between 2.2 and 2.1 with the script, which happens whether or not I run it on the NFS server or client (and when running on the server I get near 100% CPU usage). There is still an 8s differential that is tacked on at the end of the 2.2 run. As I pointed out to Alex, it clearly is related to how 2.2 is deleting the map, because the 2.1-2.2 difference disappears simply by adding 'del m' to the end of my script. Warning! Masochists only need continue reading. Here are some more results from the wild and wonderful 2.1 vs 2.2. I have modified the script to do the deletions explicitly and report times. I'm also running on the NFS server. All these numbers are repeatable and do not reflect some oddness on an individual run since I am getting near 100% CPU usage # With the del m, no difference between 2.2 and 2.1 mother:~/ox2/test> time python2.1 test_allwords.py Read len 1712676 seq: 1.820s Loaded map with 856338 keys: 4.740s Deleted map: 0.280s 6.680u 0.770s 0:07.45 100.0% 0+0k 0+0io 299pf+0w mother:~/ox2/test> time python2.2 test_allwords.py Read len 1712676 seq: 1.880s Loaded map with 856338 keys: 4.510s Deleted map: 0.250s 6.460u 0.780s 0:07.30 99.1% 0+0k 0+0io 350pf+0w # Comment out the del m line, big difference between 2.2 and 2.1 mother:~/ox2/test> time python2.1 test_allwords.py Read len 1712676 seq: 1.850s Loaded map with 856338 keys: 4.730s 6.690u 0.770s 0:07.46 100.0% 0+0k 0+0io 299pf+0w mother:~/ox2/test> time python2.2 test_allwords.py Read len 1712676 seq: 1.870s Loaded map with 856338 keys: 4.520s 14.480u 0.810s 0:15.28 100.0% 0+0k 0+0io 350pf+0w # Now let's get really weird. Add a 'del seq' and comment out 'del # m'. Python 2.1 now craps out! mother:~/ox2/test> time python2.1 test_allwords.py Read len 1712676 seq: 1.820s Loaded map with 856338 keys: 4.780s Deleted seq: 0.200s 14.610u 0.880s 0:15.57 99.4% 0+0k 0+0io 299pf+0w mother:~/ox2/test> time python2.2 test_allwords.py Read len 1712676 seq: 1.880s Loaded map with 856338 keys: 4.500s Deleted seq: 0.200s 14.550u 0.770s 0:17.73 86.4% 0+0k 0+0io 350pf+0w What is bizarre about this is that the addition of the del seq line to the script causes this 8s lag between the last print and the end of the program in 2.1 Here then is the synopsis (excluded runs where %CPU < 99%) 2.1 2.1 2.1 2.1 del m yes yes no no del seq yes no yes no run time 7.9s 7.6s 15.4s 7.4s 2.2 2.2 2.2 2.2 del m yes yes no no del seq yes no yes no run time 7.6s 7.24s 15.6s 15.4s OK, I'll stop torturing you and me now. John Hunter import time class Timer: """Record events and how long it takes. The time between event is recorded""" def __init__(self): self.last = time.clock() self.events = [] def event(self, s): now = time.clock() self.events.append( (s, now - self.last) ) self.last = now def __repr__(self): s = '' for event in self.events: s += '%s: %1.3fs\n' % event return s timer = Timer() file = '/home/jdhunter/ox2/meta/allwords.dat' fh = open(file, 'r') s = fh.read() seq = s.split() timer.event('Read len %d seq' % len(seq)) m = {} for i in xrange(0,len(seq),2): m[seq[i]] = int(seq[i+1]) timer.event('Loaded map with %d keys' % len(m.keys())) # these are the del seq and del m lines that I commented or #uncommented for the table above del m timer.event('Deleted map') del seq timer.event('Deleted seq') print timer, From wweexxsseessssaa at telusplanet.net Mon Jul 1 10:17:08 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Mon, 01 Jul 2002 14:17:08 GMT Subject: Q: Status of MySQL & Python? References: <69hvhu4otkrcncmu0d4vudfhv74o7maiul@4ax.com> Message-ID: <1oo0iugee4uaijc36s0o4kulqe32s825r5@4ax.com> On Mon, 1 Jul 2002 06:59:34 +0200, Gerhard H?ring wrote: >...Did you really execute MySQL-python-0.9.1.win32-py2.2.exe (replace 2.2 >as appropriate), didn't you?... I suspect my brain had gone mushy by the end of yesterday, and I may have missed doing something. I'm going to help a friend with a plumbing problem and won't get back to this until the evening, but I find tht working in another domain helps to clear the mind. Thanks again for the latest info, and I will report back. -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From StRanGy at cna2.kav.vest.hr Fri Jul 26 03:59:14 2002 From: StRanGy at cna2.kav.vest.hr (Ivica) Date: 26 Jul 2002 07:59:14 GMT Subject: Detecting pipe on stdout? -- col References: Message-ID: On Wed, 24 Jul 2002 13:01:07 -0500, DIG wrote: > Hi, Alexander Schreiber ! > > On Wed, Jul 24, 2002 at 02:32:17PM +0000, Alexander Schreiber wrote: > > [...] >> Is there any way for a Python program to detect wether its stdout has >> been redirected to a pipe/file (like "./programm | less")? I've didn't >> find anything about this in the FAQ and failed to come up with the right >> search terms for google. >> >> Reason: I've got a Python program[0] here which normally colorizes its >> output (to the terminal) using escape sequences. This is fine and nice >> while running on a terminal, but when running the program with less >> attached to it the escape sequences are annoying. Ideally, I want to >> detect a pipe attached to stdout and switch of the color (the flag is >> already there) in this case. > > It is not EXACT answer to your question, but I hope this could help you to solve your problem: you could use ``col'' command (if you are using Linux). > > From ``man col'': > [...] > col - filter reverse line feeds from input > [...] > All unrecognized control characters and escape sequences are discarded. > [...] > > So, you could use it like this: > > $ program | col | less Why not do a program | less -R R stand for R Repaint screen, discarding buffered input. From pyth at devel.trillke.net Tue Jul 16 09:18:30 2002 From: pyth at devel.trillke.net (holger krekel) Date: Tue, 16 Jul 2002 15:18:30 +0200 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: ; from huaiyu@gauss.almadan.ibm.com.trillke.net on Mon, Jul 15, 2002 at 06:04:05PM +0000 References: <3D2E1793.8030600@jerf.org> <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <20020716151830.A10625@prim.han.de> Huaiyu Zhu wrote: > holger krekel wrote: > >Huaiyu Zhu wrote: > >> Readability for machines does not have to come at the expense of readability > >> for humans. A few years back I experimented with an indentation based data > >> format that is: > >> > >> - as readable as emacs's outline mode > >> - reduce to common conventions like this paragraph for simple cases > >> - allow mixed nested structures of set, sequence, dictionary, and seqdict > >> - can include binary data > >> - can handle different encodings/encryptions in different elements > >> - with average less than 5% bloat, in contrast to XML's over 100% bloat > > > >do you have any code or design documents for this? > > > >Sounds quite interesting. > > The basic idea is quite simple: consider a data structure as a tree; denote > the type of branching at each node; indent the subtrees. It appears to me > that indentation is easier to handle than quotes and escapes. Here's a > simple example: > > ...snipped... > > OK, hope this makes sense. It does and it's very interesting. It does sound a lot like http://yaml.org to me, though (They even have an RFC). Don't you think YAML might be a superset of your ideas? Let me add some random thoughts/questions about your/yaml's scheme (i hope i am not missing something obvious): - how is a binary data-stream's size determined? What about open-ended streams? Embedding of arbitrary data-streams is very useful (IMO). - somehow your and yaml's scheme remind me of todays wiki techniques. E.g. Wikis have methods of sequence-detection (bullets ...) and they have a commitment to readability. Of course, they are generally more concerned with graphical views than with beeing a concise persistence scheme. - Is there a canonical conversion between XML and your scheme/YAML? Shouldn't be too hard, anyway... - how do you express external addresses akin XPATH? Ideas: - Mappings are easy, just take the 'key'. - Sequences are easy (take the sequence number) but not very robust to deletions and insertions of items. - tag-names (IDs) which can be associated with any item might be interesting. readability is likely to suffer, probably. btw, I wonder whether some form of your and/or YAML's ideas should play a role in the new persistence-SIG. While the actual persistence mappings are not in the focus there are certainly some interesting connections between the two areas. > If this is still interesting I'll dig the thing > out. I have documents and code (perl and python) at home, but I'll have to > ... this sure is useful. Especially for me since i work with a (perl-) friend on a project which needs to address the persistence-question. And we want to have it interoperable, simple and fast. I guess looking at YAML might avoid that you have to dig too much into old harddisks :-) holger From erno-news at erno.iki.fi Tue Jul 23 03:18:24 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 23 Jul 2002 10:18:24 +0300 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> Message-ID: In article <7xu1mr7jmr.fsf at ruckus.brouhaha.com>, Paul Rubin writes: | Does that reasoning not also apply to class instances? Why should | class instances be callable through the __call__ method? you have to use __call__ (and not pass a bound method) when you pass something out as a callback, but still want to be able to do other things with the object when you get one back. in most other situations it is better to just use a normal method, in my opinion. -- erno From mgerrans at mindspring.com Wed Jul 10 01:42:33 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 9 Jul 2002 22:42:33 -0700 Subject: Which OS? References: Message-ID: I suppose you are running PythonDos on DOS and regular Python on Windows, but for some reason don't know which you are running at runtime. I think sys.platform will be adequate in your case, but here are a couple other tricks, for good measure: If you try to import any of the win32 extensions on windows, then that should tell you; something like this: inPlainOldDos = 1 try: import win32ui inPlainOldDos = 0 except: win32ui.MessageBox( 'You are not running on Windows and your script has just crashed.') (sorry, I couldn't resist: of course you will do something intelligent in the exception handler, unlike me) Another thing you can do is check for the 'windir' environment variable: import os if 'WINDIR' in os.environ: doWindowsStuff() else: doDosStuff() > ... Any form of reproduction, or further dissemination of this > email is strictly prohibited. Oh my, sounds like Google and a lot of other web-crawlers -- not to mention servers in general -- are in big trouble now! From cliechti at gmx.net Fri Jul 26 06:13:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 26 Jul 2002 12:13:01 +0200 Subject: python class question References: Message-ID: Jonathan Hogg wrote in news:B966BE75.E94D%jonathan at onegoodidea.com: > On 25/7/2002 19:38, in article > Xns9256D2197BD87cliechtigmxnet at 62.2.16.82, "Chris Liechti" > wrote: > >>> class xrml(SimpleItem.SimpleItem): >>> def init_db(self): >>> try: >>> dbc = getattr(self, connection) >> >> why not: >> dbc = self.connection > > Because that won't work. Look again at the code above. It gets an > attribute of self with the *name* stored in 'connection'. oh, you're right. sorry to the OP. and it wasn't that late when i wrote that... chris -- Chris From gerhard.haering at gmx.de Tue Jul 9 05:49:38 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 9 Jul 2002 11:49:38 +0200 Subject: [OT] Corrections about Java In-Reply-To: <200207091137.11467.b.maryniuk@forbis.lt> References: <96c7f32.0207081518.52ea644a@posting.google.com> <200207091041.07136.b.maryniuk@forbis.lt> <20020709090857.GA1413@lilith.my-fqdn.de> <200207091137.11467.b.maryniuk@forbis.lt> Message-ID: <20020709094938.GA1489@lilith.my-fqdn.de> * Bo M. Maryniuck [2002-07-09 11:37 +0200]: > [Java sucks] > For example, this goes loop forewer: > > for (;;) { > try { > break; > //^^^^^ > continue; > } finally { > lalala... > } > } Works for me. gerhard at lilith:~$ java -showversion java version "1.3.1" Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1) Classic VM (build 1.3.1, J2RE 1.3.1 IBM build cxia32131-20020302 (JIT enabled: jitc)) Btw. Python had a similar problem in 2.0, IIRC. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fredrik at pythonware.com Mon Jul 1 07:32:21 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 11:32:21 GMT Subject: private References: Message-ID: <95XT8.14068$p56.4577943@newsb.telia.net> Bjorn Pettersen wrote > After all, if you can't trust your developers you have bigger > problems. especially if they're named Machiavelli. double underscores are more than enough to deal with that Murphy guy... From vraghavan at cnmnetwork.com Wed Jul 31 21:47:09 2002 From: vraghavan at cnmnetwork.com (Srivatsan Raghavan) Date: 31 Jul 2002 18:47:09 -0700 Subject: clarification on previous post Message-ID: <7b6e2177.0207311747.52942d47@posting.google.com> i'd like to clarify on my previous post regarding embedding of python in C++ i would actually prefer to call a function in a script , and pass it a parameter of an object that's not a python builtin type .. in the Logging module ( that maps to a namespace in C++ ) i have a class called LogEvent, i tried a hack by trying to use a global & have an accessor function called GetCurrentLogEvent() that gets exposed to python this is well, a hack and clearly suboptimal .. and per my previous post isn't working :/ in addition to my previous problem with regard to calls that work from the commandline but not from embedded call, can someone tell me how i can pass an object (or a copy of an object) that i've got in a C++ function, and send that to a python script .. --vat vraghavan at cnmnetwork.com From fperez528 at yahoo.com Mon Jul 8 21:57:41 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 08 Jul 2002 19:57:41 -0600 Subject: Generic vector aggregates References: Message-ID: Ingo Blank wrote: > > Q:??How?can?I?refer?to?the?built?in?arithmetic?operators?"+","*"?etc. > This?would?save?the?additional?dispatching?step,?without?the?need?to look up the special __names like __add__, __mult__, etc. Here's the output for an integer: In [19]: x=4 In [20]: x.__ x.__abs__ x.__hash__ x.__or__ x.__ror__ x.__add__ x.__hex__ x.__pos__ x.__rpow__ x.__and__ x.__init__ x.__pow__ x.__rrshift__ x.__class__ x.__int__ x.__radd__ x.__rshift__ x.__cmp__ x.__invert__ x.__rand__ x.__rsub__ x.__coerce__ x.__long__ x.__rdiv__ x.__rtruediv__ x.__delattr__ x.__lshift__ x.__rdivmod__ x.__rxor__ x.__div__ x.__mod__ x.__reduce__ x.__setattr__ x.__divmod__ x.__mul__ x.__repr__ x.__str__ x.__doc__ x.__neg__ x.__rfloordiv__ x.__sub__ x.__float__ x.__new__ x.__rlshift__ x.__truediv__ x.__floordiv__ x.__nonzero__ x.__rmod__ x.__xor__ x.__getattribute__ x.__oct__ x.__rmul__ Many of those special methods are what really gets called when binary operators are applied to integers. The docs have more details. cheers, f. From python at experimentzero.org Fri Jul 26 12:59:28 2002 From: python at experimentzero.org (Britt A. Green) Date: Fri, 26 Jul 2002 09:59:28 -0700 Subject: Let's Talk About Lambda Functions! References: <20020726024901.2725.176.Mailman@mail.python.org> Message-ID: <016201c234c5$cf5793a0$5f01000a@opentable.com.ot> So I know what lambda functions are, they're syntax and how they're used. However I'm not sure *why* one would use a lambda function. What's the advantage that they offer over a regular function? Britt -- "My mom says I'm cool." From noone at here.invalid Mon Jul 8 01:13:28 2002 From: noone at here.invalid (JohnJacob) Date: Mon, 8 Jul 2002 00:13:28 -0500 Subject: idiots guide to python References: <626290cd.0207051529.518f4ce7@posting.google.com> Message-ID: "Mike Johnson" wrote in message news:626290cd.0207051529.518f4ce7 at posting.google.com... > I am starting an A-Level course in computing in september, and i will > need to learn how to use python. I have no previous experience of > programming, but could anyone point me in the direction of an "Idiots > Guide"? > > thanks. > > Mike Johnson 'Learn to Program Using Python' by Alan Gauld[1] teaches programming and uses Python as its language of choice. Note that I have never read this book, but it sounds like what you're looking for. One I have read is 'Programming Python' by Mark Lutz[2]. Once you get a footing in Python, this book will let you...take big strides? That was a lame analogy, but you know what I mean. I really like this one. Good luck, greg [1]http://tinyurl.com/l7g [2]http://tinyurl.com/l7o From spam07 at kuwest.de Mon Jul 29 10:33:32 2002 From: spam07 at kuwest.de (Jens Kubieziel) Date: Mon, 29 Jul 2002 16:33:32 +0200 Subject: What is a glue language? Message-ID: Hi all, the word 'glue language' is mentioned in the FAQ. I have no clue :-) what this could mean. Could someone explain this (also a german translation is appreciated)? TIA -- Jens Kubieziel Das Problem ist heute nicht die Atomenergie, sondern das Herz des Menschen. Einstein, Albert From fan_jacob at hotmail.com Fri Jul 5 12:45:38 2002 From: fan_jacob at hotmail.com (Fan Guanping) Date: 5 Jul 2002 09:45:38 -0700 Subject: possible bug of parser.suite Message-ID: <79e3000a.0207050845.faba950@posting.google.com> parser.suite seems broken at least in Python '2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)]'. Is this a bug,or I use it incorrectly? >>> parser.suite('class Abc:pass') >>> parser.suite('class Abc:\n def hello(self):\n pass') Traceback (most recent call last): File "", line 1, in ? parser.ParserError: could not parse string From aleax at aleax.it Mon Jul 8 17:50:06 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Jul 2002 21:50:06 GMT Subject: Embedding: how to extend a C++ instance by Python methods References: <878dc260.0207080613.3d6aca81@posting.google.com> Message-ID: Renzo Tomaselli wrote: ... > A key point is that I want users to be able defining just method > bodies, not to play around with entire modules. For this reason I > would like to implement the housekeeping details in C++ as much as > possible. This second sentence does not follow from the first. You can perfectly well implement all housekeeping details in Python (and make your life substantially simpler thereby) without burdening your users with having to do anything more than "adding method bodies". > What I miss here is about creating callable objects from these stored > declarations, so that they can be added to instances and invoked on > the fly. Executing (in a specific 'local' dictionary, and possibly after prepending 'def ' or whatever you don't want the users to have to type) the declarations will give you the function objects. Adding them to instances (rather than types or classes) is one possibility, which will work to some extent, but not without problems -- you'd need to set up a closure and play some dirty tricks to get the 'self' passed in. Simplest is always to add to a class -- as long of course as the later invocation is also done from Python -- possibly an otherwise empty subclass built on the fly just for the purpose, if need be. Alex From ianb at colorstudy.com Thu Jul 18 11:29:08 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 18 Jul 2002 10:29:08 -0500 Subject: Python robot web client? In-Reply-To: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> References: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> Message-ID: <1027006148.692.83.camel@lothlorien.colorstudy.net> WebUnit has HTTPSession, which does the persistent cookies, though no parsing. On Thu, 2002-07-18 at 02:30, Paul Rubin wrote: > Are there any Python robot web clients around, sort of like Perl LWP? > I mean something fancier than urllib, that parses the HTTP headers and > remembers any cookies. It would also be great if it parsed the HTML > enough to find the form fields, links, and so forth. I guess I can > implement what I need, but thought I'd ask first if something like > it is already available. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list From talsit at talsit.org Sun Jul 7 02:31:27 2002 From: talsit at talsit.org (tALSit) Date: Sun, 7 Jul 2002 16:31:27 +1000 Subject: Crash boom, why? Message-ID: <3d27d736@dnews.tpgi.com.au> Hi, I'm doing some python/c++ integration, and i've come across a problem that has nothing to do with c++. I've got a couple of scripts, and I want python to execute them. I execute them with the builtin command "execfile" with just the name of the script as a parameter. I have two scripts, one of them executes perfectly fine, and the other one only has 2 lines (calls to c++ objects). But the thing is that if I exec the script, python crashes, but if i copy and paste the contents of the script inside the python interpreter, it works fine! Is execfile () the way to go around when I want to exec a script? Are there limitation to be taken into account with that function? Thanks for all! // talsit From roy at panix.com Sun Jul 28 11:21:17 2002 From: roy at panix.com (Roy Smith) Date: Sun, 28 Jul 2002 11:21:17 -0400 Subject: How to detect the last element in a for loop References: <3D4388C8.6040005@nowhere.org> <49S09.13011$9U4.7618@nwrddc01.gnilink.net> Message-ID: Tom Verbeure wrote: > say, 10 lines of code. Too much to duplicate it outside the loop, not > enough for a separate function... Why is 10 lines of code not enough for a separate function? I use functions to group code into conceptual blocks that can be thought about and understood as a unit. Sometimes that block is 100 lines of code, sometimes it's 3 or 4 lines. I've even written one-line functions. Whatever makes sense to factor out as an atomic unit. Line count has little to do with it. I'm not quite as rabid about it as the XP'er are with "Refactor Mercilessly", but (like so much with XP) the basic idea has merit if you don't try to be too extreme about it :-) From b.maryniuk at forbis.lt Tue Jul 9 07:08:04 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 9 Jul 2002 13:08:04 +0200 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <20020709103758.GC1792@lilith.my-fqdn.de> References: <200207091218.50549.b.maryniuk@forbis.lt> <20020709103758.GC1792@lilith.my-fqdn.de> Message-ID: <200207091308.04503.b.maryniuk@forbis.lt> On Tuesday 09 July 2002 12:37, Gerhard H?ring wrote: > gerhard at lilith:~$ time java nothing # IBM JDK 1.3.1 > > real 0m0.651s > user 0m0.560s > sys 0m0.110s Cool time for _nothing_. BTW, can You "cat nothing.java" here? How much lines that "nothing" took? bo at toaster:(~) time python -c '' real 0m0.058s user 0m0.030s sys 0m0.000s Emmm... I remember, You asked me antique car. ;-) See this: *bo at sfas:(~) time python -c '' real 0m0.384s user 0m0.330s sys 0m0.060s *bo at sfas:(~) cat /proc/cpuinfo processor : 0 model name : Pentium 75 - 200 cpu MHz : 149.696 *bo at sfas:(~) java bash: java: command not found > Once you use lots of classes, there are some problems with startup time. > Because of bytecode verification and all that. Actually, this "problem" seems to be in Python too, especially if You use same antique car, like my P75 with 150 mhz. > Oracle developers apparently have no clue about > 1) Writing installers. > 2) Writing client-side Java that doesn't look crappy and actually works. Yes, that's right. Here I fully agree with You. Anyway, let us both to shutdown this nonsence thread. :) -- Sincerely yours, Bogdan M. Maryniuck "It's God. No, not Richard Stallman, or Linus Torvalds, but God." (By Matt Welsh) From ralphc at bellsouth.net Sun Jul 7 15:06:20 2002 From: ralphc at bellsouth.net (Ralph Richard Cook) Date: Sun, 07 Jul 2002 19:06:20 GMT Subject: VisAD/Jython or PyOpenGL for 2D/3D cellular automata? Message-ID: <3d28904f.1941722@news.atl.bellsouth.net> I'm plowing through Stephen Wolfram's 'A New Kind of Science' and would like to make some 3D cellular automata. Since this is a fun project for me I want to use Python since it's a fun language, right? :) Looking around I see two main alternatives, VisAD with Jython or PyOpenGL. I was wondering what experience people had with either of these packages, either good or bad, and if they had any insights as to which would be better suited for this, not making static pictures but "winding up" the cellular automata and letting the graphs change with time, adding and deleting cells, etc. Thanks, Ralph From marklists at mceahern.com Tue Jul 30 11:39:00 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 30 Jul 2002 10:39:00 -0500 Subject: How to find out if february has 29 or 28 days ? In-Reply-To: <5.1.1.6.0.20020730120725.009f2610@imap.datacraft.com.br> Message-ID: > I use the mx.DateTime package, and I need to know if in one > particular year > has a february with 28 or 29 days ? I don't know how to do that ! import mx.DateTime d = mx.DateTime.DateTimeFrom("2/1/2002") print d.days_in_month == 28 d2 = d + mx.DateTime.RelativeDateTime(years=2) print d2.days_in_month == 29 // m - From logiplexsoftware at earthlink.net Wed Jul 3 14:47:14 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 3 Jul 2002 11:47:14 -0700 Subject: HT clear some wxPython fram? In-Reply-To: References: <20020703110607.00c02458.logiplexsoftware@earthlink.net> Message-ID: <20020703114714.47419520.logiplexsoftware@earthlink.net> On Wed, 03 Jul 2002 20:36:34 +0200 Klaus Reinhardt wrote: > Am 03.07.02 20:06:07, schrieb Cliff Wells : > >> >> HOW I CAN CLEAR SOME FRAME? > Hi > > 1.) Thank you very much, it's now working with > the changes ### I made (s.b.) > 2.) A further question: How can I change the font > to equal spacing? > > tia K at Rdt > > >What you will want to do instead is something more like this: > > > >from wxPython.wx import * > > > >class MyPanel(wxPanel): [snip] > > def draw(self, dc): > > dc.Clear() font = wxFont(12, wxMODERN, wxNORMAL, wxNORMAL) dc.SetFont(font) [snip] Notice that the font size is 12 (although this is rather arbitrary). If you want a different font size, you'll also want to change the line spacing in MyPanel.draw(). This being the case, I would recommend using an attribute to MyPanel to keep track of the font size and adjusting the line spacing accordingly: class MyPanel(wxPanel): def __init__(self, parent, fontsize = 12): wxPanel.__init__(self, parent, -1) self.SetBackgroundColour(wxWHITE) self.text = [] self.fontsize = fontsize EVT_PAINT(self, self.OnPaint) def draw(self, dc): dc.Clear() font = wxFont(self.fontsize, wxMODERN, wxNORMAL, wxNORMAL) dc.SetFont(font) y = 0 for t in self.text: dc.DrawText(t, 0, y) y += self.fontsize + 2 -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From mgilfix at eecs.tufts.edu Wed Jul 24 09:35:49 2002 From: mgilfix at eecs.tufts.edu (Michael Gilfix) Date: Wed, 24 Jul 2002 09:35:49 -0400 Subject: how to count lines in a file ? In-Reply-To: ; from james.kew@btinternet.com on Wed, Jul 24, 2002 at 12:20:25PM +0100 References: <60FB8BB7F0EFC7409B75EEEC13E20192158F4F@admin56.narex.com> Message-ID: <20020724093549.B12572@eecs.tufts.edu> Er, hopefully this hasn't been suggested already, but perhaps file.xreadlines() will do the trick? If all that needs to be done is to count the file: for line in file.xreadlines(): count += 1 -- Mike On Wed, Jul 24 @ 12:20, James Kew wrote: > *cough* Reread the OP's problem specification: > > "Shagshag13" wrote in message > news:ahk020$tl4ue$1 at ID-146704.news.dfncis.de... > > i need to count lines in a file (that i *can't* keep in memory, so can't > use readlines()) > > The "for line in file" solution addresses this constraint: > "len(file.readlines())" doesn't. -- Michael Gilfix mgilfix at eecs.tufts.edu For my gpg public key: http://www.eecs.tufts.edu/~mgilfix/contact.html From fperez528 at yahoo.com Wed Jul 24 19:07:23 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 24 Jul 2002 17:07:23 -0600 Subject: Numeric Q: How to get DBL_MAX, etc. in Python? References: <240720021728273627%pecora@anvil.nrl.navy.mil> Message-ID: Louis M. Pecora wrote: > In C there are platform-specfic, floating-point constants as follows > defined in float.h, > > /* The largest double precision # */ > DBL_MAX (* (double *) __double_max) > > /* The accuracy of double precision */ > #define DBL_EPSILON (* (double *) __double_epsilon) > > /* The smallest double precision # */ > #define DBL_MIN (* (double *) __double_min) > > Where do these reside in Python? I have looked over my Python manuals > and done a Google search, but can't find any reference to them or > float/double limits outside of some threads online that are requesting > the same as me, but no answers. Are there standard Python functions or > globals that return these values for the platform one is operating on? > Any help appreciated. Thanks. In [4]: import kinds In [5]: kinds.default_float_kind. kinds.default_float_kind.DIG kinds.default_float_kind.EPSILON kinds.default_float_kind.MAX kinds.default_float_kind.MAX_10_EXP kinds.default_float_kind.MAX_EXP kinds.default_float_kind.MIN kinds.default_float_kind.MIN_10_EXP kinds.default_float_kind.MIN_EXP kinds.default_float_kind.RADIX kinds.default_float_kind.ROUNDS kinds.default_float_kind._basic_del kinds.default_float_kind._basic_get kinds.default_float_kind._basic_set kinds.default_float_kind._delete_disallowed kinds.default_float_kind._properties_d kinds.default_float_kind._properties_g kinds.default_float_kind._properties_s kinds.default_float_kind._write_disallowed kinds.default_float_kind.get_property_d kinds.default_float_kind.get_property_g kinds.default_float_kind.get_property_s kinds.default_float_kind.is_internal_attribute kinds.default_float_kind.name kinds.default_float_kind.set_property kinds.default_float_kind.str kinds.default_float_kind.typecode The kinds module is part of Numeric. cheers, f From shagshag13 at yahoo.fr Wed Jul 31 05:18:32 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 31 Jul 2002 11:18:32 +0200 Subject: signature for a file ? References: Message-ID: "Huaiyu Zhu" a ?crit dans le message de news: slrnake48e.467.huaiyu at gauss.almadan.ibm.com... > Shagshag13 wrote: > > > >i had at home many hdds, that could contain many time same files, in many > >places/directories (-> i'm really disorganized). i would like to do some > >sort on theses files. to do this i'm planning to write a python script that > >would compute a kind of CRC32, MD5 or SHA (i'm really not competent in that > >- so here i need advices and pointer to some implementations - and to know > >which is the best to had a unique unambiguous signature for a file) and > >then use it to find "doubles" : same size + same signature = probably same > >file. > > That would be very useful indeed. (Concurs another disorganized person :-) > > Here's a further question. Once you get to know the identities of files, > how do you know about the directories? I have many directories that have > identical subdirectories. I'd like to build an inventory of maximal > identical directories. A and B are defined as maximal identical if they are > identical but their parents are not. The few ideas I have all produces > combinatorial explosion. hello, i don't think about that yet, it was just a quick idea to check double files. if a had a cool idea for "maximal identical directories" i'll you know... s13. From phr-n2002b at NOSPAMnightsong.com Fri Jul 19 00:18:56 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 21:18:56 -0700 Subject: HTML DOM parser? References: <3D378CE6.E670EDAD@engcorp.com> Message-ID: <7x3cugnydr.fsf@ruckus.brouhaha.com> Peter Hansen writes: > My choice of www.nightsong.com was of course because that's the > domain the OP posted from. I didn't stop to think someone might > have a "www" subdomain which actually refused a connect request... > strange if you ask me. www.nightsong.com doesn't refuse connect requests. It accepts connections and sends back a valid HTTP 403 response indicating there's no page available at "/" (e.g. no index.html at the document root). If you use an interior URL like it should work fine. From bokr at oz.net Wed Jul 31 16:32:38 2002 From: bokr at oz.net (Bengt Richter) Date: 31 Jul 2002 20:32:38 GMT Subject: lexing nested parenthesis References: Message-ID: On Sun, 28 Jul 2002 23:57:21 -0400, Dave Cinege wrote: >It's nice when you open up your reference book, and immediately >find a section on what you want to do. > >It sucks large donkey rocks when that section is titled: >"Difficulties and Impossiblies" (Mastering Regular Expressions) > >I've been playing with shlex, and think in my application I'm >better off minimizing or avoiding it. > >Primarily I want to do search, evaluate, modify, and replace >on a line by line basis. The diffculty comes with matching >arbitrary nested constructs, IE nested parenthesis. > >IE > if 1 and (var1 or ?(-d /etc/)): > If you have defined the syntax of the above (I assume it's literal text), perhaps you would gain by adding quotes, and using a symbol instead of '?', e.g., if 1 and (var1 or qm('-d /etc/')): would already be legal Python. >I want to find ?(.*), but not runneth under or over. >Evaluating a token at a time will become disgusting. It also >seems redundant as you can see it's the same parsing rules as >Python has. (And in fact that is what the line will be >converted to.) Maybe a few examples with un-nested and nested parens (and nested ?(...) constructs??) together with what Python you would like to have them transformed to would get you some useful help. > >Can anyone recommend a 'Better Way'? I'm thinking maybe subclassing >generate_tokens. 'Better' is a waste of time unless we're working on the real problem ;-) Regards, Bengt Richter From MENJI at hepsinen.edu.co Wed Jul 24 17:33:10 2002 From: MENJI at hepsinen.edu.co (Murad Abbas Al Haji) Date: Wed, 24 Jul 2002 21:33:10 GMT Subject: it's very raw today, I'll kick monthly or Anne will expect the counters Message-ID: <24ECE483.DAEC85F4@hepsinen.edu.co> tgos at spamcop.net m.hanauska at gmx.net admin at tgos.org unexxaq vugnorej tech at tgos.org dom at tgos.org webmaster at tgos.org postmaster at tgos.org tgos at spamcop.net m.hanauska at gmx.net admin at tgos.org tgos at spamcop.net m.hanauska at gmx.net admin at tgos.org tgos at spamcop.net m.hanauska at gmx.net admin at tgos.org All papers will be dull healthy elbows. I am frantically weak, so I scold you. Why will we join after Osama explains the new corner's fork? Charlene fears the dust within hers and rigidly recollects. All proud twigs behind the lean bathroom were wasting under the short store. There, it seeks a can too closed beneath her blunt window. Blanche kills, then Dave smartly fills a noisy grocer between Tom's square. Some frogs arrive, sow, and mould. Others truly cover. What Dave's inner disk answers, Elizabeth hates in front of handsome, full moons. They sadly help without weird hollow plains. Every fat sauces are urban and other quiet dogs are cold, but will Jimmy pull that? Many dark dry cat walks wrinkles below Yosri's bad porter. Will you call to the rain, if Ramzi daily laughs the tree? Nell, near buckets dirty and bizarre, dreams to it, excusing weakly. Hardly any sick lentils receive Priscilla, and they loudly like Taysseer too. The fresh butcher rarely jumps Christopher, it judges Katherine instead. The tag among the angry shore is the gardner that lifts wrongly. Who cares gently, when Karim burns the raw dose towards the college? They love dully, unless Moammar promises walnuts without Zamfir's case. Are you tired, I mean, nibbling over shallow tickets? Don't even try to pour the clouds annually, converse them furiously. What will you recommend the cosmetic strange enigmas before Jeremy does? Well Jadallah will measure the painter, and if Youssef crudely looks it too, the button will tease towards the ugly stable. One more sad farmer or fog, and she'll fully learn everybody. If you will wander Woody's forest under pickles, it will bimonthly change the powder. To be kind or polite will attack lower eggs to monthly irritate. Tell Franklin it's elder attempting between a counter. She wants to creep smart cups against Edna's hallway. We play the sour poultice. It kicked, you smelled, yet Muhammad never freely grasped above the star. Try ordering the lake's sweet car and Joe will clean you! I was believing to behave you some of my strong coconuts. Larry! You'll reject oranges. Hey, I'll climb the goldsmith. Who did Basksh dine near all the jackets? We can't live plates unless Alhadin will admiringly open afterwards. Just shouting in back of a candle over the road is too deep for Basksh to comb it. If the outer pitchers can taste angrily, the sharp jar may depart more mornings. She should move once, solve eventually, then irrigate before the sauce among the light. He can talk bitter coffees, do you expect them? Fucking don't dye halfheartedly while you're improving on a old floor. I was cooking spoons to cheap Mustapha, who's arriving in the dryer's camp. Yesterday, go care a draper! She'd rather kick simply than receive with Donald's think fig. Otherwise the weaver in Perry's tailor might clean some open units. He'll be living about rural Neil until his shoe answers badly. Why did Tommy taste the lemon near the abysmal puddle? Gawd, carrots behave without wide bedrooms, unless they're young. As lovingly as Fahd calls, you can hate the frame much more generally. He may burn easy shopkeepers over the upper filthy evening, whilst Feyd grudgingly shouts them too. Sometimes, Brahimi never measures until Rasheed lifts the younger carpenter happily. They are grasping near the spring now, won't dye boats later. Bernice, still covering, departs almost weekly, as the yogi wastes over their cobbler. Her desk was empty, good, and sows below the navel. My clever potter won't irrigate before I join it. It will explain cruelly if Felix's exit isn't rude. It can hourly fill around Ibrahim when the glad printers attack in the wet office. Until Marwan jumps the diets steadily, Ramez won't recommend any active signals. The bandages, caps, and pears are all long and worthwhile. Better nibble bowls now or Donovan will seemingly fear them throughout you. Karen, have a stale kettle. You won't learn it. We wander them, then we partly expect Mikie and Kareem's solid raindrop. No clean sticky envelopes will finitely order the balls. Fucking don't seek a barber! When does Tom love so partially, whenever Donovan solves the light game very absolutely? Get your familiarly teasing ointment in front of my swamp. You won't move me scolding in front of your brave cafe. It will look the lost ache and reject it in back of its ladder. Where doesn't Andy walk slowly? It's very blank today, I'll laugh stupidly or Jonnie will improve the shirts. Calvin's tape judges to our pool after we attempt below it. Lots of humble lazy jugs deeply climb as the thin teachers open. Other pathetic unique hats will converse nearly throughout cards. One more stickers undoubtably cook the durable room. If you'll pour Shelly's sign with pumpkins, it'll locally kill the pin. Let's change inside the stupid foothills, but don't comb the rich ulcers. It can unbelievably talk difficult and irritates our distant, pretty smogs in a hair. Both playing now, Saad and Ibraheem promised the hot doorways in back of poor hen. For Greg the tyrant's heavy, to me it's short, whereas for you it's dreaming sick. From PoulsenL at capanalysis.com Mon Jul 15 18:14:21 2002 From: PoulsenL at capanalysis.com (PoulsenL at capanalysis.com) Date: Mon, 15 Jul 2002 18:14:21 -0400 Subject: Maximizing observations from Sparse matrices Message-ID: <72F73B808A78D511A73600034771D9FF717E14@dc_exchange2.howrey.com> I am running a regression that gathers its data from a panel dataset (cross-sectional time series). Because the dataset is sparse I must sometimes either drop cross-sections or variables or some combination of the two to avoid a singular matrix. A quick, extremely simplified example: obs region var1 var2 var3 Valid ob? 1 1 1 4 7 3 2 1 7 NA 9 0 3 1 7 NA 9 0 4 1 5 NA 7 0 5 1 7 7 5 3 1 2 7 NA 9 0 2 2 5 NA 6 0 3 2 7 4 5 3 4 2 9 8 NA 0 5 2 7 6 5 3 1 3 NA 58 4 0 2 3 NA 98 25 0 3 3 63 85 NA 0 4 3 74 NA 78 0 5 3 97 54 NA 0 1 4 NA 89 7 0 2 4 25 85 NA 0 3 4 5 NA 2 0 4 4 32 85 NA 0 5 4 45 12 3 3 Sum of valid obs 15 In this example I have 4 regions and 3 variables. Region 3 has no valid observations and therefore cannot be utilized unless corrected. I have two choices: eliminate a variable or eliminate the region. If I eliminate the variable it will now run because I have valid obs across all remaining regions: obs region var1 var2 var3 Valid ob? 1 1 4 7 2 2 1 NA 9 0 3 1 NA 9 0 4 1 NA 7 0 5 1 7 5 2 1 2 NA 9 0 2 2 NA 6 0 3 2 4 5 2 4 2 8 NA 0 5 2 6 5 2 1 3 58 4 2 2 3 98 25 2 3 3 85 NA 0 4 3 NA 78 0 5 3 54 NA 0 1 4 89 7 2 2 4 85 NA 0 3 4 NA 2 0 4 4 85 NA 0 5 4 12 3 2 Sum of valid obs 16 Finally I can instead eliminate a region obs region var1 var2 var3 Valid ob? 1 1 1 4 7 3 2 1 7 NA 9 0 3 1 7 NA 9 0 4 1 5 NA 7 0 5 1 7 7 5 3 1 2 7 NA 9 0 2 2 5 NA 6 0 3 2 7 4 5 3 4 2 9 8 NA 0 5 2 7 6 5 3 1 4 NA 89 7 0 2 4 25 85 NA 0 3 4 5 NA 2 0 4 4 32 85 NA 0 5 4 45 12 3 3 Sum of valid obs 15 This quick example yields the same number of observations, but there are configurations where this may lead to more obs than eliminating a variable. The problem is I have hundreds of variables and about 50 regions. Is there an efficient way to maximize the number of observations? Thanks for any help Loren From paul1brian at yahoo.com Wed Jul 17 11:54:38 2002 From: paul1brian at yahoo.com (Paul Brian) Date: Wed, 17 Jul 2002 16:54:38 +0100 Subject: how to ask google, altavista or another search engine... References: Message-ID: <1026921280.24445.0.nnrp-07.c1c3e11b@news.demon.co.uk> Dear shagshag..... It can all be done with the google web API This is an xml-rpc based service that allows you to send through queries and get back xml formatted results. Its very impressive, although I am lost for "real world" automated applications.... You need to register however, to prevent abuse i suppose: https://www.google.com/accounts/ As for the other search engines, perhaps use urllib to download the pages and just a simple string.find would result in most answers, with little effort (or, for masochists, use htmltidy to convert to xhtml, and XPath to get the bits, or even regular expressions ! ) ------------------------------ Paul Brian (07899) 877 295 paul1brian at yahoo.com "Shagshag13" wrote in message news:ah431f$q33vu$1 at ID-146704.news.dfncis.de... > hello, > > i'm looking for a python script able to ask to a web search engine (google, altavista or another search engine) and/or able to parse > a result page. > > any other helps / advices / urls are welcome... > > thanks in advance, > > s13. > > From tdelaney at avaya.com Tue Jul 9 04:15:26 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 9 Jul 2002 18:15:26 +1000 Subject: Using Python for processing of large datasets (convincing man agment) Message-ID: > From: Thomas Jensen [mailto:spam at ob_scure.dk] > > Delaney, Timothy wrote: > > > "select a from T_A;select b from T_B;select c from T_C;" > > > > Doing this should reduce your network latency massively. > > I've used this method before, but never to reduce latency, thanks for > the advice! It's actually got dual benefits. 1. You have reduced your latency by approx a third (you have one send - wait for network - calculate - wait for network - receive cycle instead of three); 2. The calculate - wait for network - receive portion can actually overlap - while you are retrieving the data from the first query, the second and third can still be calculating. Another method which works well is to spin each of the selects off into its own thread, then wait for each to finish. However, doing multiple selects in a single request will almost certainly perform better (and have less code change). Tim Delaney From pyth at devel.trillke.net Thu Jul 25 06:51:31 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 25 Jul 2002 12:51:31 +0200 Subject: Callable modules? In-Reply-To: ; from bokr@oz.net on Wed, Jul 24, 2002 at 11:44:20PM +0000 References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> Message-ID: <20020725125131.K10625@prim.han.de> Hi Bengt, thanks for your nice code samples. Although i had problems reading code containing my name too often (Signal Overflow :-). Especially your experiments with putting the execution of the module-file into a class makes some sense to me. Below i tried a similar yet different approach :-) I really wonder whether there are *any* reasons to have a distinct ModuleType. What does it offer that a plain good old (or new) 'class' could not do? Anyway, here is one interesting small experiment ... ** start Module.py ** import __builtin__ class Module(object): oldimporter = __builtin__.__import__ def __init__(self, name, globals={}, locals={}, fromlist=[]): module = self.oldimporter(name, globals, locals, fromlist) self.__dict__ = module.__dict__ def __getattr__(self, name): getter = self.__dict__.get('__getattr__') return getter(name) __builtin__.__import__ = Module **end** ** test.py ** def __getattr__(name): print "__getattr__ called with name",name import os,sys ** and the sesssion with these experimental stuff: >>> import Module # wraps __import__ >>> import test >>> test >>> test.os >>> test.h __getattr__ called with name h I wonder if there are any serious drawbacks of this approach. regards, holger From astrophels at yahoo.com Thu Jul 11 22:27:53 2002 From: astrophels at yahoo.com (Micah Mayo) Date: Fri, 12 Jul 2002 02:27:53 GMT Subject: Python for data driven website? Message-ID: Howdy Folks, My company is in the early stages of building a web application for accountants. Right now we're trying to choose which technology we're going to write it in. The database will almost certainly be mySQL. At first we were going to use the .NET framework microsoft is offering, which is perfect for what we're trying to do, but when considering microsofts gestapo license crew, we decided it was not the best option. We then started looking at the options in the free software arena, and had almost decided to go with a MySQL/PHP/Apache solution. PHP looks at least adequate for what we're trying to do, but my boss(who has typically worked with the microsoft stuff) started reading some things about python, and is very interested. So, he sent me out to do some research. I've been reading some articles on the web which give me a pleasant view of python, but don't quite answer my questions. What can python offer as far as the web goes? How well does it function and/or integrate with mySql and apache? How does it compare with php as pertains to the web and dealing with mySql? I'm not trying to do a php vs. python thing here. I'd just like to see a fair comparison of what the languages offer. Can anyone point me to some articles? Thanks, Micah From tweedgeezer at hotmail.com Wed Jul 31 15:55:58 2002 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 31 Jul 2002 12:55:58 -0700 Subject: Strange behavior with classes deriving from object and weakrefs. Message-ID: <698f09f8.0207311155.4fdcb159@posting.google.com> I can't say much more than the code itself: >>> import gc, sys, weakref >>> class O(object): pass >>> o = O() >>> d = weakref.WeakValueDictionary() >>> d['o'] = o >>> d['O'] = O >>> d.items() [('O', ), ('o', <__main__.O object at 0x00A116F8>)] >>> del o >>> del O >>> gc.collect() 0 >>> d.items() [('O', )] >>> sys.getrefcount(d['O']) 5 Whence came those 5 references? Jeremy From maxm at mxm.dk Tue Jul 16 04:12:44 2002 From: maxm at mxm.dk (Max M) Date: Tue, 16 Jul 2002 10:12:44 +0200 Subject: Webware 0.7/Singleton pattern References: Message-ID: <3D33D57C.6000709@mxm.dk> Michael Bub wrote: > does anyone know how to get "safe" singleton classes to get rid of > that problem? I belive that Alex Martelli has posted a singleton class to the group, or to the coockbook. Oh ... guess I found it at: http://www.onlamp.com/pub/a/python/2002/07/11/recipes.html?page=2 regards Max M From joost_jacob at hotmail.com Wed Jul 24 18:54:38 2002 From: joost_jacob at hotmail.com (J.Jacob) Date: 24 Jul 2002 15:54:38 -0700 Subject: programming with XML-RPC in Python Message-ID: <13285ea2.0207241454.583c743f@posting.google.com> Hello, I put some things I tried at http://www.liacs.nl/~jjacob/swc/swc.zip (16K source files zipped) and I would be happy with comments or suggestions. It is a sort of client-server framework so you can turn your class into an XML-RPC server without having to modify any code of the class. It is also backwards compatible with python 1.5.2 (has xmlrpclib.py and adapted SimpleXMLRPCServer.py in the zip file). I want to do some research with it and maybe somebody has good ideas :-) Joost Jacob QOTD: Remember Darwin; building a better mousetrap merely results in smarter mice. From gerhard.haering at gmx.de Tue Jul 30 00:30:20 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 30 Jul 2002 06:30:20 +0200 Subject: Python & X-Chat In-Reply-To: <3d4610d1$0$289$ba620e4c@news.skynet.be> References: <3d4610d1$0$289$ba620e4c@news.skynet.be> Message-ID: <20020730043020.GA11696@lilith.my-fqdn.de> * Hikage [2002-07-30 06:03 +0200]: > Hello, I seach people who had make script for x-char or had doc about this.. > > > I've found nothing ... HELP HELP ;) > > Thanks to the people who can help me :) I guess you should check out the latest XChat, quoting from http://www.xchat.org: | 09-JUL-2002 | Released development version 1.9.2. This version includes a new Python | interface, written by Gustavo Niemeyer. It has been designed and | implemented really well! It sure puts the Perl interface to shame. Well, it _can_ only have improved, *cough* ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From marklists at mceahern.com Thu Jul 18 20:45:48 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 18 Jul 2002 19:45:48 -0500 Subject: Percent sign in format string? In-Reply-To: Message-ID: print "%d%%" % 98 in other words, % is an escape character that lets you print %. // m > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Ron Levine > Sent: Thursday, July 18, 2002 7:33 PM > To: python-list at python.org > Subject: Percent sign in format string? > > > > How can I put a "%" sign in a format string? > > For example, x=98 and I want to output > "x = 98%" > > The statement > print "x = %d%"%x > produces a ValueError: incomplete format string > > So does the statement > print "x = %d\%"%x > > > -- > http://mail.python.org/mailman/listinfo/python-list > - > > - From bdesth at nospam.free.fr Sun Jul 14 16:14:40 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 14 Jul 2002 16:14:40 -0400 Subject: Calling Python from Allegro Lisp References: <3D2EC4B5.1070605@thomas-guettler.de> Message-ID: <3D31DBB0.3040901@nospam.free.fr> Marco Antoniotti wrote: > Thomas Guettler writes: > > >>Hi! >> >>I have an old application which needs to call python. >>The old app is written in allegro lisp. >> >>I tried the following: >>(defparameter hlib "c:\\winnt\\system32\\python22.dll") > > > It's be better to say > > (defparameter *hlib* (parse-namestring "c:\\winnt\\system32\\python22.dll")) > > >>(probe-file hlib) > > > This will just return the above pathname or NIL. > > >>(ct:defun-dll Py_Initialize() >> :return-type :void >> :library-name hlib >> :entry-name "Py_Initialize") >>(ct:defun-dll PyRun_SimpleString((s :char *)) >> :return-type :long >> :library-name hlib >> :entry-name "PyRun_SimpleString") >> >>(Py_Initialize) >>(setq foo "print 'foo'") >>(PyRun_SimpleString (cref (ct:char *) foo 0)) >> >>But get: >>""" >>The first element (CREF (CHAR *) foo 0) of a function >>application is not a function name >>""" > > > After your setting up of your Python Library you have ended up with a > function called > > PyRun_SimpleString > > (Note that ct:defun-dll may not be the best way to achieve this) > > You are calling the above function of the value that the macro CREF. > However, note that CREF is in the CT package and that you may or may > not have that symbol available in your code snippet. Try putting the > fully qualified name in your code: CT:CREF. > > >>What could be wrong. > > > (with-sarcasm () > (print "Wanting to use Python?")) > > >>I am new to lisp > > > Then stick with it. Rewrite the Python stuff in a better language and > live happier everafter. (begin-troll () (print "But ? There is *no* better language than Python !!!?")) laotseu From greg at cosc.canterbury.ac.nz Wed Jul 31 01:21:54 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 31 Jul 2002 17:21:54 +1200 (NZST) Subject: Pyrex / py2exe import interaction In-Reply-To: <20020730232547.A86330@doublegemini.com> Message-ID: <200207310521.g6V5Ls2j019263@kuku.cosc.canterbury.ac.nz> > The _import_one is being called on 'testmod', which is the binary > module compiled by pyrex. What puzzles me most about this is that there's no such thing as a "binary module" -- Pyrex modules are perfectly ordinary module objects, the same as the interpreter uses. I have a feeling this may have something to do with the "current module". When I was figuring out how to implement the import statement, I did some poking about to find out how the interpreter does it. I can't remember all the details, but I think I found that I couldn't emulate it exactly, because it made use of a notion of a "current module" that only applies when interpreted code is being executed. Maybe the import hooks are using this to find out what package the importing module belongs to? If that's the case, then it's probably going to get whatever was the last interpreted module that a function was executed from. Now, if the Pyrex module is being invoked as the main module by py2exe without going through an interpreted module first... maybe that's what the root cause of the problem is? I'm just guessing wildly here, and may be completely wrong. Greg Ewing, Computer Science Dept, +--------------------------------------+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | greg at cosc.canterbury.ac.nz +--------------------------------------+ From loewis at informatik.hu-berlin.de Wed Jul 31 05:36:02 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 31 Jul 2002 11:36:02 +0200 Subject: global interpreter lock not working as it should References: <7xofcoopfs.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > But that is precisely the gripe about the GIL. If you have multiple > CPU's, you can use them with C threads but not with Python threads. That is the general gripe about the GIL, yes - but not the one of the OP. The OP wants a pthread_yield call to be inserted in some place; he appears not to be worried about the fact that there is a global lock in the first place. Regards, Martin From bokr at oz.net Tue Jul 16 01:38:34 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Jul 2002 05:38:34 GMT Subject: Python's Lisp heritage References: <72jvga.eb.ln@grey.aerojockey.localdomain> Message-ID: On Mon, 15 Jul 2002 18:41:11 -0400, Carl Banks wrote: >Christopher Browne wrote: >> From a paper on Emacs: > >Incidentally, I'd like a reference to this paper. I hope it's not >something that appeared in a scholarly journal, because it's flatly >wrong. (I think it more likely to be someone at Perl conference in >1992 trying to justify the local statement. :) > googling for "Some language designers believe that dynamic binding should be" yields http://www.gnu.org/software/emacs/emacs-paper.html and an April post by Christopher http://mail.python.org/pipermail/python-list/2002-April/100306.html but this looks like it was originally by RMS: http://www.daemoncode.com/hacker/AI-519a.php -- MASSACHUSETTS INSTITUTE OF TECHNOLOGY ARTIFICIAL INTELLIGENCE LABORATORY AI Memo 519a 26 March 1981 EMACS The Extensible, Customizable Self-Documenting Display Editor by Richard M. Stallman Abstract: EMACS is a display editor which is implemented in an interpreted high level language. This allows users to extend the editor by replacing parts of it, to experiment with alternative command languages, and to share extensions which are generally useful. The ease of extension has contributed to the growth of a large set of useful features. This paper describes the organization of the EMACS system, emphasizing the way in which extensibility is achieved and used. Keywords: Display, Editor, Extensible, Interactive, Self-documenting This report describes work done at the Artificial Intelligence Laboratory of the Massachusetts Institute of Technology. Support for the Laboratory's research is provided in part by the Advanced Research Projects Agency of the Department of Defense under Office of Naval Research contract N00014--80--C--0505. A truncated version of this paper appeared in the proceedings of the ACM SIGPLAN/SIGOA Symposium on Text Manipulation, Portland Oregon, June 1981. Copyright ? MASSACHUSETTS INSTITUTE OF TECHNOLOGY 1981. [This version was done in the interest of accessibility by Dave Love d.love at dl.ac.uk with Texinfo markup of an OCRed version of the raw scanned pages from ftp://publications.ai.mit.edu/classic-hits/AIM-519A.ps. Corrections to transcription errors would be appreciated.] -- Looks like you can go one more step, to the .ps. google is wonderful if you have a verbatim phrase, and great if you don't ;-) Regards, Bengt Richter From gerhard.haering at gmx.de Tue Jul 2 18:30:13 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 3 Jul 2002 00:30:13 +0200 Subject: Is Python growing? In-Reply-To: <3D22263A.8090007@hotmail.com> References: <3D1D3D34.6080001@hotmail.com> <3D22263A.8090007@hotmail.com> Message-ID: <20020702223012.GA2271@lilith.my-fqdn.de> * scott [2002-07-02 22:16 +0000]: > Gerhard H?ring wrote: > [help builtin only available in Python 2.2 or later] > > You are mistaken Gerhard. 2.1.1 (Activestate on NT4) is demonstrated > below: > > bash-2.02$ python > ActivePython 2.1.1, build 212 (ActiveState) > Python 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman It's either ActiveState or your Alternative ReadLine that's installing pydoc.help as a builtin. In the standard Python 2.1.x, it isn't there. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mark.charsley at REMOVE_THIS.radioscape.com Mon Jul 22 07:04:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Mon, 22 Jul 2002 12:04 +0100 (BST) Subject: Dpulicating "class Foo:" in C References: Message-ID: In article , walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) wrote: > > Is there any way to create a new Class Object from C without having > > to call into new.classobj? > > In Include/classobject.h there's a > PyObject *PyClass_New(PyObject *, PyObject *, PyObject *); > > Arguments seem to be: > * tuple of base classes > * class attribute dictionary > * class name Which exactly matches new.classobj(). > But PyClass_New isn't documented, so I wonder, if it's > part of the official API. At least, the function name does > indicate that it is. Well after a bit of googlin... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54352 seems to recommend its use and http://www.python.org/peps/pep-0253.html includes the phrase "For a regular base class (or when no base class is specified), current Python calls PyClass_New(), the C level factory function for classes, directly." So I'd guess that it's safe-ish to use. Still slightly worried about the lack of official documentation though. Thanks for the pointer. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From fperez528 at yahoo.com Wed Jul 10 12:59:19 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 10 Jul 2002 10:59:19 -0600 Subject: leastSquaresFit References: Message-ID: Alex Tournier wrote: > Fernando P?rez wrote in message >> Many numeric functions do not >> implicitly convert lists to arrays (though some can operate on lists as >> well as arrays). Try data = Numeric.array(data) and see what happens. >> >> f > > I tried as you said, putting it through array(), but still get the same > message! Could there be a problem with the FirstDerivatives.py module?? > Alex Well, it seems like you need to upgrade numeric or you need to upgrade python. On my machine (python 2.2, Numeric 20.3) it works just fine: IPython profile: tutorial *** Pasting of code with ">>>" or "..." has been enabled. In [1]: >>> from Scientific.Functions.LeastSquares import leastSquaresFit In [2]: >>> import Numeric In [3]: >>> # The mathematical model. In [4]: ... def exponential(parameters, x): ...: ... a = parameters[0] ...: ... b = parameters[1] ...: ... return a*Numeric.exp(-b/x) ...: In [5]: >>> # The data to be fitted to. In [6]: ... data = [(100, 4.999e-8), ...: ... (200, 5.307e+2), ...: ... (300, 1.289e+6), ...: ... (400, 6.559e+7)] In [7]: In [8]: >>> fit = leastSquaresFit(exponential, (1e13, 4700), data) In [9]: fit Out[9]: ([8641551709749.7666, 4715.4677901570467], 1080.2526437958597) cheers, f. From jblazi at hotmail.com Sun Jul 14 07:17:09 2002 From: jblazi at hotmail.com (JB) Date: Sun, 14 Jul 2002 13:17:09 +0200 Subject: Moving list entries from one list to another References: <3d30085b_9@news.newsgroups.com> <3d308c96_8@news.newsgroups.com> Message-ID: <3d315be9_1@news.newsgroups.com> Bengt Richter wrote: > On Sat, 13 Jul 2002 22:32:32 +0200, JB > wrote: > [...] >> >>f will be *slow*. The list entries are tuples and the >>tuple entries are strings. Then f is "in" for strings, >>that is it checks, if one string contains another one. >>What I want to implement, is a list view with incr4emental >>search. There > What kind of incremental search? Just matching leading > characters? Or matching additional words anywhere? Or > arbitrary word fragments? Or? > >>will be up to 250000 entrie in the list view at the moment >>(for example all headers of the news group >>alt.binaries.mp3.classical) and this number is going to >>increase in the future as news servers become bigger and >>bigger. I thought that when f is slow, then at least the >>merging should be as fast as possible. > This sounds like the data changes fairly infrequently > compared to how often it's searched. Would a costly > indexing job run infrequently be worth while if it paid > off in search speed? > > There are probably better ways to generate a selection > than brute scanning of python lists with strings, but just > to get the requirements down, does this do the kind of > incremental search you are interested in? > -- > >>> class IncSrch(object): > ... def __init__(self, master_list): > ... self.master = master_list > ... self.curr = [] > ... def new_search(self, patt): > ... self.curr = [x for x in self.master if > x[1].find(patt)!= -1] > ... def inc_search(self, patt): > ... self.curr = [x for x in self.curr if > x[1].find(patt)!= -1] > ... def __repr__(self): > ... return '\n'.join([`x` for x in self.curr]) > ... > > Here we just generate a list of example tuples with ids > and random-suffix strings: > >>> import random > >>> r = random.Random() > >>> master1 = [(i,'item_%s%s' % > >>> (r.choice('ABCD'),r.choice('XYZW'))) for i in > >>> xrange(10)] master1 > [(0, 'item_AZ'), (1, 'item_BX'), (2, 'item_BY'), (3, > ['item_BZ'), (4, 'item_AZ'), (5, 'item > _BW'), (6, 'item_BW'), (7, 'item_DY'), (8, 'item_BY'), > (9, 'item_CY')] > > (Is this like your data? Or how does it differ?) This is ok. The real data are much longer strings, but it is ok. > > Here we initialize a search object with a master starting > list and nothing selected > >>> is1 = IncSrch(master1) > >>> is1 > > >>> `is1` > '' > I.e., there is nothing selected to the curr list yet. > > Here we do a first search based on containing substring > 'D': > >>> is1.new_search('D') > Just typing the name calls repr to print the current state > of the search object: > >>> is1 > (7, 'item_DY') > > That wasn't much to do a secondary search on, so we do a > new search on the master list for 'B': > >>> is1.new_search('B') > >>> is1 > (1, 'item_BX') > (2, 'item_BY') > (3, 'item_BZ') > (5, 'item_BW') > (6, 'item_BW') > (8, 'item_BY') > > That got a few, so we incrementally search for 'Y': > >>> is1.inc_search('Y') > >>> is1 > (2, 'item_BY') > (8, 'item_BY') > > And so forth. Is that the kind of thing you want to do? Yes. > I presume you have to pass a list of items in some form to > the display widget, and that you will not want to pass > more than say MAX_FOR_WIDGET items for a reasonable > scrolling display, and you may(??) need the items as a > list of strings, not tuples, so you might want to add a > first_for_widget() and next_for_widget() method to the > class as part of the definition (but I'll do it separately > here since I have some state above to use): Of course, only 40 or so lines can be displayed at the same time. It plays no r?le if I pass list or tuples of strings. > If you will comment on what this simple class does and > doesn't do that you need functionally, that will establish > unambiguous requirements. Then we can make it fast one way > or another. That is exactly. what I want. I do not quite understand in your soulution, what you do, when the search string is shortened by the user. Let us assume, he had typed in "Mo" (for Mozart) but then he decides he is looking for "Me" (another composer). So he deletes the "o". What happens then? This is, why I thought, I should need two lists. -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From mwh at python.net Wed Jul 31 09:58:30 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 31 Jul 2002 13:58:30 GMT Subject: Python Cookbook dict problem References: <200207302001.g6UK1Rc07994@localhost.localdomain> <20020730224427.GA14027@nullcube.com> Message-ID: Dave Reed writes: > > Python expects you to do positional and keyword argument > > unrolling at the end of the function argument list (i.e. > > after all "normal" arguments). Change the last line to: > > > > tada = dodict(yellow=2, green=4, *data.items()) > > > Thanks. Did something change in Python versions or is it a typo in the > book? I'm pretty sure this has never changed, or at least not within the last five years or so. Cheers, M. -- ARTHUR: Don't ask me how it works or I'll start to whimper. -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From tundra at tundraware.com Mon Jul 29 02:30:02 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 29 Jul 2002 06:30:02 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: Tim Daneliuk wrote: > Does some kind soul out there happen to have a pointer to a > tutorial/examples on > fiddling with the Win32 registry from PythonWin? > > TIA, Thanks to the many who followed up on this thread. I now have a first-cut of my MRU cleanup utility, but have a few further questions: ###################################################################################### from _winreg import * mrulist = \ ( \ r"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List", \ r"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List", \ r"Software\Microsoft\Office\9.0\PowerPoint\Recent File List", \ r"Software\Microsoft\Office\9.0\Excel\Recent Files", \ r"Software\Microsoft\MediaPlayer\Player\RecentFileList", \ ) reg = ConnectRegistry(None,HKEY_CURRENT_USER) for entry in mrulist: DeleteKey(reg, entry) CreateKey(reg, entry) CloseKey(reg) ###################################################################################### This works fine for those programs that place their MRU list in a distinct key just for that purpose, as the examples in 'mrulist' above do. However, some programs place this information within a key that also holds other information the program needs to do its job. In this case, my approach - nuking the whole key and then recreating an empty one - does not work because I would also be wiping out the non-MRU stuff. This is where I run into a problem. I am having a dickens of a time figuring out how to remove just a single value within a key. I cannot seem to find the magic that allows editing of the lowest level leaf nodes of a registry entry on an individual basis. If I try to treat them as *key* Python grumbles something to the effect that it cannot find that file at the OpenKey call. If I try to use DeleteValue, I get permission denied even though I am running with Administrator privileges on a Win2K machine. This may well be a lack of my understanding Windoze and the arcana of the registry - I'm more of a Unix person - and not a Python problem at all. In any case, help is appreciated as always. TIA, ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From kristian.ovaska at helsinki.fi Wed Jul 31 05:05:29 2002 From: kristian.ovaska at helsinki.fi (Kristian Ovaska) Date: Wed, 31 Jul 2002 12:05:29 +0300 Subject: Let's Talk About Lambda Functions! References: <3d455445_9@news.newsgroups.com> Message-ID: <02afkus6bb1dj8b4l95dbteopqdafd58bc@4ax.com> JB : >(1) Why are back ticks a failure? I love them. In addition to the problems others have pointed out, on my (Finnish) keyboard I have to press Shift+?+Space if I want a single back tick. There are two ticks on the same key, back and forward, and I never use either. In English the traditional way to quote is ``like this?? or `like this?, right? Here it's just "like this" or 'like this'. -- Kristian Ovaska From whisper at oz.net Mon Jul 8 01:36:35 2002 From: whisper at oz.net (David LeBlanc) Date: Sun, 7 Jul 2002 22:36:35 -0700 Subject: Linux clock-setting script In-Reply-To: <7x8z4mubwp.fsf@ruckus.brouhaha.com> Message-ID: No, the ftp site I pointed to has a simple client in C - admittedly with some "windowisms" for setting the cmos clock on a PC mobo (which might translate pretty directly over to linux). It's spread over several files and looks to be about 20kb total of c source. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Paul Rubin > Sent: Sunday, July 07, 2002 20:39 > To: python-list at python.org > Subject: Re: Linux clock-setting script > > > "David LeBlanc" writes: > > "Set Your Clock Via Internet" > > http://www.boulder.nist.gov/timefreq/service/its.htm > > > > This particular page focuses on Windows, but the ftp site has > sources in C. > > I know there's a full blown NTP pckage on that ftp site but I didn't > want to spend hours reading documentation and configuring some hairy > monstrosity. I don't need millisecond accuracy; I just want my > computer to know what time it is within a few seconds. > > Apparently the C package has a program called ntpdate that maybe does > the right thing, but I haven't examined it. > -- > http://mail.python.org/mailman/listinfo/python-list From rhaper at houston.rr.com Tue Jul 2 21:58:04 2002 From: rhaper at houston.rr.com (Rod Haper) Date: Wed, 03 Jul 2002 01:58:04 GMT Subject: what can i expect... References: Message-ID: <3D225A39.6070400@houston.rr.com> Shagshag13 wrote: > hello, > > what can i expect if i change my python application to java ? More filling, less flavor. -- Rod +----------------------------------+ | There is a better way ... | | LAP => Linux + Ada95 + Python | +----------------------------------+ From shalehperry at attbi.com Tue Jul 9 19:56:44 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 09 Jul 2002 16:56:44 -0700 (PDT) Subject: php function "addslashes" / "removeslashes" in python In-Reply-To: Message-ID: On 09-Jul-2002 Lowel Stern wrote: > Does anyone know if this exists already? > Remember we speak python, not php. What do these functions do? From claird at starbase.neosoft.com Fri Jul 19 11:19:34 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 19 Jul 2002 10:19:34 -0500 Subject: Tkinter vs. wxPython References: Message-ID: <1486AA6999721FAF.C7F3DDBCDA87CFD8.10D369894B4EC4FD@lp.airnews.net> In article , d2002xx wrote: >> My question is this: is there any compelling reason I shouldn't just go >> with Tkinter instead? I work (for now) exclusively on Win32 boxes, by >> the way. > >Just compare the number of widgets in wxPython and Tkinter, you will >find out tkinter is almost useless. I'm wondering why python doesn't >use wxPython (or PyQT) as default GUI. 'Cause, as others have already noted, Tkinter's both lighter-in- weight and far more mature, particularly in regard to portability. Tkinter's the basis for many applications which are far from useless. Its Text and Canvas widgets are particularly potent and convenient; well-informed use of "tags" can make wxPythoneers en- vious. You're right that wxPython has many more widgets, and that quite a few people find Tkinter's visual appearance "old-fashioned". There are also quite a few people for whom that's secondary. Moreover, Tkinter provides nice hooks for localization of widget appearance. I've run into still other people who say they get acceptable Windows and Linux widget displays from Tkinter with just a few option specifications. Some of their tips are likely to show up in . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From phr-n2002b at NOSPAMnightsong.com Sun Jul 7 07:41:55 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 04:41:55 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> Message-ID: <7xk7o7n4sc.fsf@ruckus.brouhaha.com> Thomas Jensen writes: > I am quite certain that scaling (well) to multiple CPU requires one to > use threading at least. Scaling to several physical machines might be > (relativly) easy with Java, but imagine it must require some coding, > or? You are obsessed with this multi-CPU stuff but have not given the slightest bit of evidence that you need that complexity to meet your performance goals. Spend your time trying to understand your problem better rather than throwing fancy technology at it. Chances are you can do what you need with a simple, single-CPU approach. From niessink at serc.nl Sat Jul 13 17:42:30 2002 From: niessink at serc.nl (Frank Niessink) Date: 13 Jul 2002 21:42:30 GMT Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> <3D290EE0.C9A97B1E@engcorp.com> Message-ID: Roy Smith wrote: > > Peter Hansen wrote: >> Is it really important the order the tests are run in? > > I'm not sure, but it certainly *feels* like it should be important ;-) > > Well, here's an example. I've got a parser which returns a dictionary > of dictionaries. My setUp() method put this in self.tables, then I've > got: > > def test101 (self): > 'parse() returns a dictionary' > self.assertEqual (type (self.tables), DictType) > > def test102 (self): > 'parse() returns a dictionary of dictionaries' > for table in self.tables.values(): > self.assertEqual (type (table), DictType) I would probably do it like this: def testTableTypes(self): self.assertEqual (type (self.tables), DictType) for table in self.tables.values(): self.assertEqual (type (table), DictType) This way the asserts in the for loop are only tested if the first assert succeeds. Maybe I would even make a custom assert, to make the code a bit more readable: def assertTypeIsDict(self, object): self.assertEqual(type(object), DictType) def testTableTypes(self): self.assertTypeIsDict(self.tables) for table in self.tables.values(): self.assertTypeIsDict(table) Cheers, Frank -- Important facts from Galactic history, number one: (Reproduced from the Siderial Daily Mentioner's Book of popular Galactic History.) The night sky over the planet Krikkit is the least interesting sight in the entire Universe. -- Douglas Adams, 'Life, the Universe, and Everything' From cliechti at gmx.net Thu Jul 25 10:29:08 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Jul 2002 16:29:08 +0200 Subject: DLL files References: Message-ID: "Terry Reedy" wrote in news:GQT%8.276752$Bt1.14483509 at bin5.nnrp.aus1.giganews.com: > "Uwe Mayer" wrote in message > news:MPG.17aa19eb2ca3d536989688 at news.rz.uni-karlsruhe.de... >> is it possible to write Windows DLL files in python? > > No. .dll must be machine code and have special structure. (99% > certain on this) yes. but one could embedd the python interpreter in a DLL and just forward the calls to the DLL to a loaded script. this requires a compiler and some code for the DLL that is application specific (but autogenerable through a script). -- Chris From bhoel at web.de Sun Jul 7 17:19:13 2002 From: bhoel at web.de (Berthold Höllmann) Date: 07 Jul 2002 23:19:13 +0200 Subject: is this a bug? References: <1026076470.877638@master.nyc.kbcfp.com> Message-ID: "news" writes: > Python 2.0 (#1, Feb 7 2001, 22:41:16) > [GCC 2.95.2 19991024 (release)] on sunos5 > Type "copyright", "credits" or "license" for more information. > >>> "aa" in ["aa", "ab"] > 1 > >>> "aa" in ["aa"] > 1 > >>> "aa" in ("aa") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'in ' requires character as left operand > > Is this a bug, or should this be consistent between lists and tuples? Yes, it should be consistent between lists and tuples, but no, this is no bug, because ("aa") is a string and not a tuple: Python 2.2.1 (#2, May 22 2002, 22:49:15) [GCC 3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ("aa") 'aa' >>> ("aa",) ('aa',) >>> To make a one telement tuple you have to add the comma. Greetings Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From tim.one at comcast.net Thu Jul 4 13:09:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 04 Jul 2002 13:09:18 -0400 Subject: replacing instance __setattr__ In-Reply-To: Message-ID: [Robin Becker] > special methods aside I find in 'Unifying types and classes in Python > 2.2' http://www.python.org/2.2/descrintro.html#mro > that the object is always searched last for methods which seems a bit > daft and obviously different for non-method attributes. The builtin class named "object" is searched last for methods. When you say "the object", I expect you're thinking of the x in x.somemethod() That's a different thing entirely. If x is an instance of a newstyle class, then x's class either is, or inherits from, the builtin class named "object", and of course the object class is searched last because object is at the root of the inheritance hierarchy. That's waht the MRO discussion is talking about. It doesn't even mention x's dict, because x's dict plays no role in method lookups. > Maybe that's not true of the 2.2.1 interpreter. It is. > I had always imagined that the object dict was used before anything else > in all cases. The object dict (x's dict in the above, which has nothing to do with object's dict) is never searched for methods, and not in any version of Python. Methods can only come from classes in Python. If the name "somemethod" isn't found in x's class or any of its base classes, then "somemethod" is not a method of x. "somemethod" may well be a data attribute of x that's bound to a function that "acts like" a method, or close enough to acting like a method that your app doesn't care about the difference, but even so it's not a method of x if you're careful with words. An object's (as opposed to the builtin class named object) dict in Python can only supply data attributes. > We seem to have a lot of special cases for the unwary to find punji > sticks in. Python does draw distictions between instances and classes, and between method attributes and data attributes. That was as true in 1.0 as in 2.1. As they're universally applicable distinctions in Python, "a lot of special cases" isn't a reasonable characterization. From whisper at oz.net Tue Jul 23 16:08:59 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 23 Jul 2002 13:08:59 -0700 Subject: list to string Message-ID: I have this code: fn = file('foo.txt') txt = fn.readlines() str = ?something?(txt) # or txt.?something?()... What's the something? This is probably so obvious, i'm going to feel dumb, but I havn't been able to find anything in any doc I've looked at. David LeBlanc Seattle, WA USA From aahz at pythoncraft.com Tue Jul 16 21:22:57 2002 From: aahz at pythoncraft.com (Aahz) Date: 16 Jul 2002 21:22:57 -0400 Subject: Queue.get_nowait() sometimes bogusly returns Empty References: Message-ID: In article , Geoffrey Talvola wrote: > >In case you're wondering, this is in Webware's WebKit application server >where there is a pool of N threads, and a queue of (non-thread-safe) servlet >instances acting as a cache. We only want to create servlet instances when >all existing instances are in-use. When a given thread needs a servlet, it >basically does: > > try: > instance = cache.get_nowait() > except Queue.Empty: > instance = new_instance() > # use the instance... > cache.put(instance) > >The problem is that every once in a while get_nowait() returns Empty when >the queue isn't actually empty, so the size of the cache grows slowly and >unboundedly over time. But I'd prefer for the cache to contain at most N >instances where N is the number of threads. You've got several options. Simplest is to change the exception so that it only creates new instances when there are fewer than N instances. What I'd consider doing, though, is make a data queue instead of a servlet cache queue, such that all the servlet threads grab their data from that data queue. Then you have a separate monitor thread that periodically checks the data queue and creates new servlet threads when it hits "too many" items. Conversely, if the data queue stays empty, you delete servlet instances (by passing quit tokens in the data queue would be simplest). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From jubafre at zipmail.com.br Fri Jul 5 14:33:03 2002 From: jubafre at zipmail.com.br (jubafre at zipmail.com.br) Date: Fri, 5 Jul 2002 15:33:03 -0300 Subject: =?iso-8859-1?Q?how=20to=20disable=20maximize=20button=3F?= Message-ID: <3D25D5BA000004FB@www.zipmail.com.br> how i can disable de maximise button in tkinter, i don?t want the user modific the size of the window, i want a real size of window, how can i do it??? Juliano Freitas www.gebrasil.hpg.com.br ------------------------------------------ Use o melhor sistema de busca da Internet Radar UOL - http://www.radaruol.com.br From jimmy at retzlaff.com Fri Jul 26 19:49:11 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Fri, 26 Jul 2002 16:49:11 -0700 Subject: PythonWin ODBC: DSN-less connecting string Message-ID: Gabe Newcomb [mailto:Gabe.Newcomb at noetix.com] wrote: > I'm unable to find the right combination of options to build a DSN-less > connection string with which I can connect to a database using the odbc > module. Has anybody out there found the right way to do this? The current odbc module in win32all doesn't support DSN-less connections. A while back I submitted a patch to Mark Hammond to add support for this - hopefully it'll make it into the next release of win32all. In the meantime I'd be happy to send a copy of my patched odbc.pyd compiled for Python 2.2/2.2.1, or I can also send odbc.cpp if you'd like to compile it yourself for another version of Python. Jimmy From whisper at oz.net Wed Jul 10 19:09:59 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 10 Jul 2002 16:09:59 -0700 Subject: Is this possible in python? In-Reply-To: Message-ID: Yes, all of it is possible. You'll want to use Python, Tkinter and the Pmw/Blt 3rd party packages. You may also be able to do it with wxPython or fltk. (Just because I have this feeling: Please don't email me directly asking about these packages - either ask on comp.lang.python or search yahoo or google.) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of py thon > Sent: Wednesday, July 10, 2002 14:54 > To: python-list at python.org > Subject: Is this possible in python? > > > I need a visual (gui) based app that can take a series of data point > and plot them on a graph like a line chart. Then I would like to > reshape the curve created above by moving the data points with the > mouse. (all using spline interpolation). Then re-output the correct > data to a textfile. I would like to know what part of this can > python perform. > > > Thanks for your time > > > -- > http://mail.python.org/mailman/listinfo/python-list From sholden at holdenweb.com Mon Jul 1 11:28:03 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 1 Jul 2002 11:28:03 -0400 Subject: Newbie that don't understand References: <3d1e262f.3755054@news.clara.net> <3D1E4F80.D8EFBB3E@engcorp.com> <3D1E56EC.7080203@SPAMnwinternet.com> Message-ID: <%w_T8.68926$F16.45491@atlpnn01.usenetserver.com> "Jonathan Hogg" wrote ... > On 30/6/2002 1:55, "Jim" wrote: > > > Some British > > sports cars from the 50's and 60's have the positive > > terminal connected to the chassis (ground for a car), > > so they have a -12v (-6v?) electrical system (or "positive > > ground"). There is no difference, however, between the > > battery in an American car and these British cars - just > > a difference in reference point. As Einstein said, it's > > all relative.. > > [Still being off-topic:] > > Wouldn't a positive ground car rust faster? I seem to vaguely remember > something from school physics about negative ground helping to slow > oxidation by replacing electrons in the chassis. > > If I remember rightly, that's also why iron ships have (or used to have?) > zinc plates bolted to the hull on the inside. When the zinc oxidises it > gains a negative charge which replaces electrons being stripped from the > iron on the outside. > Weren't these devices called "sacrificial anodes", or is my (also ageing) memory deceiving me? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From mgerrans at mindspring.com Tue Jul 2 01:42:56 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 1 Jul 2002 22:42:56 -0700 Subject: Teaching programming -- circular data structures References: Message-ID: > You could always show him a fundamental data structures text that covers > AVL or Red-Black trees . Heck, even a simple doubly-linked list has circular references. From jonathan at onegoodidea.com Fri Jul 26 09:45:34 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 26 Jul 2002 14:45:34 +0100 Subject: __call__ bad style? (was Re: Callable modules?) References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> Message-ID: On 26/7/2002 12:33, in article Ora09.122577$Jj7.2838699 at news1.tin.it, "Alex Martelli" wrote: > (BTW, I've been programming for over _25_ years now -- more than > half of my life...). Hmmm... over 18 years, about 2/3rds of my life. Never thought of it that way before. I don't recall ever intending to be a computer programmer... Jonathan From howard at eegsoftware.com Thu Jul 25 12:37:52 2002 From: howard at eegsoftware.com (Howard Lightstone) Date: Thu, 25 Jul 2002 16:37:52 GMT Subject: DOS-Shell hangs up, python/Tkinter References: <3D3FBF1A.C1531FB3@ipm.fhg.de> Message-ID: Markus von Ehr wrote in news:3D3FBF1A.C1531FB3 at ipm.fhg.de: > Hi, > > when I start my python/Tkinter apps out of a MS-DOS shell > and kill the app, very often the DOS-prompt doesn't come back, > the Shell hangs-up. This is a "known" bug in Tk. http://sourceforge.net/tracker/?func=detail&atid=105470&aid=216289& group_id=5470 The workaround: use pythonw for now........ From spammers.do.not.bother at void.bogus Sun Jul 28 16:57:28 2002 From: spammers.do.not.bother at void.bogus (Magnus) Date: Sun, 28 Jul 2002 20:57:28 GMT Subject: python mysql interface References: <3d444d8e$1_2@nopics.sjc> Message-ID: Adonis wrote: > i hav downloaded Python mySQL, but lacks any documentation? is there a > recommended mySQL module for Python? > > any help is greatly appreciated. > > Adonis Quite often you can find enough of information in the Python interpreter by typing: import theModule help(theModule) /Magnus From donald_welch at nospam.hp.com Wed Jul 24 12:07:12 2002 From: donald_welch at nospam.hp.com (djw) Date: Wed, 24 Jul 2002 09:07:12 -0700 Subject: xml processing : too slow... References: Message-ID: <3D3ED0B0.40906@nospam.hp.com> Shagshag13 wrote: > hello, > > i need to process *each line* of many huge files (> 2 million lines) with xml processing, by now i do it with parseString from > xml.dom.minidom and it's work. > > i do xml validation, extract attributes and tags. > > that's really slow, how do you think i can speed it up ? i'm thinking of writing a xml mini wrapper using things like string.find or > even regular expressions, do you this that's a good idea ? > > thanks in advance, > > s13. > > Maybe pyRXP would work? D From see_reply_address at something.invalid Mon Jul 22 21:29:37 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 23 Jul 2002 13:29:37 +1200 Subject: A better self References: Message-ID: <3D3CB181.9040907@something.invalid> Michael Chermside wrote: >>> > def pretendFormula(x,y,z,t): > return sin(t) * x**y + sqrt(z) > > def MyClass: > def pretend(self): > return pretendFormula(self.x, self.y, self.z, self.t) You could do slightly better than that, if you don't want to be bothered passing in the args one at a time (untested): def pretendFormula(x, y, z, t, **_): return sin(t) * x**y + sqrt(z) def MyClass: def pretend(self): return pretendFormula(**self.__dict__) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From shagshag13 at yahoo.fr Thu Jul 25 06:31:24 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Thu, 25 Jul 2002 12:31:24 +0200 Subject: xml processing : too slow... References: Message-ID: "Fredrik Lundh" a ?crit dans le message de news: j5C%8.677$HY3.191054 at newsc.telia.net... > > from xml.parsers import expat > parser = expat.ParserCreate(None, None) > > import re > p = re.compile("<[^>]*>|\d+") > > for line in file: > # check wellformedness > parser.Parse(line, 0) > # split into parts > print p.findall() > > # check for trailing junk > parser.Parse("", 1) > > sorry to bother, but i get "ExpatError: junk after document element: line 1, column 188" and don't understand what it mean... >>> t = """ 1 2 3""" >>> parser.Parse(t, 0) Traceback (most recent call last): File "", line 1, in ? parser.Parse(t, 0) ExpatError: junk after document element: line 1, column 188 thanks, s13. From marklists at mceahern.com Thu Jul 11 09:07:21 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 11 Jul 2002 08:07:21 -0500 Subject: What does "Sparse is better than dense" mean? (Python Zen) In-Reply-To: <33803989.0207110328.5ef01f1e@posting.google.com> Message-ID: > Although it's in the Humor section I take the Python Zen > (http://www.python.org/doc/Humor.html#zen) quite seriously. > However I can understand what does “Sparse is better than > dense” means. Here's one of my pet peeves: if x: do_one_thing() or: try: foo() except: pass The problem with collapsing these single statement blocks into one line is that it complicates visual scans of a block of code. It certainly doesn't make a hill of beans difference to the compiler. ;-) // m - From claird at starbase.neosoft.com Mon Jul 8 00:12:52 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 7 Jul 2002 23:12:52 -0500 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <7xwus7n5q4.fsf@ruckus.brouhaha.com> Message-ID: <1168F2776BAA90CB.C14ACDD1146382FD.ADE3F3E45D24D67F@lp.airnews.net> In article <7xwus7n5q4.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >Thomas Jensen writes: >> I gotta look into this. >> However I am uncertain as how to structure my program. >> One of the tasks of the program will be to calculate the standard >> deviation of rows of daily values (which are the result of another >> calculation, etc). I was planning on using lists and tuples like this: >> [(date, value), (date, value), ...] >> How well will this perform i wonder? Since lists and tuples are Python >> structures, won't they still be "slow" to traverse? > >Lists and tuples are fast to traverse (they're just vectors in memory) >but I don't see their relevance if by "rows" you mean database rows. >You have to iterate over the rows and compute the SD. I expect the >time for that will be mostly taken by database operations. Me, too. While I know quite well how difficult it is to describe any program that's worth wri- ting, what we've heard of this one puzzles me. I'll summarize by saying simply that I'm with Paul: I *strongly* suspect that database opera- tions swamp arithmetic operations in elapsed time, and that attention to the former will be most rewarding. You've mentioned once already that you might do more with your SQL. I can imagine that much the greatest returns in performance will come from writing more of your algorithms in SQL. That's likely to be a more scalable and satisfying ap- proach than the multi-processing complexities at which you've hinted. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From brueckd at tbye.com Thu Jul 25 12:48:08 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Thu, 25 Jul 2002 09:48:08 -0700 (PDT) Subject: asyncore: limiting number of simultaneous connections? In-Reply-To: Message-ID: On Thu, 25 Jul 2002, Steve Holden wrote: > > > Is there an easy way to limit the number of simultaneous connections > > > to such a server? My preliminary tests indicate that it will happily > > > accept as many connections as the host system will allow, which is not > > > good. I'd like to be able to specify a ceiling on this. > > > > You should be able to just implement your own readable method in the > > listening socket, e.g. (untested and assumes your listening socket is > > derived from asnychat.async_chat): > > > > def readable(self): > > if not self.AllowedToAcceptMoreConnections(): # You implement this > > return 0 > > return asynchat.async_chat.readable(self) > > > Technically, of course, this isn't strictly going to limit the number of > connections to any given maximum since it only determines under what > conditions the listening socket returns readable(), and readable() is used > by asyncore to determine whether the socket should be added to the set for > which a read condition is accepted. Any time the socket is so listed (in the > select.select() arguments) any number of simultaneous connections might > occur, though this is unlikely. No, it's not that unlikely for many servers In any case your listening socket will then accept one, and only one, new connection - the rest stay on the listen queue. Maybe you could elaborate a little more on what you mean because I've used the method I describe above and it's a perfectly acceptable way to throttle your server. I guess if you want to get nitpicky then the above method limits the number of simultaneous connections to N + M, where N is the number your limiting function uses and M is the size of your listen queue, but it's still a fixed maximum. ;-) -Dave From mhammond at skippinet.com.au Fri Jul 26 08:30:11 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 26 Jul 2002 22:30:11 +1000 Subject: PyXPCOM and SVG In-Reply-To: Message-ID: > David LeBlanc > Are you overlooking the Mozilla active-x control - or is that gecko only? I've never used this, but I think you are going to find this is an in-process control. It will be hosted in the container app, rather than a remote mozilla.exe firing up. Further, the control itself generally doesnt provide the location bar, toolbar, menus and other chrome. So I think it is a different thing - AFAIK, the active-x control doesn't provide remote control of mozilla-the-application. Mark. > > Johann H?chtl wrote: > > > > > Well XUL is of course not my primer as i can always use the wxwindows > > > widgets. But I thought about the ability to "remote control" mozilla > > > (maybe gecko and the upcoming SVG features) and therefore I > > need xpcom, or? > > > > There is currently no technique to remote control Mozilla. xpcom is > > inprocess only. There is a bug to add some kind of RPC to xpcom, but I > > don't think it is really being worked on. It should be possible to do > > what you want via embedding though. From never at mind.info Sun Jul 14 19:10:27 2002 From: never at mind.info (G. Willoughby) Date: Mon, 15 Jul 2002 00:10:27 +0100 Subject: Getting an error when quitting an app using a call 'self.master.quit'? Message-ID: I have been getting an error when quitting an app using a menu to call 'self.master.quit'. the error is: 'The instruction at "0x00d7a0a3" referenced memory at "0x00000008". The memory could not be "read".' My OS is winXP Pro any ideas whats going on? --G. Willoughby From frob1 at archerlabs.net Tue Jul 16 00:04:02 2002 From: frob1 at archerlabs.net (frobenius) Date: 15 Jul 2002 21:04:02 -0700 Subject: curses, multiplexing, select / poll, and resizing Message-ID: preface: i'm new to python, semi-new to curses, but an otherwise experienced programmer. i'm writing a telnet client using curses to separate input and output into different windows. to multiplex the I/O from the user and the host i'm using poll(). when i resize the terminal window (i'm using win32 PuTTY to connect to FreeBSD, running Python 2.2) i generate an exception which kills poll(): Select Error: 4, Interrupted system call without a useful traceback (AFAICT). i searched online for help, found the source to cplay: a python curses front-end to various audio apps. in there the programmers has the code signal.signal(signal.SIGWINCH, self.handler_resize) followed by the code def handler_resize(self, sig, frame): ## curses trickery curses.endwin() self.w.refresh() [more update stuff.....] i've tried to adapt this trick to work with my program, but even though i register a signal handler for the resize signal, the poll() still gets a select.error exception triggered, AFTER the signal handler has returned. - how to i capture and ignore this w/out accidentally capturing a real poll() error? - as far as documentation goes, there's some serious magic with this endwin / refresh handler trick. (i finally found out what it does by consulting the ncurses manpages.) i feel like terminal window resize issues are common enough that people should have documentation on this somewhere, e.g. in the python curses tutorial. - where is the curses module source? i found the submodules (curses.ascii, etc.) in /usr/local/lib/python-2.2/curses/ on my machine but can't seem to be able to find the base package source. - other gotchas? thanks in advance, Frob PS i'll probably end up contributing my python-curses readline library, which makes nice single-line entry pads. From jb at cascade-sys.com Thu Jul 25 15:57:47 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 25 Jul 2002 12:57:47 -0700 Subject: Numeric data question References: <%Nz%8.15893$A72.86385@news1.mts.net> Message-ID: <3D40583B.974A9C19@cascade-sys.com> Terry Reedy wrote: > "terry" wrote in message > > In general it's not appropriate/legal to use > > integer or floating point math when dealing with money. It > > creates too many coding dependent variations in results - not to > > mention maintenance nightmares. > > If the amounts of money you are dealing with are well less than the > max, and if you are only doing + and - (accounting in the strict > sense) and maybe * by int amounts, Accounting per se cannot be limited to the above operations. Think of tax tables, withholding percentages, asset depreciation, interest calculations, etc., etc. "Accounting" generally is far from trivial and is way more complicated than balancing your checkbook. > ints using the lowest denomination > (cents in the US) work just fine. +/- 2 billion cents is +/- 20 > million dollars. Python's integration of longs with ints should > remove the upper limit constraint. Financial calcs with interest and > other rates requires more care. Note that "currency" is more than just dollars and cents. First off, even in US currency there is need to talk about fractions of a penny. E.g., in the stock market, 1/8 "point" is $0.125. Also you quickly run into scale problems with non-US currencies, e.g., 2 billion Lira is too harsh an upper limit. (My last hotel bill in Venice was over L 1.000.000). FWIW, Microsoft COM defines a currency type as an 8-byte, two's complement integer, scaled by 10,000. This is the format VB uses. This gives a fixed point decimal value with 15 digits of whole number and 4 digits of fraction. A lot of databases allow the designer to explicitly specify field size and precision to better control the trade-off of value range vs. space consumed. Luckily nobody I know of still uses a non-decimal currency, like the old English system. Lesse, 5 shillings to the crown, 4 crowns to the pound, 2 shillings per florin, two sixpence (12 pennies) per shilling, two tuppence per groat, two pennies per tuppence, 2 farthings to the ha'penny, and they actually minted coins as small as 1/4 farthing. Basically 12 pennies to the shilling, and 20 shillings to the pound, or 240 pennies per pound. THAT was when money was worth something, when you minted coins worth 1/16 of a cent or 1/3840th of your basic monetary unit! Regards --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From anton.wilson at camotion.com Mon Jul 29 19:49:00 2002 From: anton.wilson at camotion.com (anton wilson) Date: Mon, 29 Jul 2002 19:49:00 -0400 Subject: global interpreter lock not working as it should In-Reply-To: References: Message-ID: <200207292348.TAA31011@test-area.com> On Monday 29 July 2002 07:35 pm, Martin v. Loewis wrote: > anton wilson writes: > > I'm having a problem where the interpreter in ceval.c does not let > > threads run concurently. Any thread that holds the lock never gives > > up the lock until it has run to completion. > > I don't believe that statement. Do you have an example program that > demonstrates you claims? > > To demonstrate my point, consider > > import threading, time > > def func1(): > for i in range(3): > print "FUNC1" > time.sleep(1) > > def func2(): > for i in range(3): > print "FUNC2" > time.sleep(1) > The reason your code works is because you explicitly give up the CPU with the sleep calls. If you remove both time.sleep calls the results will look like: FUNC2 FUNC2 FUNC2 FUNC1 FUNC1 FUNC1 > t = threading.Thread(target=func1) > t.start() > func2() > > On my Linux system, it prints > > FUNC2 > FUNC1 > FUNC1 > FUNC2 > FUNC2 > FUNC1 > > Regards, > Martin From remi at cherrypy.org Mon Jul 8 10:09:22 2002 From: remi at cherrypy.org (Remi Delon) Date: 8 Jul 2002 07:09:22 -0700 Subject: ANN: CherryPy-0.2 released Message-ID: <585c0de9.0207080609.1c969d5a@posting.google.com> We're pleased to announce the release of CherryPy-0.2. This release fixes a minor bug that prevented non-Unix users from using the CookieAuthenticate module. ------------------------------------------ About CherryPy: CherryPy is a Python-based tool for developing dynamic websites. It uses many powerful concepts together, which makes it unique in its approach to website development. CherryPy sits between an application server and a compiler. You write source files, compile them with CherryPy and CherryPy generates an executable containing everything to run the website (including an HTTP server). CherryPy has been used in production for more than 6 months are we are now releasing it to the public, under the GPL license. Key properties/features of CherryPy are: - Based exclusively on Python (runs everywhere Python runs) - Delivers fast, robust, and scalable websites - Uses OOP as well as AOP (Aspect Oriented Programming) concepts to develop websites - True separation of content and presentation - Simple but powerful templating language - Powerful standard libraries to make your life easy Other properties/features are: - Can be linked to many databases (Oracle, Sybase, MySql, PostgreSql, ...) - Can run behind another webserver (Apache, ...) - Easy clustering and load-balancing set up for high-traffic websites Remi. http://www.cherrypy.org From sholden at holdenweb.com Sat Jul 27 00:55:24 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 00:55:24 -0400 Subject: how to count lines in a file ? References: <2259b0e2.0207250631.1e093e64@posting.google.com> <7aU%8.139472$vm5.4528856@news2.tin.it> <15682.10208.325890.497677@12-248-11-90.client.attbi.com> Message-ID: "Skip Montanaro" wrote in message news:15682.10208.325890.497677 at 12-248-11-90.client.attbi.com... > > >> Not quite. Any cycle containing an object with a __del__ method will > >> be skipped and left to languish in memory-limbo forever. > >> > Steve> You mean the garbage collector doesn't *collect* data that > Steve> appears in cycles? That's not my understanding (which doesn't > Steve> nevessarily mean it's dissonant with reality). > > No, just those cycles where at least one of the involved objects contains a > __del__ method. In those situations, it's the programmer's responsibility > to break the cycle. Thanks for the clarification. I hadn't understood that the existence of a __del__() would modify the GC's actions. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From Answer.via.news.please.prikryl at skil.nospam.cz Fri Jul 26 07:24:53 2002 From: Answer.via.news.please.prikryl at skil.nospam.cz (Petr Prikryl) Date: Fri, 26 Jul 2002 13:24:53 +0200 Subject: test -- please, ignore it... Message-ID: <3d412ef5$1@post.newsfeed.com> *** post for FREE via your newsreader at post.newsfeed.com *** thanks -- Petr Prikryl (prikrylp at skil dot cz) -----= Posted via Newsfeed.Com, Uncensored Usenet News =----- http://www.newsfeed.com - The #1 Newsgroup Service in the World! -----== 100,000 Groups! - 19 Servers! - Unlimited Download! =----- From jpm at papercut.org Mon Jul 29 23:33:17 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Mon, 29 Jul 2002 23:33:17 -0400 (EDT) Subject: [ANN] Papercut 0.8.3 - python nntp server Message-ID: Papercut is a multi-threaded news server written in Python. Its main objective is to integrate existing web based message board software (Phorum [http://phorum.org] on this case) with a Usenet front-end. However, its extensibility enables developers to write their own container for the storage of the Usenet articles (messages). That means that the code is extensible enough that _you_ could write new containers to integrate the news server with other web message board projects or even with other ways to store the messages. The source code is available freely under the BSD license, which means you can do whatever you like with it. I do welcome any and all contributions to the project :) A quick description of the changes on this release: - A lot of work re-designing the way the various storage modules work and also doing the initial code to support NTTP authentication. More changes are still to come, but this version already serves as a nice initial version with most (if not all) of these features working. New features include a standalone mysql storage module (no web front-end), an authentication module for Phorum and the concept of a 'read-only' / 'read-write' server with password protection. More information can be found on the project site -> http://papercut.org Cheers, Joao Prado Maia From aleax at aleax.it Sat Jul 20 04:35:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 08:35:33 GMT Subject: NEW TO THIS: Assigning values to strings in list? References: Message-ID: Chris Liechti wrote: ... >>> Johannes Graumann wrote in >>>>>names = ["one","two","three"] >>>>>values = [ 1,2,3] >> --> DO SOMETHING HERE >>>>>print one >> 1 > > my tip: don't pollute the global namespace. Seconded! Don't pollute local ones either, btw:-). > if you do it with a class it's easier anyway: > >>>> class Lexikon: > ... def __init__(self, values): > ... self.__dict__.update(values) > ... >>>> l = Lexikon(dict(zip(names,values))) >>>> l.one > 1 Yay, the good old Bunch idiom. You can do a tiny bit better if this specific use is widespread for you: class Namespace: def __init__(self, names, values): self.__dict__ = dict(zip(names,values)) n = Namespace(names, values) print n.one but that's a factoring detail. The key idea is that said little innoucous-looking l. or n. before the dynamically determined name saves a LOT of problems. Namespaces are a honking great idea. Let's do more of those. Alex From pecora at anvil.nrl.navy.mil Tue Jul 9 17:15:19 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Tue, 09 Jul 2002 17:15:19 -0400 Subject: Why self? References: Message-ID: <090720021715194593%pecora@anvil.nrl.navy.mil> In article , Mark McEahern wrote: > Do you use emacs? No >It would probably be trivial to write a Lisp macro that > would transform this: > > y = x**2 * t/z + a * FFT(tseries) > > into: > > x = self.x > t = self.t > z = self.z > a = self.a > tseries = self.tseries > > y = x**2 * t/z + a * FFT(tseries) > > self.y = y > > // m Yuck. Lots of effort there. -- Lou Pecora - My views are my own. From mis6 at pitt.edu Wed Jul 3 13:47:37 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 3 Jul 2002 10:47:37 -0700 Subject: Newbie question on Tkinter Message-ID: <2259b0e2.0207030947.4a13834a@posting.google.com> I have found a confusing (to me) behavior of Tkinter in displaying GIF images. Consider the following four programs (assuming you have a GIF image called 'picture.gif' in the current directory): #Program 1: works import Tkinter root=Tkinter.Tk() img=Tkinter.PhotoImage(file='picture.gif') lbl=Tkinter.Label(root,image=img) lbl.pack() Tkinter.mainloop() #Program 2: doesn't work import Tkinter root=Tkinter.Tk() lbl=Tkinter.Label(root,image=Tkinter.PhotoImage(file='picture.gif')) lbl.pack() Tkinter.mainloop() #Program 3: doesn't work import Tkinter def DisplayPicture(root,picture): img=Tkinter.PhotoImage(file='picture.gif') lbl=Tkinter.Label(root,image=img) lbl.pack() root=Tkinter.Tk() DisplayPicture(root,'picture.gif') Tkinter.mainloop() #Program 4: works import Tkinter def DisplayPicture(root,picture): global img img=Tkinter.PhotoImage(file='picture.gif') lbl=Tkinter.Label(root,image=img) lbl.pack() root=Tkinter.Tk() DisplayPicture(root,'picture.gif') Tkinter.mainloop() The second program should give the same output of the first one, however the first one works, the second one gives a transparent picture! Why ?? The only difference is that there is no explicit name for the PhotoImage object. Moreover: program 3 has an explicit name for the PhotoImage, but the picture is still transparent ! Why ?? By trials, I discovered that it is possible to fix the problem at the price of making the PhotoImage name a global variable (see program 4). How can I avoid that ? I have the same problem both with Python 1.5 and Python 2.1 on a Red Hat Linux 7.3 machine. I also tried with Python 2.2 on Windows 98: its the same. Therefore I don't think this is a bug, it there should be some logic in the way Python display image objects via Tcl/Tk; it seems to me that there is an issue with the naming of objects and global/local variables. Anybody can help me to understand ? Is there some good reference on Tkinter ?(I have the one by Fredrik Lundh on http://www.pythonware.com/library/tkinter/introduction/) P.S. BTW, how to display jpeg images ? From timothyrandolph at yahoo.com Fri Jul 19 19:46:27 2002 From: timothyrandolph at yahoo.com (Tim Randolph) Date: 19 Jul 2002 16:46:27 -0700 Subject: Python Sets (no not those sets) Message-ID: <7f2b571b.0207191546.67583b88@posting.google.com> Check out: http://labs1.google.com/sets?hl=en&q1=Tim+Peters&q2=Fredrik+Lundh&q3=Alex+Martelli&q4=Guido+van+Rossum&q5=&btn=Large+Set It's worth putting this URL back together if needed. Or go to: http://labs1.google.com/ and type in: Tim Peters Fredrik Lundh Alex Martelli Guido von Rossum It's an amazing technology. Tim From d95lars at dtek.chalmers.se Tue Jul 30 08:11:57 2002 From: d95lars at dtek.chalmers.se (Lars Lundgren) Date: Tue, 30 Jul 2002 14:11:57 +0200 Subject: Nested stream line iteration Message-ID: Hi, I am an experienced programmer that tries python for the very first time. I visited python.org and then wrote this program: #!/usr/bin/env python import sys, os, time, fileinput, string def build( module, tag ): os.system( "cvs co " + tag + " " + module) filename = module + "/cvsDependencies" for line in fileinput.input(filename): [m,t] = string.split( line ) build( m,t ) os.chdir(module) os.system( 'make -DVERSION="' + tag + '"') build( "my_module", "-r v1_0" ) When I run it I get the following error: raise RuntimeError, "input() already active" RuntimeError: input() already active As I understand it, this means that it is not allowed to nest input() like I do. Is that correct? Then is there a working solution to my problem? (I'm using Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386) Thanx /Lars L From tjreedy at udel.edu Tue Jul 16 02:32:27 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Jul 2002 06:32:27 GMT Subject: Maximizing observations from Sparse matrices References: Message-ID: <%5PY8.223877$vq.11984177@bin6.nnrp.aus1.giganews.com> wrote in message news:mailman.1026771383.3938.python-list at python.org... > I am running a regression that gathers its data from a panel dataset > (cross-sectional time series). Because the dataset is sparse I must > sometimes either drop cross-sections or variables or some combination of the > two to avoid a singular matrix. A quick, extremely simplified example: Analyszing data matrices with holes is a notoriously difficult and messy problem. Look up 'missing data' in statistics books for others have done. TJR From matt_gerrans at hp.com Tue Jul 9 19:42:49 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Tue, 9 Jul 2002 16:42:49 -0700 Subject: Converting a hex string to a number References: <0017278C.C22236@smiths-aerospace.com> <3d2b3c2f.3993392@news.dsl.pipex.com> <3d2b69b6.15643974@news.dsl.pipex.com> Message-ID: > Using exec or eval without explicit dictionaries _is_ dangerous, if > you can't absolutely trust the data. Hey Gerhard, can you elaborate a bit on explicit dictionaries or refer me to some reference material on this? (I did some searching on Python.org, but only found a few offhand references). - Matt From phr-n2002b at NOSPAMnightsong.com Sat Jul 6 23:46:28 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 06 Jul 2002 20:46:28 -0700 Subject: structs in python References: Message-ID: <7xd6u05hez.fsf@ruckus.brouhaha.com> "Kevin O'Connor" writes: > Unfortunately, this quickly becomes cumbersome when the code starts to make > frequent references to tuple positions instead of member names. For > example, one would see code like "delta = (p1[0] - p2[0], p1[1] - p2[1])". > Ideally, this code would read something more like "delta = (p1.x - p2.x, > p1.y - p2.y)". > > Clearly, the use of classes makes the code much more readable, but > unfortunately the declarations necessary to instantiate a class is often > too much of a hassle for small and infrequently used objects. It doesn't take much: class frob: pass p1 = frob() p1.x = 3 p1.y = 5 etc. That's what I usually do. From whisper at oz.net Fri Jul 19 12:16:55 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 19 Jul 2002 09:16:55 -0700 Subject: HTML DOM parser? In-Reply-To: <3D3817E8.13203964@engcorp.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen > Sent: Friday, July 19, 2002 6:45 > To: python-list at python.org > Subject: Re: HTML DOM parser? > > > "Daniel E. Burrow" wrote: > > > > My present task requires the automation of IE. After much prayer, I > > found that the "dom = ie.Document" assignment IS case sensitive. The > > lower case form of "ie.document" just would not work for my > > ActiveState ActivePython 2.2.1 distribution. > > That's odd. I have never had to worry about case in almost any > aspect of IE automation, especially this one. > > Does anyone with greater knowledge of the guts of this stuff > have any input on why Daniel would have to worry about case > while I do not? > > Peter David LeBlanc wrote: > While trying to figure out how to make the recently posted (by Paul Rubin) > ie navigation example work, I had occasion to run makepy.py on "Microsoft > Internet Controls". After doing this, the sample would fail on "ie.visible = > 1". Removing the generated file would return the sample to working order. Mark Hammond replied: "Was the problem "AttributeError: visible"? If so, the problem is simply that the correct name for the property is "Visible". makepy is case sensitive." If he's run makepy, then the ?mapping? gets used, which is case sensitive. I had to ask too :-) Dave LeBlanc Seattle, WA USA From imbosol at vt.edu Mon Jul 15 18:28:30 2002 From: imbosol at vt.edu (Carl Banks) Date: Mon, 15 Jul 2002 18:28:30 -0400 Subject: Python's Lisp heritage References: Message-ID: Christopher Browne wrote: > Dynamic scope buys you the ability to not need to specify _all_ the > values that you might be customizing. As does lexical. > If a new Emacs mode requires adding in a bunch of additional > parameters, dynamic scope lets them be visible throughout the scope > during which they are "live" as opposed to just within the environment > in which they were defined. You can put all the defuns inside a let form. > From a paper on Emacs: > > "Some language designers believe that dynamic binding should be > avoided, and explicit argument passing should be used > instead. Imagine that function A binds the variable FOO, and calls > the function B, which calls the function C, and C uses the value of > FOO. Supposedly A should pass the value as an argument to B, which > should pass it as an argument to C. > > This cannot be done in an extensible system, however, because the > author of the system cannot know what all the parameters will > be. Imagine that the functions A and C are part of a user extension, > while B is part of the standard system. The variable FOO does not > exist in the standard system; it is part of the extension. To use > explicit argument passing would require adding a new argument to B, > which means rewriting B and everything that calls B. In the most > common case, B is the editor command dispatcher loop, which is > called from an awful number of places. > > What's worse, C must also be passed an additional argument. B > doesn't refer to C by name (C did not exist when B was written). It > probably finds a pointer to C in the command dispatch table. This > means that the same call which sometimes calls C might equally well > call any editor command definition. So all the editing commands must > be rewritten to accept and ignore the additional argument. By now, > none of the original system is left!" > > If all you have is lexical scoping, parameters have to get explicitly > passed down the chain in order to get from function A to function C. > That means introducing additional parameters to function B, which > didn't actually care about those extra values. (let ((foo whatever)) (defun A (x) (setq foo x) (B (symbol-function C))) (defun C () (use-in-some-way foo))) > Most of the time, lexical scope is likely to be more useful. But > there are places where dynamic scope is to be preferred. I disagree. The only time I have found a lexical scope not able do the job is when the scope is too large to be convenient for a single file, and rarely if some code needs access to a scope but can't be physically placed within it. But in those cases, a way for different lexical scopes to share a namespace is enough. Dynamic scoping should die fast. -- CARL BANKS http://www.aerojockey.com From pinard at iro.umontreal.ca Sun Jul 7 08:45:45 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 07 Jul 2002 08:45:45 -0400 Subject: procmail replacement in Python In-Reply-To: References: <3u8pea.617.ln@127.0.0.1> Message-ID: [Sheila King] > The tarball URL for the pycmail packages is not working for me. > Did anyone grab a copy that they can share? Here is a copy of my copy: -rw-rw-r-- 1 pinard pinard 15107 2002-06-19 10:27 /bpi/titan/pub/poste/pycmail_0.1.1.tar.gz -------------- next part -------------- A non-text attachment was scrubbed... Name: pycmail_0.1.1.tar.gz Type: application/x-tar-gz Size: 15107 bytes Desc: not available URL: -------------- next part -------------- -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From anthony at interlink.com.au Tue Jul 2 02:04:34 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 02 Jul 2002 16:04:34 +1000 Subject: zipfile and Tru64 UNIX In-Reply-To: Message-ID: <200207020604.g6264YT24484@localhost.localdomain> >>> Albert Chin-A-Young wrote > Ok, I did some digging. The attached patch solves the problem. I think > this is a problem for any machine where sizeof(long) == 8. Is there an > easier way to force crc to be a 32-bit int. From the typesnumeric.html > document: > Plain integers (also just called integers) are implemented using > long in C, which gives them at least 32 bits of precision. Please submit this as a patch to Sourceforge, if you haven't already. Thanks, Anthony > -- > albert chin (china at thewrittenword.com) > > -- snip snip > --- Lib/zipfile.py.orig Mon Jul 1 23:10:00 2002 > +++ Lib/zipfile.py Mon Jul 1 23:10:26 2002 > @@ -346,7 +346,7 @@ > raise BadZipfile, \ > "Unsupported compression method %d for file %s" % \ > (zinfo.compress_type, name) > - crc = binascii.crc32(bytes) > + crc = struct.unpack(' if crc != zinfo.CRC: > raise BadZipfile, "Bad CRC-32 for file %s" % name > return bytes > -- > http://mail.python.org/mailman/listinfo/python-list > -- Anthony Baxter It's never too late to have a happy childhood. From cp at onsitetech.com Wed Jul 17 18:51:02 2002 From: cp at onsitetech.com (Curtis Poe) Date: 17 Jul 2002 22:51:02 GMT Subject: Using Python to talk to a Perl SOAP::Lite server Message-ID: Hi all, My apologies if this is viewed as off-topic. I have a SOAP server written in Perl using SOAP::Lite. I have no problem using this to instantiate an object using Perl and then making method calls on it. However, the client software is being written in Python and my coworker (who, like me, is unfamiliar with SOAP), cannot seem to perform the same task. If I recode the SOAP server to use functions instead of methods, he has no problem connecting and getting appropriate responses. Here's the Python code: ###################### from ZSI.client import Binding server = Binding(url='/soap/temper.cgi', ns='http://192.168.1.26/Temperatures', host='192.168.1.26', port=80, soapaction='') try: print server.f_f2c(100) # Works print server.new() # Doesn't except: print "Got XML I can't parse:" print server.ReceiveRaw() ###################### Note that the line marked "Works" is a simple function call and is not dependant on an object. And here's the XML that it prints: ###################### <_format xsi:type="xsd:string">%.2f ###################### I've been searching through mailing lists, Google, and FAQS for about three hours and I am not even close to getting an answer. Is it possible that Python cannot instantiate a Perl object via SOAP? (I don't know anything about SOAP, either, so this may be a stupid question). -- Curtis "Ovid" Poe, Senior Programmer, ONSITE! Technology Someone asked me how to count to 10 in Perl: push @A, $_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//; shift @a;shift @a if $a[$[]eq$[;$_=join q||, at a};print $_,$/for reverse @A From peter at engcorp.com Mon Jul 22 20:16:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Jul 2002 20:16:24 -0400 Subject: Callable modules? References: <7xznwk1hfy.fsf@ruckus.brouhaha.com> <7xr8hwnu3s.fsf@ruckus.brouhaha.com> <3D3C3F81.6090001@sschwarzer.net> <7xu1mr7jmr.fsf@ruckus.brouhaha.com> <3D3C971E.D0386D7D@engcorp.com> Message-ID: <3D3CA058.2FA5D211@engcorp.com> Chris Liechti wrote: > > Peter Hansen wrote in > news:3D3C971E.D0386D7D at engcorp.com: > > > Paul Rubin wrote: > >> Does that reasoning not also apply to class instances? Why should > >> class instances be callable through the __call__ method? > > > > Because that's how you create an instance of the class (i.e. an > > object). > > no, no, read again... he already talks of instances, not classes. i.e. the > __call__ method. Oops, thanks for the correction. In that case I'll change my comment to point out that for certain classes, it is quite appropriate for their instances to have __call__ because they are intended to simulate methods or classes themselves (i.e. other things which are normally callable). They don't have __call__ just to let somebody use an unusual syntax to do something that looks a little wordy done differently. For example, given an object which has a method that does something useful obj.doUsefulStuff() but which does not itself have any particular reason to pretend to be a callable object, overriding __call__ to let you do obj() and accomplish the same thing would just make the code less readable, wouldn't it? > > Although you can do as you wish, of course, I want to chime in > > with a "this is a really bad idea" and hope you don't follow through > > on it. This is, even in the best case, going to make your code > > less readable to anyone else. It is also likely to cause > > maintainability problems because making the claim "but this module has > > only one function!" almost certainly means it will not stay that way > > forever. > > no need for such a restriction. just because an object has a __call__ > method does not mean that it must not have any others. a module is an > object after all, so there is realy no good reason to prevent it from > having a __call__ method... Oh, I wouldn't want to _prevent_ it, but I can't see the extreme need for it since the potential useful cases are so rare, IMHO. > > > Any time you find yourself going to a lot of effort to work around > > what feels like a small wart or syntactical ugliness (neither of which > > even apply in this case, IMHO) you should probably stop yourself and > > say "whoa, what was I thinking?" and do it the standard way. > > yeah, its not realy needed. however having a __call__ function in modules > would be nice for plugin systems, where a plugin == a module/file.py. it > would allow to init the plugin by calling the module instead of defining an > init() function or whatsoever. At first I thought this might be a nice idea, but then I realized on would be doing it only to avoid typing "modulename.init()" which is so clear and simple that I can't see why one would want to obfuscate matters by doing modulename() instead. Maybe it's just me... -Peter From dutoitc at hotmail.com Sun Jul 14 16:52:05 2002 From: dutoitc at hotmail.com (Cedric Dutoit) Date: Sun, 14 Jul 2002 22:52:05 +0200 Subject: List to STR to List References: <7clY8.357964$R61.347463@rwcrnsc52.ops.asp.att.net> Message-ID: <3D31E475.8030402@hotmail.com> Larry wrote: > I did a typo...should be... > > List1 = [1,2,3] > String1 = str(List1) > > Is there now a way to convert my String1 variable back into a list??? Another way... more funnier so I like it ! List2 = [int(el) for el in String1[1:-1].split(",")] C.Dutoit From dcinege at psychosis.com Wed Jul 31 17:30:40 2002 From: dcinege at psychosis.com (Dave Cinege) Date: Wed, 31 Jul 2002 17:30:40 -0400 Subject: lexing nested parenthesis (for a Python Unix Shell) In-Reply-To: References: Message-ID: <200207311730.40206.dcinege@psychosis.com> On Wednesday 31 July 2002 16:32, Bengt Richter wrote: > if 1 and (var1 or qm('-d /etc/')): > > would already be legal Python. That's not the point. I'm not making legal Python but a 'short hand' subset, specifically a Python Unix Shell (aka bourne shell replacement) The idea right now is to parse and replace the short hand with python constructs that are predefined, and then let python run all of it. It's either that or I basically handle ALL the parsing and pretty much recreate the wheel. You see I only want to deal with 'my' subset...python will then run (via compile()) and handle the remaining grammer, indentation, etc. Things get a bit more difficult in interactive mode, but I feel this is still the best route. > Maybe a few examples with un-nested and nested parens (and nested ?(...) > constructs??) together with what Python you would like to have them > transformed to would get you some useful help. I haven't speced it all out yet, but I'm pretty much decided I want to contain most all thing within ()'s and prefix the first ( with an identifier. To put things in perspective: In bash sh: [ -d /etc/ ] In pysh: =(-d /etc/) (Maybe =('-d /etc/') ) At runtime it will be parsed and replaced by: pysh_test('-d', '/etc/') Somethings will not be so easy as this, as they will not be a simple function name replacement. It can get ugly when I need to work recursivly through nested functions. I need to work on the next item first so I know how to handle output. IE if the return is normally a list, and it's nested in what requires and string, I have to account for that. In bash: for line in $(cat *.py); do echo $line; done # Yep time to retire this POS In pysh for $line in !(cat *(*.py)): print $line ;; # Ain't it pretty? FYI $ == variable prefix (I might be able to avoid using this, dunno) !() == Command Substitution *() == Shell glob (might become seemless, ie I search for glob chars!) ;; == explict newline Parsed to python: for line in pysh_cmdsub_inpath('cat',pysh_ListToArgStr(pysh_glob('*.py'))): print line # You can visualize the pysh functions... > 'Better' is a waste of time unless we're working on the real problem ;-) The problem is Python already works. : > I KNOW how I can do all this, I just don't feel like writing a complete parser if I can reuse something Python itself already uses for parsing. -- The time is now 22:48 (Totalitarian) - http://www.ccops.org/ From phr-n2002b at NOSPAMnightsong.com Mon Jul 8 00:23:51 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 07 Jul 2002 21:23:51 -0700 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> <3D281AE3.3070800@ob_scure.dk> <3D282290.1050101@ob_scure.dk> <7xk7o7n4sc.fsf@ruckus.brouhaha.com> <3D282FF8.6040602@ob_scure.dk> <7x3cuvsnc7.fsf@ruckus.brouhaha.com> <3D2864DE.6030608@ob_scure.dk> Message-ID: <7xvg7qj19k.fsf@ruckus.brouhaha.com> Thomas Jensen writes: > > Is 5 hours acceptable, if your data doesn't get any bigger? > > It not, what's the maximum you can accept? > > 5 hours is about the maximum acceptable. Usually the time is a little > shorter, but 5 hours happen when much new data is added. > However, this is a case of "faster is better". 5 hours is acceptable > but 1 minute would open up new business oppertunities. OK, that make sense. > > I think the bottleneck is going to be the database. You might not get > > better throughput with multiple client CPU's than with just one. If > > you do, maybe your client application needs more optimization. > > We already have 2 DB Servers, a master replicating changes to a slave. > Our analysis shows that most database operations are/will be SELECTs. > Adding more DB servers is trivial, especially if we migrate to MySQL > (well, cheaper at least :-) If you're doing all these single row selects without many updates, and you're not doing many joins, it really sounds more and more like an SQL database isn't the best tool for your task. > Before going on with the distributed approach, I will probably write a > "proof of concept" demo. Should this demo show, that it is not worth > the effort, I will put it aside for now. Fair enough. You could just check the CPU load on your SQL server right now, as your single client runs. > But all that apart - the distributed part is not really the hard or > complex part about this project. I understand that as soon as the > calculations take place in more than one thread (be it on one or more > CPUs/machines) it adds some complexity. However, designing the > application in such a way that parralell computations are > possible/plausible, can't be that bad I think. What kinds of calculations are these really? The only one you've described so far is selecting a bunch of rows and computing the SD of the numbers on one column. It may be fastest to do that with a server sided stored procedure. > I really see all this distribution talk as one among several > optimization strategies. OK, that's good, as long as you see there's a range of approaches. Sometimes all someone will have is a hammer and everything looks like a thumb ;-). > An extreme example of another strategy: Develop the entire thing in > assembler, using flat files or entirely bypassing the file-system. > I done correctly, it would probably outperform other strategies by > far, but it would also be: > * Less maintainable > * Less readable > * a lot harder to use from ASP/PHP > * etc If your data layout is simple enough you might just store it in a fixed-width record format, then mmap() it into memory and crunch it with a C program (or even a Python program). That approach is generally simple and fast. It will probably outperform any SQL approach by orders of magnitude. From rs at onsitetech.com Wed Jul 3 13:58:14 2002 From: rs at onsitetech.com (Robb Shecter) Date: 03 Jul 2002 17:58:14 GMT Subject: multiple inheritance & __init__ References: Message-ID: <3D233AF8.70701@onsitetech.com> Interesting - I had the sazme issue yesterday. I forgot / didn't realize, though, that you have to call __init__ explicitly. I also implemented an Observer class that I used via multiple inheritance. So, although I'm not answering your question, I thought I'd post the classes that I came up with. They're fairly Java-like - I have mixed feelings about that: class Observable: """ An object that generates events that other objects are interested in knowing about. """ def __init__(self): self.__observerList = [] def addObserver(self, anObserver): "Add the given listener to the list of observers" self.__observerList.append(anObserver) def notifyObservers(self, aMessage): """Call the notify() method on all observers in my list. The aMessage parameter is appliction-specific.""" for observer in self.__observerList: observer.notify(self, aMessage) class Observer: """ An object that wishes to be notified when something has happened. """ def notify(self, aSender, aMessage): "Recieve a message from an observable object." print `self` + " received notification: " + `aMessage` From jepler at unpythonic.net Tue Jul 30 21:20:21 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 30 Jul 2002 20:20:21 -0500 Subject: global interpreter lock not working as it should In-Reply-To: <200207302247.SAA21093@test-area.com> References: <200207302247.SAA21093@test-area.com> Message-ID: <20020730202014.A3224@unpythonic.net> > On Tuesday 30 July 2002 07:18 pm, brueckd at tbye.com wrote: > > Quick tangential question: if there's no blocking of any kind, why are you > > using threads, anyway? Off the cuff thinking says this seems like a misuse > > of them. On Tue, Jul 30, 2002 at 06:48:40PM -0400, anton wilson wrote: > For a real-time system. ;) It will work. It would just be nice if they > switched exactly every 10 byte codes becuase that means they only use about > 10 to 20 milliseconds each. Realtime? Really? So can you tell me what the upper-bound on the runtime of >>> x = 3 on the hardware you're targeting? Jeff From stefan.heimann at web.de Mon Jul 29 05:11:38 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 29 Jul 2002 09:11:38 GMT Subject: TAB completion References: Message-ID: Dave Cinege wrote:: > On Sunday 28 July 2002 6:19, Stefan Heimann wrote: >> Hi! >> >> I have a application with a builtin interactive shell. I use the >> readline module for command completion and history browsing. The >> following code enables filename completion: > > Is your work based on the cmd module? No it is not. I have looked at the cmd module, but its completion function does not contain filename completion. Bye Stefan From blokeatiidotnet Mon Jul 22 11:15:39 2002 From: blokeatiidotnet (Rob Hall) Date: Mon, 22 Jul 2002 23:15:39 +0800 Subject: i++ in Python? References: <5606b639.0207181429.2c6d2569@posting.google.com> Message-ID: <3d3c2af0$0$25221@echo-01.iinet.net.au> "Alex Martelli" wrote in message news:doSZ8.84684$Jj7.2150581 at news1.tin.it... > David Eppstein wrote: > > > In article <5606b639.0207181429.2c6d2569 at posting.google.com>, > > otis_usenet at yahoo.com (OtisUsenet) wrote: > > > >> Python newbie question. How does one do something like this in > >> Python: > >> > >> # assign the value of j to i and then increment j by 1 > >> i = j++ > > > > Python is not designed for maximal terseness, nor for compatibility with > > C, so you need two statements to do this (well, maybe there's a way to > > do it in one, but the easiest-to-read and therefore best is with two): > > > > i = j > > j += 1 > > A particularly mysterious, unreadable and useless way to "do it in one": > > i = [ j for j in j, j+1 ][0] > > Generally, I find that abusing list comprehensions is the easiest way > to produce obfuscated Python. The specific "feature" of LCs that makes > them so suitable for obfuscation is their ability to rebind variables > in their for clauses. > > > Alex > There always has to be some smart arse who can invent a complex way of doing things! (Just jealous 'cause I have a hard enough time reading it, lete alone coming up with it) From mwh at python.net Mon Jul 8 09:21:40 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 8 Jul 2002 13:21:40 GMT Subject: `~/.pythonrc' `from __future__ import' References: Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > Suppose, for example, that I write a module in which some function makes > good use of some future feature (it could be the `yield, statement), > but I want to provide an alternate implementation of that function which > is less interesting (because it gets much complex and slower) in case the > feature is not available. Since I cannot except out of the `from __future__ > import' statement, for reasons I understand, I do not see how I take good > advantage of available future features, in a program meant to be portable > between versions. Maybe the future statement is rougher than I expected? I think you more-or-less have to have separate modules for the differently versioned functionality, eg. try: from two_point_two_using_module import func except SyntaxError: # is that what bogus future statements should # really raise? too late now, I guess from two_point_one_using_module import func ... Writing code that uses 2.2 features where possible but still runs on 2.1 is a pain, but I'm not sure how it could have been done better, really. Cheers, M. -- I have a feeling that any simple problem can be made arbitrarily difficult by imposing a suitably heavy administrative process around the development. -- Joe Armstrong, comp.lang.functional From akuchlin at ute.mems-exchange.org Wed Jul 31 09:05:21 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 31 Jul 2002 13:05:21 GMT Subject: ZPT Was: Good XML tools? References: <3D46D1B5.248A2921@q-survey.be> <3D47C373.4040805@thomas-guettler.de> Message-ID: In article <3D47C373.4040805 at thomas-guettler.de>, Thomas Guettler wrote: > I programmed with ZPT, but I switched back to generating HTML > with pure python: > > Example: (ignore the german words) > def editListsForm(self, REQUEST): ... Quixote's PTL lets you make it slightly simpler, because you don't need the res.append() calls and the ''.join() at the end; compiler wizardry takes care of that for you. You lose the ability to have docstrings, though, which is a minor tradeoff. In PTL your example would be: template editListsForm(self, REQUEST): self.standard_html_header() ''' Projekte: Bitte w?hlen Sie die zu l?schenden Projekte aus:

%s Hinzuf?gen eines neuen Projekts:
''' % (Utils.keywordInput('del_projekt', self.defaults.GRS.grs_projektList()) self.standard_html_footer() --amk From i.linkweiler at gmx.de Wed Jul 3 15:08:06 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Wed, 03 Jul 2002 21:08:06 +0200 Subject: REPEAT... UNTIL ? Message-ID: <3D234B96.7000704@gmx.de> Hi, what do you think about adding "repeat .... until" to python syntax? Often a "repeat-until" is better to use than a "while" loop. Guido 8-) ??? Ingo From nospam at nonesuch.com Wed Jul 31 18:46:08 2002 From: nospam at nonesuch.com (David Smith) Date: Wed, 31 Jul 2002 15:46:08 -0700 Subject: C++/Python version problems? References: <3D484ACD.7030503@nonesuch.com> <3D485962.4060506@nonesuch.com> <3D48619C.9030506@nonesuch.com> Message-ID: <3D4868B0.5030903@nonesuch.com> David Smith wrote: > and rebuilt. But when I tried to import it into Python, I still got the > error: > > ImportError: ./cfuncs.so: undefined symbol: __gxx_personality_v0 > OK, I made the mistake of not moving the newly-built object file into my working directory. Once I did that, it worked. Problem solved. -- David Smith drs at labs dot agilent dot com <- hopefully doesn't trigger spambots From stephen at theboulets.net Sun Jul 21 13:22:45 2002 From: stephen at theboulets.net (Stephen Boulet) Date: Sun, 21 Jul 2002 12:22:45 -0500 Subject: Base classes or global functions Message-ID: I have two classes, Class1 and Class2. Class1 contains a list of Class2 objects, but no inheritance is involved Both classes use some functions I wrote. What's the best way of making the functions available to the classes? -- Stephen, who's trying to develop good programming habits From mhammond at skippinet.com.au Sat Jul 13 21:41:09 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 14 Jul 2002 01:41:09 GMT Subject: Print a traceback from an extension? References: Message-ID: <3D30D78F.4080102@skippinet.com.au> gb at cs.unc.edu wrote: > Can I print a traceback from within a extension written in C? > > I know we're supposed to just keep returning NULL until we make it > back to the main loop. That normally works fine. > > But I'm calling Python code from a callback that is called by C > code. The Python code fails so PyEval_CallObject returns NULL. I want > to provide a helpful message at that point. > > Can this be done? If so, can someone suggest where to look for an > example? > > Thanks > gb You can find a function inside http://lxr.mozilla.org/seamonkey/source/extensions/python/xpcom/src/ErrorUtils.cpp that creates a traceback in your C/C++ code. Mark. From marklists at mceahern.com Mon Jul 8 19:56:28 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 8 Jul 2002 18:56:28 -0500 Subject: j2ee vs. python (and what our evil competitors are saying about python) In-Reply-To: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: > Summary > Python is often used as pseudocode to conduct rapid development. Its > major users are web sites that do not reuse code and often conduct > “throw away” development to meet internet development time > tables. It is a very new language and has very little support compared > to the Java development community. It is also not J2EE compliant. Python is something like 10 years old--how old is Java? Some metrics for support: activity of comp.lang.python projects on sourceforge, freshmeat, etc Also interesting in the way of comparison: comments from eric raymond http://www.linuxjournal.com/article.php?sid=3882 comments from bruce eckel http://www.mindview.net/Etc/FAQ.html#Ruby I'm not a Java expert, but you might want to point out something about Jython. > Platform Drawbacks > As a new relatively untested development platform in the licensed > software community, Python has certain deficiencies with which all > users and developers should be aware. Oh boy, bring on the FUD... > Issues and concerns > > ? No integrated GUI (Graphic user interface) support. Tk, wxPython, etc. > ? No compiler to the native code. Advantages here are that Python is probably more easily portable than Java, so I've heard. ;-) > ? No automatic garbage collection. http://www.python.org/doc/current/lib/module-gc.html > ? Does not have vast number of libraries as that of Java, > Perl, C++; etc. What matters, of course, is whether it has the libraries you need. Python is known for its batteries included approach. Does it please everybody? Of course not. > ? Since Python is an interpreted language, it requires > frequent run-time checks and thus does not provide the speed, > performance and efficiency of compiled languages like Java, Perl and > C++, which is a major issue. Python is compiled. The important point is that it's dynamic. If you need speed, building extensions in C/C++ is a snap: http://www.python.org/doc/current/api/intro.html Of course, the thing to tout here is Python's speed of *development* and easy maintenance. There's probably some study somewhere showing these are where projects typically fail. > ? Python does not provide multiple ways to perform tasks as do > most other languages. Yeah, that's right. There is only ONE way to do it in Python. Who fell off the clue train here? This sounds like someone who heard wind of TMTOWTDI, heard that Python strives for having One Right Way(tm), and forgot that Python is Turing Complete. > ? It takes a lot of time for Python to adjust to the > indentation style of the structuring code. Um, Python is compiled. So indentation makes no difference at runtime. Correct me if I'm wrong here. Besides, what shop doesn't have indentation standards? Python merely enforces those at the language level. > ? Since Python is relatively a new language, there are only a > few resources available for information on its latest developments. Huh? > ? Limited documentation- only two English language books exist > which provide tutorials or a library reference for Python. Amazon appears to think differently: http://www.amazon.com/exec/obidos/tg/browse/-/285856/ref=br_bx_c_2_6/102-735 8375-9932923 > ? The language is restricted to fewer code modules. What on earth does this mean? > ? Lacks native threading capabilities. I've heard threading in Java is superior to Python. I don't really know the details here and I haven't had to care yet. > ? Lacks basic tools such as integrated source level debuggers. I'm not up to speed on this issue. > ? No packaging methods for software distribution. distutils. > ? Lacks tools to solve typographical and type mismatch classes > of errors. It's called unit testing. > ? Python cannot write docstrings in C++. Is that true? > ? Python is difficult to read. This is a matter of opinion. The common opinion is that Python is easy to read and learn. See Eric Raymond's comments. > ? Dynamic loading is not available on all systems, requiring > that a developer use static loading. Huh? > ? Prototyping and development Python excels here. > ? Platform independent graphic user interface applications I'm not a gui person, but isn't that what Tk, wxPython, et al, deliver? > ? Internet scripting/applications Python is so easy for web scripting that everyone writes their own web app server! ;-) > ? Automated test harnesses pyunit > ? System administration applications it excels here. > ? Shell scripting/OS Scripting > ? Text processing I'm not an expert here, but it has support for regular expressions! ;-) > ? Database Interfaces I use PostgreSQL just fine from Python via pyPgSql. > ? Application Extensions ? > ? Distributed Programming checkout twisted. Cheers, // mark - From max at alcyone.com Wed Jul 10 03:25:11 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Jul 2002 00:25:11 -0700 Subject: Lunar lander example References: Message-ID: <3D2BE157.68344E80@alcyone.com> Richard Jones wrote: > Maybe pygame.org would like it too? Probably only if it used pygame, though, right? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ See the son in your bad day / Smell the flowers in the valley \__/ Chante Moore Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/ A personal guide to Aliens vs. Predator 2. From janeaustine50 at hotmail.com Sat Jul 13 06:00:43 2002 From: janeaustine50 at hotmail.com (Jane Austine) Date: 13 Jul 2002 03:00:43 -0700 Subject: sre.finditer break down: is this a bug? Message-ID: Newly added function sre.finditer and (matchedObject.)finditer break down and the system crushes on win32 when requested for next() after StopIteration. see: >> import sre >> fi=sre.finditer(r'\s','a b') >> fi.next() >> fi.next() >> fi.next() #system halts for ever. From tim at remove_if_not_spam.digitig.cix.co.uk Fri Jul 12 12:37:18 2002 From: tim at remove_if_not_spam.digitig.cix.co.uk (Tim Rowe) Date: Fri, 12 Jul 2002 16:37:18 GMT Subject: XML overuse? (was Re: Python to XML to Python conversion) References: <3D2E4FD6.CDEB601A@engcorp.com> Message-ID: <3d2f0379.12577707@usenet.plus.net> On Fri, 12 Jul 2002 08:37:59 GMT, Alex Martelli wrote: >Jonathan Hogg wrote: > ... >> I'm not sure it is possible to "overuse" XML. > >It is -- easily. My pet peeve is the idea of using XML files for >tasks that obviously need a real database, preferably a relational one. I'd agree that XML + tools in general makes a poor substitute for a proper DBMS (and so have most of the books I've read on it). But if you want to move data between different databases, expecially if they use incompatible DBMSs then XML is there as a very strong contender (/way/ ahead of comma-separated variables). And if you're worried about size, don't forget that it can be compressed for transfer (as per Star Base, IIRC) , and any decent compression algorithm will make easy work of all those repetitive tags. >Let's try to avoid pro-XML hype in an attempt to counter the >anti-XML hype that's suddenly burst on this group...:-) Should we try to avoid being anti-XML too? It's not the only data format you'll ever need, but it's pretty good at what it sets out to do. From steve.menard at polyester.com Wed Jul 24 11:49:30 2002 From: steve.menard at polyester.com (Steve Menard) Date: Wed, 24 Jul 2002 11:49:30 -0400 Subject: GUI toolkits References: Message-ID: "Stefano Vedovelli" wrote in message news:yLv%8.23058$s74.614012 at twister1.libero.it... > Hello all > > in my spare time I am writing a tool in python, with the intention of > deliver it under GPL. > > I am now starting to approach the GUI part. I have read a lot about Tkinter, > PyQT and wxWindows, but I am now actually even more confused. > > As the interface will be "quite" rich, I'd like to know the opinions of > people who already faced this decision, which tool they have chosen and > why. > One thing that hasnt been mentioned by the other posters is that pyQT does not ofer full functionality under Windows. Last time I checked the only free QT available on windows was 2.X, while on linux you can use QT 3.X. widget-wise, QT2 is a lot weaker than the other toolkits. I personally settle on wxWindows. I will not say I like it. I am used to SWING and wxWindows is painful to use. But it works as well on all supported platforms. Steve From emile at fcfw.fenx.com Mon Jul 8 10:12:51 2002 From: emile at fcfw.fenx.com (Emile van Sebille) Date: 8 Jul 2002 09:12:51 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jul 8) Message-ID: <117722385B7B2D17.41E48E31D56BB3CF.C0B5EA2AE27ADD9F@lp.airnews.net> QOTW: "A common response was 'But the problem's hard! It can't be that easy!' (presumably because Sun have told you you need J2EE for this problem). Tim[Couper]'s basic strategy seemed to be 'give me a morning and see what I can do', which I can imagine being effective. Michael Hudson, on Tim Couper's EuroPython Conference talk on "Selling Python to a Fortune 500 Company". "Helping others is the best repayment one could give." Clark C. Evans Duncan Grisby is the first to announce pictures from the EuroPython meeting last week... http://groups.google.com/groups?selm=9ZUT8.21128$l6.4303892 at newsfep2-win.server.ntli.net ...and Michael Hudson puts the notes he took during the conference online: http://groups.google.com/groups?selm=lk7kkdylwd.fsf at pc150.maths.bris.ac.uk Eric Brunel reports a strange 'access denied' error running on Win2k, which Thomas Heller resolves with an even stranger looking fix: http://groups.google.com/groups?threadm=afp6fr$ksf$1 at wanadoo.fr Stuart Langridge has written a utility that works with Apache and provides the Active Server Pages object model to Python for those of you who think in terms of Request.Querystring and Response.Cookies. http://groups.google.com/groups?selm=a32124ee.0207010631.e68b17e at posting.google.com Which Pythoneer merits election as Active of the year? Selection of just one of Robin Dunn Paul F. Dubois Jim Fulton Mark Hammond Alex Martelli by the 17 July 2002 deadlines poses a difficult problem. http://www.ActiveState.com/ActiveAwards2002 If you're using the new email package, Oleg Broytmann asks that you download the latest Python from CVS or the daily snapshop and test that the patches don't break your programs. http://groups.google.com/groups?selm=mailman.1025531586.7419.python-list at python.org Ever need to get to the XP clipboard from tkinter? Here's a thread that shows how. http://groups.google.com/groups?threadm=3D1F1A81.95602DE0 at tds.net Christian Tismer announces availability of Stackless 2.2.1 alpha on PPC. http://groups.google.com/groups?selm=mailman.1025532187.14035.python-list at python.org Fred L Drake releases an update of the development version of the documentation, including the new textwrap module for the first time. http://www.python.org/dev/doc/devel/ Some of the details of thread safety are covered in this thread http://groups.google.com/groups?threadm=slrnai5ssg.a67.jgoerzen at christoph.complete.org Frank Carlos posts links to tutorial covering Python and XML development using the open source 4Suite toolkit. http://groups.google.com/groups?selm=64ebecf3.0207040545.a5dbbad at posting.google.com Anthony Baxter announces the first release of python director a pure python (async I/O based) TCP loadbalancer/redirector http://groups.google.com/groups?selm=mailman.1025727423.26218.clpa-moderators at python.org Trent Mick introduces go, a simple command line application to help you change directories in your shell session quickly... http://groups.google.com/groups?selm=mailman.1025858889.3154.python-list at python.org ... as well as px and p4lib, which provide python based client and administrative access to Perforce repositories... http://groups.google.com/groups?selm=mailman.1025859248.11749.python-list at python.org ... and a smarter which command replacement, understanding the PATHEXT environment variable and providing an all option. http://groups.google.com/groups?selm=mailman.1025859068.6203.python-list at python.org Paul Rubin found Simon Foster's SNTP client on the ASPN Cookbook site and adapted it to set the hardware clock under Linux: http://groups.google.com/groups?selm=7xfzyx5i7s.fsf at ruckus.brouhaha.com Leon Wang feels his way through to see and use Chinese within idle for development. http://groups.google.com/groups?threadm=d5d388d4.0207060619.f8bbc9e at posting.google.com Svein Brekke is building a slideshow and asks how to make tk use the entire screen. http://groups.google.com/groups?threadm=21298535.0207040554.6caeed01 at posting.google.com Gerhard H?ring posts a script that gets all HTML tags and removes requested attributes. http://groups.google.com/groups?selm=mailman.1025633824.13815.python-list at python.org Holden Caulfield asks about metaclass & __slots__... http://groups.google.com/groups?threadm=c2595393.0207031317.7d9bb013 at posting.google.com ...Alex Martelli posts a nice metaclass example... http://groups.google.com/groups?selm=mailman.1026011529.32320.python-list at python.org ...as does Greg Ewing. http://groups.google.com/groups?selm=3D22881F.10204 at something.invalid Oren Tirosh posts information and links to a library that implements pipelines (referred to as flows) using Python iterators and generators. http://groups.google.com/groups?selm=mailman.1025705465.27835.python-list at python.org Achim Domma is looking for someone to provide PythonMagick binaries for non-windows platforms. http://groups.google.com/groups?selm=afviu0$ae9$02$1 at news.t-online.com Thomas Jensen asks for help in preparing some really compelling arguments to convince management to use Python for a job. http://groups.google.com/groups?threadm=3D27152C.8020108 at obscure.dk.X Konrad Hinson announces release 2.2 of The Molecular Modelling Toolkit (MMTK), an Open Source program library for molecular simulation applications, written in Python with C modules for time-critical parts. http://groups.google.com/groups?selm=mailman.1025875203.640.clpa-moderators at python.org Vinay Sajip announces release v0.4.6 of the Logging Module, which offers the ability for any Python program to log events which occur during program execution. http://groups.google.com/groups?selm=2e37dc1.0207071638.11381436 at posting.google.com ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From opengeometry at NOSPAM.yahoo.ca Tue Jul 9 17:23:38 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 9 Jul 2002 21:23:38 GMT Subject: HTML to PDF converter? References: Message-ID: Lance Ellinghaus wrote: > Does anyone know of a HTML to PDF converter that is written in Python? On Linux, I would do netscape -remote "openURL(http://...)" -remote "saveAS(xxx.ps, PostScript)" ps2pdf xxx.ps xxx.pdf where the commands can be typed manually, from script, or called from Python via 'os.system()'. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From shagshag13 at yahoo.fr Wed Jul 24 11:10:09 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 24 Jul 2002 17:10:09 +0200 Subject: xml processing : too slow... Message-ID: hello, i need to process *each line* of many huge files (> 2 million lines) with xml processing, by now i do it with parseString from xml.dom.minidom and it's work. i do xml validation, extract attributes and tags. that's really slow, how do you think i can speed it up ? i'm thinking of writing a xml mini wrapper using things like string.find or even regular expressions, do you this that's a good idea ? thanks in advance, s13. From heikowu at ceosg.de Fri Jul 19 14:49:19 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 19 Jul 2002 20:49:19 +0200 Subject: Funny behaviour of MySQLdb In-Reply-To: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> References: <1027104030.17779.92.camel@d168.stw.stud.uni-saarland.de> Message-ID: <1027104559.17779.96.camel@d168.stw.stud.uni-saarland.de> Hi List! I just tried the single-threaded way, and that works... Hmm... Nothing apparently different, except that I took out the base class SocketServer.ThreadingMixIn from the definition of the server class... Strange... Yours, Heiko W. From jerf at jerf.org Tue Jul 23 01:19:31 2002 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 23 Jul 2002 05:19:31 GMT Subject: Metaclasses & docstrings in 2.2 References: <%x4%8.613290$352.131254@sccrnsc02> Message-ID: On Mon, 22 Jul 2002 23:00:59 -0500, I wrote: > class M1: > "M1's docstring." > def __init__(cls, name, bases, dict): > pass Ah. Moron source located. class M1(type): "M1's docstring." def __init__(cls, name, bases, dict): suprt(M1, cls).__init__(name, bases, dict) will work as I expected and do the right thing. It's even cooler when it works right. From duduca007 at yahoo.com Mon Jul 8 18:59:40 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Mon, 8 Jul 2002 15:59:40 -0700 (PDT) Subject: python & web services In-Reply-To: <6pNV8.24555$2w.1181063@news20.bellglobal.com> Message-ID: <20020708225940.66782.qmail@web11401.mail.yahoo.com> --- John wrote: > What is currently available for the development of > web services in python? > Does Zope provide a complete solution? (I am new to > both and plan to learn > them together) > > Thanks. > > J. Another solution: PSP - Python Server Pages http://webware.sourceforge.net/ []'s Cadu Moreira KaduSoft President ----------------------------- [..."A guerra eh o ultimo recursso dos maus governantes" -- Sven Hassel...] __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com From janeaustine50 at hotmail.com Thu Jul 25 12:14:09 2002 From: janeaustine50 at hotmail.com (Jane Austine) Date: 25 Jul 2002 09:14:09 -0700 Subject: euid/egid eaten up by os.popen Message-ID: We use python cgi for a part of our web programs. For some permission concerns, we have an execv file that simply runs our main python code via "execv" C function. The execv file is compiled and set as "chmod 6xxx". When we print out geteuid from the python code, it prints out as we expect. However, when we call a popen, the pipe is run without the effective user/group id. That is a problem since web accesses are done via apache(or nobody) account and we don't want to reveal everything to the world while using some external programs through pipes. Any helps? From phr-n2002b at NOSPAMnightsong.com Thu Jul 18 15:27:36 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 18 Jul 2002 12:27:36 -0700 Subject: Python robot web client? References: <7x65zdtrv9.fsf_-_@ruckus.brouhaha.com> Message-ID: <7x1ya0kf9z.fsf@ruckus.brouhaha.com> Ian Bicking writes: > WebUnit has HTTPSession, which does the persistent cookies, though no > parsing. Where do I find this? Thanks. From fredrik at pythonware.com Mon Jul 1 12:29:15 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Jul 2002 16:29:15 GMT Subject: New style classes as exceptions (Was: exception handing) References: Message-ID: Denis S. Otkidach wrote: > This doesn't matter: > > >>> class o(Exception, object): pass > ... how come you aren't subclassing from Exception: >>> class o(Exception): ... pass ... >>> try: ... raise o("spam") ... except o: ... print "OK" ... OK From marvelan at hotmail.com Tue Jul 30 06:42:52 2002 From: marvelan at hotmail.com (M) Date: 30 Jul 2002 03:42:52 -0700 Subject: Good XML tools? Message-ID: Hi all, Can you recommend any good XML packages for Python? I looked at the PyXML but it seems to be lacking proper documentation (=unusable). Are you aware of any package that provides DOM/XPath for Python? Good documentation is a must, only hackers doing their favorite OSS project in their spare time can spend time reading source code instead of proper documentation... Thanx. /M From pecora at anvil.nrl.navy.mil Sun Jul 21 09:57:32 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Sun, 21 Jul 2002 09:57:32 -0400 Subject: A better self References: Message-ID: <210720020957323127%pecora@anvil.nrl.navy.mil> In article , Fredrik Lundh wrote: > > 5) Use the x,y,z = self.x, self.y, self.z idiom > > unfortunately, that actually creates a 3-item tuple, > only to tear it apart again. this is better: > > x = self.x; y = self.y; z = self.z If that's faster, that's what I'd use. Thanks. -- Lou Pecora - My views are my own. From cliechti at gmx.net Mon Jul 15 13:33:04 2002 From: cliechti at gmx.net (Chris Liechti) Date: 15 Jul 2002 19:33:04 +0200 Subject: Radians vs. Degrees References: <3D33016C.8030804@cox.net> Message-ID: Jef wrote in news:3D33016C.8030804 at cox.net: > I'm new to this NG so please bear with me :-) I'm writing an addon > for the Quake2 editor named QuArK and could use some advice from the > math/coding gurus out there. welcome > My problem is that I'm trying to create a torus (donut) and the C > code I'm looking at uses DTOR to convert degrees to radians and I see no > mention of it (DTOR) in Python. My question is whether I need this in > Python or does Python automatically convert to radians during > calculations? no. all math/trigonometric functions expect radians. some conversion functions are easily written: >>> import math >>> def toDEG(rad): ... return 180.0*rad/math.pi ... >>> def toRAD(deg): ... return math.pi*deg/180.0 ... >>> math.sin(toRAD(90)) 1.0 >Also, do the FOR loops work the same as in C++ (e.g. > FOR(x=0, x<360, x++))? If not, any suggestions on how to do this? no. "for" works a little bit differnt in python: it iterates over a list and takes one element after an other. if you want to count, you can use the range() function to create a list of numbers. for c in range(360): ... or maybe you want to convert directly to radians: for c in map(toRAD, range(360)): ... (map applies the function (1st arg) to each element in a list (2nd arg)) chris -- Chris From brueckd at tbye.com Thu Jul 4 18:12:57 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Thu, 4 Jul 2002 15:12:57 -0700 (PDT) Subject: sending a file through sockets In-Reply-To: <3d2458c1$0$228$4d4ebb8e@news.nl.uu.net> Message-ID: On Thu, 4 Jul 2002, Guyon Mor?e wrote: > so the trick is to convert a file to a string representation right? > i still have to try it out, but maybe you can confirm my way of thinking > here :) Um... you *could* do that, but it wouldn't actually help at all. The contents of the file already are in a string representation because Python strings can contain anything, including binary characters. The easiest way to send a file is to simply read the data from the file and send it out the socket, but to send the length of the file first so the receiving end knows if and when it got the whole thing. If you need too much more functionality than this it might be easier to just use one of the standard file transfer protocols, e.g. FTP. Anyway, here's some sample code, but if you're not already familiar with sockets then you should spend a little time experimenting with them. The sending side listens for incoming connections and sends out the file. The receiving side connects to the "server" and writes the file to disk. Common code: import struct PORT = 5555 FILENAME = 'foo.bin' HDR = '!I' HDR_SZ = struct.calcsize(HDR) Sending side: import os from socket import * s = socket(AF_INET,SOCK_STREAM) s.bind(('',PORT)) s.listen(1) while 1: q,v = s.accept() q.sendall(struct.pack(HDR, os.path.getsize(FILENAME))) f = open(FILENAME,'rb') while 1: data = f.read(4096) if not data: break q.sendall(data) q.close() Receiving side: from socket import * f = open(FILENAME, 'wb') s = socket(AF_INET, SOCK_STREAM) s.connect(('', PORT)) size = s.recv(HDR_SZ) size = struct.unpack(HDR, size) while size > 0: data = s.recv(4096) if not data: break size -= len(data) f.write(data) s.close() Note that if you're not using Python 2.2 or later there isn't a sendall method in socket objects so the sending side should check the return value from send() to see how many bytes were actually written out and resend any that didn't make it. -Dave From pinard at iro.umontreal.ca Sat Jul 13 08:13:07 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 13 Jul 2002 08:13:07 -0400 Subject: Moving list entries from one list to another In-Reply-To: <3d30085b_9@news.newsgroups.com> References: <3d30085b_9@news.newsgroups.com> Message-ID: [JB] > I have two lists and . The entries of these lists have the > format (id,rest), where is a natural number. The list are sorted, > the key is . I should like to write a funtion move "def move(f):". > The argument is a predicate (f: {set of entries of list1} --> {true, > false}). Now all elements of list1, for which returns true, should be > moved to list2. It is very important, that remains sorted, that > is, the entries from should be inserted to the right positions > in . When is defined by n := max(len(list1),len(list2)), > then should work in O(n) time. Any hints of how to do this > (as fast as possible)? Being O(n) and being as fast as possible may be contradictory goals. If you use `list1.remove()' and `list2.insert()', you may get up to O(n**2). But if you evaluate first how many moves will be required, which can be decided in O(n), and find out that this number is "small", you may beat with `list1.remove()' and `list2.insert()' an algorithm designed to be O(n). Now, being O(n) is all of a requirement. It means in particular that you cannot use neither `list2.insert()' that might climb up to O(n**2), nor `list2.sort()' which is O(n*log(n)). The only choice left seems to build a `prelist2' holding only the elements to move, and then merge `prelist2' with `list2' in a O(n) pass. You also have no choice but separately copy `list1' without the moved elements, and this can be done O(n) too. Of course, I presume that `f' is efficient itself, probably based on a dictionary of some sort say. dictionary lookup is slightly more than O(1), but I hope it is O(1) enough for your purpose. Else, you have to implement another way. If `f' is more than O(1), your problem cannot be solved. If `prelist2.append()' is not O(1) enough for you either, you have to pre-allocate it at once to full length, and using `f', the length may be predicted in O(n) time, and then fill its slots using indexing. All in all, I think that you will pay a high multiplicator price for being strictly O(n), and you could achieve something much faster _in practice_ by relaxing this constraint. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From b.maryniuk at forbis.lt Thu Jul 11 05:44:53 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 11 Jul 2002 11:44:53 +0200 Subject: PyGPG In-Reply-To: References: Message-ID: <200207111144.53954.b.maryniuk@forbis.lt> On Thursday 11 July 2002 11:26, Ivica wrote: > I'm looking for PyGPG wrapper around gpgme ... the URL i found does > not work any more. Can any one tell me where to find them. > Tnx! There is nice one at http://py-gnupg.sourceforge.net -- Sincerely yours, Bogdan M. Maryniuck Feel free to contact me (flames about my english and the useless of this driver will be redirected to /dev/null, oh no, it's full...). (Michael Beck, describing the PC-speaker sound device) From prema at prema.co.nz Thu Jul 18 15:10:38 2002 From: prema at prema.co.nz (Prema) Date: 18 Jul 2002 12:10:38 -0700 Subject: Pmw Inconsistencies -- Any ideas ?? References: Message-ID: Hi Gerhard ! Yes it is ! This is version 2.2 . I think I understand -- is it that the import is clashing with the file name? -- I must say that I never considered that! I take it then that a module name is therefore a kind of reserved word? Thank so much for your comment Kind regards Mike Gerhard H?ring wrote in message news:... > Mike MacDonald wrote in comp.lang.python: > > I'm wanting to use Pmw for a small project. > > I notice that sometimes I can't initialise Pmw. [...] > > ## > > ##Error message: > > ## Traceback (most recent call last): > > ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 1, in ? > > ## import Pmw > > ## File "C:\Documents and Settings\t914149\Desktop\Pmw.py", line 11, in ? > > ## root=Pmw.initialise() > > You didn't call your script "Pmw" too, did you? Which Python version > is this? > > Gerhard From christophe.delord at free.fr Fri Jul 19 10:56:14 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Fri, 19 Jul 2002 16:56:14 +0200 Subject: Recursion References: <20020719083105.5c01b6a4.christophe.delord@free.fr> <71a1c515.0207190408.ee0e943@posting.google.com> Message-ID: <20020719165614.77b721d9.christophe.delord@free.fr> On 19 Jul 2002 05:08:58 -0700 karaatanasov at hotmail.com (Kiril Karaatanasov) wrote: > Christophe Delord wrote in message news:<20020719083105.5c01b6a4.christophe.delord at free.fr>... > > Try this: > > > > def bits(x): > > return (x!=1 and bits(x>>1) or "") + "01"[x&1] > > > > The idea is to return the string instead of printing it. > > Smart but as anything French WRONG !!!! > try calling > > bits(0) Ok, but the problem was in the specification. That means that the "bug" is a requested feature. So anything french is not allways wrong ;-) What about this one (with your patch of course): bits = lambda x,f=lambda y,g:(y>1 and g(y>>1,g) or "")+"01"[y&1]:f(x,f) BTW, I know it's not good either because not very readable... > > Now may be we want to write it the good way vs. the "smart" way :o) > > def bits(x): > return (x>1 and bits(x>>1) or "") + "01"[x&1] -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From andrewm at object-craft.com.au Tue Jul 30 20:47:34 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 31 Jul 2002 10:47:34 +1000 Subject: How to find out if february has 29 or 28 days ? In-Reply-To: Your message of "Tue, 30 Jul 2002 18:48:55 +0200." Message-ID: <20020731004734.4735A3900D@coffee.object-craft.com.au> >A year is a leap year if it can be divided by 4, except if it can be >divided by 100, where it's a leap year only if it can be divided by 400. It >sounds awful to compute, but in Python, it's actually quite simple: > >>>> isLeap = lambda x: x % 4 == 0 and (x % 100 != 0 or x % 400 == 0) Or, if you have a pathological aversion to lambda: >>> def isLeap(x): ... return x % 4 == 0 and (x % 100 != 0 or x % 400 == 0) ... >>> isLeap(1980) 1 >>> isLeap(1991) 0 >>> isLeap(2000) 1 >>> isLeap(1900) 0 8-) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From tjreedy at udel.edu Sat Jul 20 10:55:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Jul 2002 14:55:21 GMT Subject: Interfacing to 1-Wire LAN, especially Dallas temperature sensors? References: Message-ID: "Wolfgang Lipp" wrote in message news:Xns9250DFB43AB73lippatpostde at 213.73.102.4... > i am currently concerned with the problem of how to read temperatures from > th ds182* components. unfortunately, i seem to have an older passive > adapter that is neither supported by newer versions of digitemp > (http://www.brianlane.com/digitemp.php) nor by pyOneWire. are there plans > to extend pyOneWire so passive adapters (DS9097, DS9097E) are supported? PyOneWire is new to me, Google, and probably most readers here. Find the author/distributor. TJR From maxm at mxm.dk Mon Jul 1 08:20:39 2002 From: maxm at mxm.dk (Max M) Date: Mon, 01 Jul 2002 14:20:39 +0200 Subject: I'd give up Perl tomorrow if only... References: Message-ID: <3D204917.8070609@mxm.dk> A.M. Kuchling wrote: > In article , > Richard Jones wrote: > >>I recently stepped up to the plate, but got zero response from catalog-sig. >>I'll be contacting authors of the various half-finished systems directly if I >>get no response soon. > > > Don't expect a response from the SIG readership. Jason Petrone posted > a BSD ports-like system: no comments. Ciphon was announced: no > reaction. Just go ahead and implement something, and tell people to > live with it; that seems the only way anything will ever get done. But isn't this what a problem like this seems to beg for? A dictator decission. There would be no point in having multiple CPYN solutions. Competing libraries would indeed be detrimental to the whole idea. I would like a library like this, but have no ideas about how such a solution should be implemented, and so have no ground on which to comment on a system. I would have suggested creating a Zope Product that implements the package system as all the elements needed is allready there (searching, security, web interface etc.), and it would be easy to create mirrors in a standard fashion. regards Max M From fredrik at pythonware.com Sat Jul 13 08:20:59 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Jul 2002 12:20:59 GMT Subject: login with python (2) References: Message-ID: Ralf Claus wrote: > Hello, the login website of my router needs the following > html code to login: > >
>

Total number of hits: %d
Total number of pages: %d
""" def produce_report(): print report_top % (total_hits, len(hits_by_page)) pages = [] for (url, hits) in hits_by_page.items(): pages.append((hits, url)) pages.sort() pages.reverse() print "" print "
Page Hits" for (hits, url) in pages: print "
%s %d" % (url, hits) print "
" # --- Main program import sys if len(sys.argv) != 2: # script name is sys.argv[0] print "Usage: %s " % sys.argv[0] sys.exit(1) read_logfile(sys.argv[1]) produce_report() # ---------------------------- # end code In the function, process_request(), why isn't the variable, hits_by_page, declared as a global var? I tried putting in that code (" global hits_by_page") and there is no effect. The script still works. My question is Why??? Please excuse any ignorance on my part; Python is not my native programming language. ;-) -- Jimmy Cerra "my mind is slipping away ... day by glorious day" - RG From jonathan at onegoodidea.com Tue Jul 30 19:00:12 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Wed, 31 Jul 2002 00:00:12 +0100 Subject: global interpreter lock not working as it should References: Message-ID: On 30/7/2002 22:49, in article mailman.1028065844.28617.python-list at python.org, "anton wilson" wrote: > It would seem that python developers like to assume other people are calling > them stupid and lazy and take hints as offensive or demanding action. I've > never seen so much hostility to a bug in my life. A "hint"? You have to be joking. The very subject line of this thread indicates that you believe you understand better how the GIL "should" work. Everyone else has said this already, but let me make it very plain: THIS IS NOT A BUG As explained, the context switching of threads is decided by the native thread implementation. Your threading system is choosing not to switch every time the GIL is released. This is a very sensible thing to do as no matter how lightweight threads are, switching them requires non-zero time. If nothing is waiting on I/O then the thread implementation might as well let the first CPU-bound thread run riot. If you have two CPU-bound threads that you want to run, and they don't communicate with each other, then running them with large timeslices *guarantees the maximum possible throughput*. The larger the timeslice, the more efficient the system is. The ideal situation is to run one fully to completion and then run the other fully to completion as this involves precisely one context switch which is O(1). If it switched every 10 instructions then the context switch cost would be O(n). Unless you have a multiple CPU machine you are wasting your time. If you do have a multiple CPU machine, then you will have to extract the CPU-intensive work out to a C extension which can operate with the GIL released. [And make sure you're using kernel-level threads as user-level threads can't utilise multiple CPUs anyway.] Jonathan From sholden at holdenweb.com Sat Jul 27 12:41:24 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 27 Jul 2002 12:41:24 -0400 Subject: how to count lines in a file ? References: <2259b0e2.0207250631.1e093e64@posting.google.com><7aU%8.139472$vm5.4528856@news2.tin.it> <1027761473.8774.242.camel@vaio2> Message-ID: <034401c2358c$93aac0d0$6300000a@holdenweb.com> [Andreas explains why garbage collection in the presence of __del__() methods is a bad idea ...] > Basically, because the system state during collection is in a flux, the > possible failure modes for finalization functions multiple quite fast. > > Now there uses for finalization with GC, but they usually do not apply > to python (because python do not contain things like unprotected > references, etc., and the whole interfacing with non-gc libraries is > done in C). > > completely sure I understand what you are saying. As the Reverend Sydney > > Smith observed upon seeing two women shouting at each other from opposite > > windows: "I fear they will never agree, for they are arguing from different > > premises". Thanks. I thought there had to be something I was missing. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From rs at onsitetech.com Tue Jul 9 17:19:58 2002 From: rs at onsitetech.com (Robb Shecter) Date: 09 Jul 2002 21:19:58 GMT Subject: Why self? References: Message-ID: <3D2B5331.7090104@onsitetech.com> And, it according to consensus in this thread, this: >> >> self.y= self.x**2 * self.t/self.z + self.a * FFT(self.tseries) >> should really be written like this: self.__y = self.__x**2 * self.__t/self.__z + self.__a * FFT(self.__tseries) to be safe from accidental overwriting by subclasses. Now there's a beauty! :-) From cliechti at gmx.net Tue Jul 23 09:30:13 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 15:30:13 +0200 Subject: No subject References: <3d3d53f4.356458609@news.skynet.be> Message-ID: henk_derudder at hotmail.com wrote in news:3d3d53f4.356458609 at news.skynet.be: > Hi, hello. please set a subject in your messages. > What datatypes can one use as key in a dictionary? anything immutable. thats numbers, strings, tumples > Can I use for example two longs as key (kind of a double key)? if you put them in a tuple, sure: >>> d = {} >>> d[(1L,2L)] = 1 >>> print d {(1L, 2L): 1} >>> d[(1,2)] 1 and as you see, it doesn't even matter if the numbers are longs or ints. if they have the same nummeric value there the same in a dict too. chris -- Chris From jonathan at onegoodidea.com Tue Jul 30 08:34:57 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 30 Jul 2002 13:34:57 +0100 Subject: re question (perhaps a stupid misunderstanding of regex-logic) References: Message-ID: On 30/7/2002 13:53, in article mailman.1028026365.30666.python-list at python.org, "Stefan Antoni" wrote: > thats why i ask the following question: > > i made the following regex: > m = re.compile("[^M]*") > > i think, it would be read as: "find everything except the occurences of > the char 'M' " . Think of it instead as "0 or more sequential occurrences of a character that isn't an 'M'" > i wrote the following code: > > all = string.letters + string.digits + string.hexdigits + \ > string.whitespace > > M = re.compile("[^M]*") > M.findall(all) > ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL', '', \ > 'NOPQRSTUVWXYZ01234567890123456789abcdefABCDEF\t\n\x0b\x0c\r ', ''] > > this gives me a list with an empty item at [1] of the list. > the documentation says: "findall: Find all occurrences of a > pattern in a string." The empty string, '', represents a perfectly valid match for your regex as it is precisely 0 sequential occurances of a character that isn't an 'M'. Try doing your experiment again with the regex "[^M]+" instead, which means "1 or more sequential...". Jonathan From tjreedy at udel.edu Thu Jul 4 10:16:39 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Jul 2002 14:16:39 GMT Subject: Quaternion Arithmetic Module References: Message-ID: "Dave Feustel" wrote in message news:ag1iqj$oi5$1 at slb3.atl.mindspring.net... > Is there a python module for doing quaternion arithmetic? google Python quaternion From shagshag13 at yahoo.fr Fri Jul 5 03:24:42 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 5 Jul 2002 09:24:42 +0200 Subject: Memory ? Message-ID: Hello, i'm still looking for a way to check which are the best ways to save memory because i work on many GB with float, etc. so is there a way to check how many bytes needs an object, a tuple, a list, a dict of objects and so on ? (something like itemsize for array - in fact array should be great if they weren't boxed) i also have troubles like : - which way is the best to handle a sequential dictionary : having 2 dicts, one for the order and other for my data ? but i think, it's better to use a list to handle order an a dict for data (like in seqdict) - how many subclassing can i use ? (is this time or memory consuming in any ways ?) and so on... i didn't find such answers in PEP, etc. or maybe i missed them, thanks in advance, s13. From chris_mk at hotmail.com Mon Jul 22 18:58:21 2002 From: chris_mk at hotmail.com (Christopher) Date: 22 Jul 2002 15:58:21 -0700 Subject: XML Style-sheet question Message-ID: Hey everybody, I am working on implementing a Python program to interface with FileMaker 6 and I had a question. The ability to use XML Stylesheets is very nice with the new FileMaker version, but I've run into a bit of a problem (I am in the middle of learning XML and all that entails but I am oblivious to some of the details). Here's the issue: I know that I can create an export protocol and run it through XML stylesheets to put things into columns with headings (in Excel; in other words, the XML formats the data and Excel can read that formatting). What I want to know is if there is a way to design a stylesheet template so that even custom exports are formatted correctly. Let me give a brief example (I know everybody is quite busy). Let's say you have a product database and each product has a unique product number. Each product also has a color, a price, a shipping price, a profit margin, etc. Now, I made an export (and stylesheet) that takes each of the products, makes a column with the product number as the heading and lists the color, price, and profit. Now, other people will have access to the database and they, too, want to have the exports formatted with the product number on top of each column. Now, there are about 100 characteristics for each product, so making a separate stylesheet for each possibility is pretty much impossible (100! (that is 100 * 99 * 98...) + possibilities, right). Is there a way to automate it somehow? If there isn't, can you tell me that too, so I'll just break the bad news to my coworkers. Thanks. Chris PS- As a side-note, I am thinking of trying a python script similiar to the Article Handler from Python & XML (something like if name == "webArticle": subcat = attrs.get("subcategory", "") if subcat.find("tech") > -1: self.inArticle = 1 self.isMatch = 1 elif self.inArticle: if name == "header": self.title = attrs.get("title", "") if name == "body": self.inBody = 1 but this is quite advanced for me at the moment, so I am trying to do the simplest, quickest, and most user-friendly manner possible. Thanks again. From gerhard.haering at gmx.de Tue Jul 2 14:03:32 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 2 Jul 2002 20:03:32 +0200 Subject: Is there any simple way to get all HTML tags and remove attribute In-Reply-To: <63170f57.0207020902.25fac937@posting.google.com> References: <63170f57.0207020902.25fac937@posting.google.com> Message-ID: <20020702180332.GA870@lilith.my-fqdn.de> * sanjay [2002-07-02 10:02 -0700]: > Hi, > > I am trying to get all HTML tag and remove color attribute using > SGMLparser. Can anyone provide simple code .. This is what I use: http://cgi.algonet.se/htbin/cgiwrap/ug/show.py?script=sgmlecho.py Basically just use the attrs_to_remove attribute of SgmlEcho. Copied for archival, should this URL ever get offline: from sgmllib import SGMLParser import string # Parse through an SGML file and copy it to self.output # Can be made to remove certain attributes from all tags by # setting 'attrs_to_remove' to a list of attribute names. # Suitable base class for all kinds of HTML file tweakers. class SgmlEcho(SGMLParser): # Initialize default values def __init__(self): SGMLParser.__init__(self) self.echo = 1 self.attrs_to_remove = [] self.output_list = [] # Return the collected output camouflaged as a member def __getattr__(self, name): if name == 'output': return string.join(self.output_list, '') else: raise AttributeError, name # Reset output def reset_output(self): self.output_list = [] # Save all output, unless turned off def write(self, data): if self.echo: self.output_list.append(data) # Trap all start tags, check attributes def unknown_starttag(self, tag, attrs): self.write('<'+string.upper(tag)) for attr in attrs: name, value = attr if name not in self.attrs_to_remove: self.write(' '+string.upper(name)+'="'+value+'"') self.write('>') # Trap all end tags def unknown_endtag(self, tag): self.write('</'+string.upper(tag)+'>') # Take care of character references def handle_charref(self, name): self.handle_data('&#'+name) # Take care of entity references def handle_entityref(self, name): self.handle_data('&'+name+';') # Take care of data def handle_data(self, data): self.write(data) # Take care of comments def handle_comment(self, data): self.write('<!--'+data+'-->') if __name__ == '__main__': import sys p = SgmlEcho() p.attrs_to_remove = ["add_date", "last_visit", "last_modified"] fp = open(sys.argv[1]) p.feed(fp.read()) fp.close() sys.stdout.write(p.output) p.close() Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mfranklin1 at gatwick.westerngeco.slb.com Wed Jul 31 11:11:52 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 31 Jul 2002 15:11:52 +0000 Subject: Window does not resize it's components In-Reply-To: References: Message-ID: <200207311412.g6VECE018308@helios.gatwick.geco-prakla.slb.com> On Wednesday 31 Jul 2002 12:54 pm, Raimo Tuisku wrote: > I have a couple of widgets in a window(Text and Entry widgets). But their > size remain even if the user resizes the window which is not what I > want. How can I make them fit precisely in the window borders even if the > window is resized? Do I have to fiddle with the signals or what? Is this Tk(inter) ? If so then when you .pack() these widgets add a few extra arguments >From `pydoc Tkinter.Frame.pack`:- Python Library Documentation: method pack_configure in Tkinter.Frame pack = pack_configure(self, cnf={}, **kw) unbound Tkinter.Frame method Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction before=widget - pack it before you will pack widget expand=1 or 0 - expand widget if parent size grows fill=NONE or X or Y or BOTH - fill widget if widget grows in=master - use master to contain this widget ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. Regards Martin From mhammond at skippinet.com.au Sun Jul 21 18:38:13 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 21 Jul 2002 22:38:13 GMT Subject: Setting the right border in PythonWin IDE References: <817kjqi8wo.fsf@darwin.lan.kassube.de> <1e2446ac.0207210838.75013e54@posting.google.com> Message-ID: <3D3B37E1.6040501@skippinet.com.au> TMinSF wrote: > Nils Kassube wrote in message news:<817kjqi8wo.fsf at darwin.lan.kassube.de>... > >>Guten Abend. >> >>How do I set the right text border/margin in the PythonWin IDE shell >>from ActivePython 2.2.1? >> >>If I try e.g. dir(sys) the resulting list is annoyingly displayed on a >>single line. I've tried playing with the settings like e.g. right edge >>mode in View/Options... but nothing seems to wrap text on a new line >>after a certain number of characters. >> >>Danke im voraus, >>Nils > > > Same problem, but even worse. When I try to scroll right with the > hor. scrollbar thumb, that doesn't work correctly either (W2K, Python > 2.2.1, PythonWin 2.2.0.146). When the scroller thumb is all the way > to the right, I should be at the end of the single line but I'm not. > To see more of the line, I have to hold down the hor. scrollbar right > arrow button. Aside from this _really_ annoying feature, I love > PythonWin. If this is just a config issue, I hope someone out there > will help us out. I've looked everywhere I can think of and can't > find the answer. The 147 and 148 win32all builds word-wrap the interactive window. Mark. From aleax at aleax.it Wed Jul 10 10:17:25 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 10 Jul 2002 14:17:25 GMT Subject: adding methods on the fly References: <878dc260.0207090321.14e06bbe@posting.google.com> <3VAW8.59624$vm5.2174084@news2.tin.it> <878dc260.0207100226.750b8513@posting.google.com> Message-ID: Renzo Tomaselli wrote: ... >> You can marshal such objects to bytestrings, too, for storing as BLOBs >> or whatever. > > Yuup! this was the big missing point. Indeed I need to marshal all > functions (user-defined methods, actually) down to my OODBMS (and the Slightly imprecise of me -- you can't marshal.dumps the function object f itself; rather you marshal its f.func_code (then rebuild a function object from the unmarshaled code with new.function): >>> def f(): print 'ciao!' ... >>> maco = marshal.dumps(f.func_code) >>> # save and later reload bytestring maco at will >>> newf = new.function(marshal.loads(maco), {}) >>> newf() ciao! >>> Globals and argument defaults too if you need them, of course. The function becomes a method later (via new.instancemethod or otherwise). >> > I still wonder why it's so hard (from a C/C++ perspective) to walk >> > from a "def foo(self): pass" string to a callable object to be added >> > to a class. >> But it's not. exec that with a locals dictionary, and in the dictionary >> at key 'foo' you find exactly a Python callable object (a function >> object, to be precise). What IS "so hard" about this? def is an >> executable statement, used to create function objects, so, if you >> start with a def statement and want a function object, you, of course, >> execute the statement. What COULD possibly be easier or mote natural? > > True but not obvious. I spent days in searching through this list on > Google (and on C++ SIG as well). There are many messages about > extending/embedding but none came to the above conclusions when the > target is focused on methods. Right. The "focus on methods" may be the misleading part, given that the Python-coded function becomes a method object separately from all the rest of the operation -- just a hypothesis on why things may not have been said in this particular context earlier! > Thank you very much Alex, let me know if you plan to visit this area > in the near future. I'm vacationing in Trentino-Alto Adige around Ferragosto, but near the Lago di Carezza, not in Valsugana this year!-) Alex From tim at bladerman.com Sun Jul 28 15:23:50 2002 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Sun, 28 Jul 2002 19:23:50 GMT Subject: Guide to the python interp. source? References: Message-ID: "Andreas Kostyrka" >Am Sam, 2002-07-27 um 15.19 schrieb Tim Gahnstr?m /Bladerman: >> I noticed, but thought that I just had missed it. I thought there must be >> some where for such a large project. But the problem is ofcourse ever >> present, "nobody likes to do documentation" >Well, start with the embedding/extending documantation. Will do that, it seems like a good start! >> Maybe look into value/copy return as Alex Martelli mentioned. What I want is >> not really CBR but the, from Ada known "in out parameters" or the Pascall >> "var parameter". >var parameters are true call by reference. And it would make no sense in >a language design, because call by value semantics have cleaner >semantics. I respect your opinion but that doesn't mean that I don't agree with it. I don't think that clean semantics is all that matters in a language design and I dont hink it is more intuitive. But I might verry well change my semantics to a call by value because there seems to be an imense amount of work to fix it. >f(i) with general reference semantics have unnice property, that I know >nothing about i after the call. Now there is nothing in the python That might verry well be an unnice property in some (most) situations but not in this case (my OPINION). >Additionally, the most important use CBR is passing out multiple return >values, which is obviously not needed in python: That is one reason, another is that it might be faster some times, there may be more reasons. (Why do Python have mutable objects? They are not really needed and you dont know what will happen with them when you send them to a funcion) >> A traceback is for instance really cryptic to a novice programmer I want an >> errormessage to look loike this. >> >> "The program stopped running for some unknown reason. It is likely an error >> on line 23 in the file "myprog.cod": >> if (max(3)>variable): >> The error is probably caused by the call to the function max(). If you mean >> to call the built in function max it must have two arguments, namely "val1" >> and "val2" but you only supply it with one argument (constant 3). >> On the other hand it might also be a misspelled call to your own function >> maz() in "mylib.cod" >But that is exactly not correct: It is not wrong either. It is not a complete list of possible errors but it is the most probable. The plan is to make better errormessages to a novice programmer not to make a list of all possible things... >max(someObject) >might also be legal, if someObject is a user made list like object. and mybe the novice using this program is not a novice at all but some ?berhacker from Mars that never ever will make an error... Sorry... what I mean is that it was an exmple error message I wrote there and it was not complete and not even intended to be complete, not even in the actuall program. It is intendet to present the novice with the most probable error. >Well, this at least correct. (arg must be a sequence.) >While your nice message above is misleading. Where you never ever a beginner asking why the errormessages were so utterly cryptic? What I wrote were not wrong, it mentioned the two most likely things. It might not have been the best example but it ilustrated what I meant wich was what asked for. Tim From alanmk at hotmail.com Wed Jul 31 06:05:51 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 31 Jul 2002 03:05:51 -0700 Subject: Good XML tools? References: <3D46D1B5.248A2921@q-survey.be> Message-ID: Laurent Szyster wrote: > In many case (if not most) XML processing is far easier with a > dedicated language like XSLT. Use Python to generate XML and/or > XSLT, but don't use it to transform XML: XSLT is far better at it. I strongly disagree. Have you looked at Zope Page Templates at all? ZPT is a way of controlling the generation of (X|HT)ML from python. It is my own opinion that ZPT and Python is far superior to XSLT, for the following reasons. 1. ZPT allows you to design your *ML page using GUI design tools. XSLT makes this next to impossible. 2. ZPT allows you to validate the structure of your page templates *before* transform. You can only validate the *output* of XSLT templates. 3. ZPT is *much* simpler to learn than XSLT. 4. ZPT provides a full object-oriented language in which to write code:python. Writing everything functionally with XSLT can be real pain. 5. (To me this is the most important one): ZPT breaks the stricture that only allows XSLT to use one XML document to control the generation of another. Consider the following sourceDocument * template -> outputDocument In XSLT, the sourceDocument can only be an XML document (unless you use Xpath extension functions, in which case you're no longer writing XSLT). In ZPT, the sourceDocument can be anything you can fit into python data structures, i.e. anything you like: database data, xml documents, live feeds, calculation results, etc, etc, etc. Admittedly, the concept of ZPT doesn't require Python. It could also be implemented with, for example, Javascript. But Guido invented it, and implemented it in Python, so it's definitely "Pythonic". i-used-to-love-xslt-too-until-zpt-opened-my-eyes-ly-yrs Alan Kennedy. From roy at panix.com Wed Jul 24 08:21:42 2002 From: roy at panix.com (Roy Smith) Date: Wed, 24 Jul 2002 08:21:42 -0400 Subject: Mastering Regular Expressions 2nd Ed. References: <4uppjuooq8qj3hfil9jo9h7h007f2dotus@4ax.com> <7xn0si9o2o.fsf@ruckus.brouhaha.com> <3D3E0CEE.E3B3B4A0@engcorp.com> Message-ID: Peter Hansen wrote: >> Regular expressions work much better if you use them for lexical >> analysis rather than for parsing. > > Would you please expand on that for those of us who are not computer > scientists and/or who do not understand the implications of your > statement? In a nutshell, lexical analysis is figuring out how to break a file up into words and symbols (genericaly called "tokens"), and parsing is figuring out what those words mean. So, if I were to write: "Quick,defenistrate him!" :-) lexical analysis would figure out that I've got the following tokens: 1) a quotation mark 2) the word "Quick" 3) a comma 4) the word "defenistrate" 5) the word "him" 6) an exclamation mark 7) a quotation mark 9) a smiley At this point, I still have no idea what that line means, but at least I've broken it up into token that I can start to try an organize into higher level constructs like sentences and understand what those sentences mean. That's parsing. From aleax at aleax.it Tue Jul 9 08:44:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 09 Jul 2002 12:44:47 GMT Subject: adding methods on the fly References: <878dc260.0207080702.2be7ba9f@posting.google.com> <878dc260.0207090321.14e06bbe@posting.google.com> Message-ID: <3VAW8.59624$vm5.2174084@news2.tin.it> Renzo Tomaselli wrote: > Alex Martelli wrote in message > news:... > >> Py_CompileString (careful about underscore placement!-) won't let you >> easily build a function (or unbound-method) object, which is what you >> need (though you can get there eventually, but it's a long way 'round). > > Fairly disappointing. Since I plan to store such used-defined methods > into a OO database, I would expect it being much more efficient to > store them in a precompiled form. It keeps looking to me as if you're making a lot of implicit assumptions, and that many of them are wrong. What makes you believe, for example, that just exec'ing "def foo(self): pass" does NOT leave you "a compiled form" of function foo (in the locals dictionary used for executing)? You can marshal such objects to bytestrings, too, for storing as BLOBs or whatever. > I still wonder why it's so hard (from a C/C++ perspective) to walk > from a "def foo(self): pass" string to a callable object to be added > to a class. But it's not. exec that with a locals dictionary, and in the dictionary at key 'foo' you find exactly a Python callable object (a function object, to be precise). What IS "so hard" about this? def is an executable statement, used to create function objects, so, if you start with a def statement and want a function object, you, of course, execute the statement. What COULD possibly be easier or mote natural? Maybe you have some unspoken assumption that "compiling" is what gives you an executable object. But it's not necessarily so, in Python. In Python, you get an executable object (a function) from executing a def statement. Compiling (using the compile built-in) gives you a *code* object, which is "executable" in a sense but is not directly *callable* -- and you do need a *callable* object for your purposes (a function is callable). > Ok, I'm not forced to fit all in C++, after all I define the features > my platform is going to offer. An extra layer in Python is acceptable, > provided I hide it from common usage (e.g. adding/invoking methods). My point exactly. > So let's see this "easy" way in more details. Sure. > Let's assume I created a C++ extension in module myExt, which exports > a type for each C++ class to be wrapped (and this type is defined so > that it can be inherited from). Then I would need to defined an empty OK, here's a specific example -- inhe.c exposing an inheritable type with no other functionality (simplified mostly to remove a zillion zeros from the type struct, you can reconstruct it from comments): #include "Python.h" typedef struct { PyObject_HEAD } inhe; static void inhe_dealloc(PyObject *op) { op->ob_type->tp_free(op); } static PyTypeObject inhe_t = { PyObject_HEAD_INIT(0) 0, "inhe", sizeof(inhe), 0, inhe_dealloc, ... 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, "inheritable type", 0, /* tp_traverse */ ... 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ _PyObject_Del, /* tp_free */ }; static PyMethodDef no_methods[] = { {0} }; void initinhe(void) { PyObject* self; inhe_t.ob_type = &PyType_Type; self = Py_InitModule("inhe", no_methods); PyObject_SetAttrString(self, "inhe", (PyObject*)&inhe_t); } Save this as inhe.c, make a setup.py in the same directory with: from distutils.core import setup, Extension setup(name = "inhe", version = "1.0", description = "inheritable type", maintainer = "Alex Martelli", maintainer_email = "aleaxit at yahoo.com", ext_modules = [ Extension('inhe', sources=['inhe.c']) ] ) cd to that directory and do "python setup.py install" and you'll be able to try out some Python code using it, e.g. import inhe class gop(inhe.inhe): pass g = gop() g.pop=23 print g.pop del g print 'OK' > class like: > > #P1: wrapping > import myExt > > class foo(myFoo): # one class per object to wrap > pass Definitely *NOT* per-object, but rather per CLASS (or type) to wrap. And if myFoo is a class exposed from myExt, you need to use myExt.myFoo as the base class. > myExt.hook(foo()) Not quite sure what this hook function is, but presumably it's something your module myExt uses to keep track of subclasses of the classes it exposes, which seems OK (you could do it slightly differently, by tweaking the metaclass for example, but as you don't intend to let endusers freely subclass your extension's classes the simpler mechanism appears to be the better one here). > Then from time to time someone adds a new method to class foo: > > #P2: declaration > def m1(self, args): > do_something > > #P3: appending > foo.m1 = m1 > > #P4: execution > and run it from C++ or from Python. "From C++" is unclear to me, unless it's via PyRun_* or the like. > Now, the entire game is C++ driven. P1, P2, P3 can be merged together > in a string(P2 is an user-defined string) and run through > PyRun_SimpleString. Now new method is attached to class foo and it can > be run through PyObject_CallMethod on the hooked class instance. Or in other Python-oriented ways, yes. > I still prefer a PyClass_New/PyMethod_New/PyInstance_New sequence from > C++, but here we are back to the point of feeding PyMethod_New with > appropriate value from pass P2 above. This is the missing link about > which I couln't find anything on the list (dealing with callables is > general is a black hole). And I still don't see why you "still prefer" a more complex solution to a simpler one. Except, perhaps, due to some unspoken (and wrong) assumptions, as I hypothesized above. There's nothing particularly mysterious about "dealing with callables": the only difference between a callable and any other Python object is that the former has a non-null entry in tp_call, which changes just about nothing else except allowing Python code to call it! (Classic-class instances typically have nonnull entries everywhere and need more complicated tests to check if they're callable and so on -- but you don't need to worry about classic classes here). > Missing precompilation is another missing feature of this solution. Just because you choose to "merge together in a string", above, several steps that you might perfectly well keep separate. As I have by now repeated a few too many times, but don't seem to be getting through to you: if you exec JUST the def statement, and supply an initially empty local dict, then you can fish out of that dict the function object, and do various things with it -- including marshaling it into a bytestring to be saved and restored at will, as well as setting it as an attribute of one or more classes. Nothing stops you from building the classes with PyClass_New, if for some reason you think that's preferable to simpler Python ways (it's not, but it's not terribly worse either, so, suit yourself) -- >> Another possibility is to look at Boost Python, if the schedule for their >> new release 2 (supporting Python 2.2 fully) is compatible with your >> timing constraints > > Several people suggested me to look at Boost, but I feel it deals > primarily with extending, while I'm on the opposite side. _Everything_ you'll find "deals primarily with extending", because that's where all the interesting / difficult / challenging stuff IS. Embedding is very simple once you have totally mastered extending. Your problems might stem from trying to skip the "totally mastered" step. Once you have a complete working solution in Python with extensions, moving some or all of the solution back into C or C++ code is invariably rather trivial, although verbose/boring if indeed it's worth doing at all. But starting with a Python-coded prototype is most often the best idea -- Python+extensions, in this case. > On the other hand I don't feel good to add an entire package only for > the purpose of adding new Python methods on the fly. If you have tiny C++ programs to start with, the idea of adding 10KB or code, of more, can indeed be unsettling -- I tend not to think of that because the C++ programs I dealt with tended to be megabytes rather than kilobytes, so a few tens of KB more or less didn't matter. Further, Boost Python is hardly a SIMPLE piece of code -- the C API are much simpler (although fussier and messier to deal with, as is often the case for C-coded versus C++-coded functionality). So, if you don't need it (because you need to expose to Python only a very few, simple classes, and would take no advantage of the many extras that Boost Python embodies, such as setters/getters, ability to override virtual functions from Python in such a way that the override will also be seen by C++ callers, etc, etc), the simpler solution, based on Python's C API, can surely be preferable. The puzzle is that you seem persistently unsatisfied with said "simpler solution", and I _still_ can't quite grasp WHY. Alex From fredrik at pythonware.com Mon Jul 8 17:19:58 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Jul 2002 21:19:58 GMT Subject: Newbie question on Tkinter References: <2259b0e2.0207030947.4a13834a@posting.google.com> Message-ID: <2mnW8.15342$p56.4970498@newsb.telia.net> Michele Simionato wrote: > I have found a confusing (to me) behavior of Tkinter in > displaying GIF images. it's a "feature", sort of -- Tkinter doesn't hang on to PhotoImage objects (they're just things that can be converted to strings), so Python's garbage collector might decide to remove them. for a bit more information, see: http://effbot.org/zone/tkinter-photoimage.htm this is also discussed in the Python FAQ: http://www.python.org/doc/FAQ.html#4.69 > P.S. BTW, how to display jpeg images ? PIL can help. follow the effbot.org link above for an example. From irmen at NOSPAMREMOVETHISxs4all.nl Thu Jul 11 16:47:38 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 11 Jul 2002 22:47:38 +0200 Subject: try..catch..finally? References: Message-ID: <3D2DEEEA.9030702@NOSPAMREMOVETHISxs4all.nl> Mark McEahern wrote: > not that i knew this from first hand experience--that's what google's for > --but python did have a try-except-finally before the 1.0 release. > you can read all about it here: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=3967d908.363887342%4 > 0news.online.no > > // m Heh, I didn't know. I've boarded the ship at release 1.2 :-) So I guess the answer to my question is AMBIGUITY. A separate try..finally around the other try block is unambiguous, in contrast to the try..catch..finally construct. Thanks Irmen From gerhard.haering at gmx.de Tue Jul 9 21:00:52 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 10 Jul 2002 03:00:52 +0200 Subject: writing python extension modules In-Reply-To: <3d2b8580$1_1@nopics.sjc> References: <3d2b8580$1_1@nopics.sjc> Message-ID: <20020710010052.GA1461@lilith.my-fqdn.de> * Adonis [2002-07-09 20:53 -0400]: > is there a simple hello world style program that can show me the > extreme basics on writing python extensions, [...] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509 Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From kendall at monkeyfist.com Thu Jul 11 11:23:22 2002 From: kendall at monkeyfist.com (Kendall Clark) Date: Thu, 11 Jul 2002 10:23:22 -0500 Subject: Good SOAP lib for Python 2.2 In-Reply-To: ; from cbbrowne@acm.org on Thu, Jul 11, 2002 at 03:08:58PM +0000 References: <3D2D9B2C.3030606@NOSPAMREMOVETHISxs4all.nl> Message-ID: <20020711102322.A7603@monkeyfist.com> On Thu, Jul 11, 2002 at 03:08:58PM +0000, Christopher Browne wrote: > Irmen de Jong wrote: > > I'm using Python 2.2.1 and I'm searching a current, up-to-date > > SOAP library for Python. > > I tried ZSI but it fails because apparently it uses an old XML api. > > > > What should I try instead? > > Something's odd there. There hasn't been any activity with ZSI since > about mid-May. > > And zolera.com (home of Rich Salz, main ZSI developer) seems dead (as > in "DNS doesn't think it exists anymore"). > > Have Zolera/Rich Salz disappeared? Zolera has, afaik, gone under. Salz is active on XML-SIG list. He's also the new XML.com Web Services columnist, and he's pretty much doing it in Python, which some on this list may find interesting. See, for example, Generating SOAP http://admin.xml.com/pub/a/2002/06/12/soap.html Examining WSDL http://admin.xml.com/pub/a/2002/05/15/ends.html the first of which uses ZSI to muck about with Google. I've also heard rumors of a Python-XML column at XML.com, but I can neither confirm nor deny them. :> Best, Kendall Clark From erik.wilsher at iname.com Thu Jul 4 02:48:22 2002 From: erik.wilsher at iname.com (erik_w) Date: 3 Jul 2002 23:48:22 -0700 Subject: baffling bug in this bit of code! References: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> Message-ID: Daniel Jaeggi wrote in message > I'm reasonably new to python but I've used various other languages > before. The bug in the following bit of code has got me banging my head > as it should be trivial. If anyone can help, I'd be most grateful. > > This snippet: > >...snip code that locates max of x and y in nodes You might be better off with this snippet of code (if you run 2.1 or newer): nodes=self.nodes locs_x = [nodes[n].location.x for n in nodes.keys()] locs_y = [nodes[n].location.y for n in nodes.keys()] max_x = max(locs_x) max_y = max(locs_y) Shorter and probably faster. BR EW From tjreedy at udel.edu Fri Jul 26 11:48:11 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Jul 2002 15:48:11 GMT Subject: Guide to the python interp. source? References: Message-ID: <%ae09.337968$Im2.17146099@bin2.nnrp.aus1.giganews.com> > Things I want to change is for example, everything should be "call by > refferense", It already is, which is why functions can mutate mutable objects. (This surprises some beginners.) Of course, for immutables (numbers, strings, tuples), there is no semantic difference between reference and value passing except for reduced memory usage. Terry J. Reedy From tundra at tundraware.com Wed Jul 10 19:10:02 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 10 Jul 2002 23:10:02 GMT Subject: Win32 Registry Manipulation w/PythonWin? References: Message-ID: David LeBlanc wrote: > OOps, I saw this after I posted my pointer to _winreg... > > I was confused in part by the mention of PythonWin - that's not needed to do > registry stuff with the standard winreg module. > > What exactly are you trying to accomplish with the registry? Manipulating > the registry isn't all that hard, but if you do scramble it, it's a Very Bad > thing. One thing you should do before testing registry manipulation code is > to make an emergency repair disk - this (IIRC) will also offer the option of > making a backup of the registry. > > David LeBlanc > Seattle, WA USA I want to write a program which goes to specific registry locations and scrubs out the MRU cruft left behind by so many programs. So, for example, say I've edited a bunch of Word docs, I want to run a script from the scheduler which periodically goes in and removes the MRU entries. ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From cliechti at gmx.net Tue Jul 23 09:46:57 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Jul 2002 15:46:57 +0200 Subject: Help! References: Message-ID: bgong at solution-soft.com (Benia) wrote in news:b6a6b494.0207222010.75e4e438 at posting.google.com: > Hello, guys, > Could you tell me the nntp server address of this groups? thats not our problem ;-) ask your ISP. usualy news.myispsname.com it's often on the same address as you mail, just exchange mail.x.x with news.x.x to get the address. alternatively you can also have this group as mailinglist. in that case go to python.org and subscribe there. chris -- Chris From fperez528 at yahoo.com Wed Jul 24 13:52:55 2002 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 24 Jul 2002 11:52:55 -0600 Subject: Make me beautiful (code needs help) References: <9co%8.2838$ub.168@nwrddc02.gnilink.net> Message-ID: Mark wrote: > Fernando Perez wrote: > >> For this kind of thing, look at Numeric. It has a ton of functions >> ready-made for numerical processing, very convenient slicing syntax >> (better than python lists) and as a bonus it's fast. Explicit loops in >> python over large lists for numerical processing take an eternity and a >> half. That's what Numeric is for. > > Fernando, > > Thanks for the tip. Is there a "HOWTO" doc on installing Numeric? I seem > to recall looking at it awhile ago and seeing NumPy NumericPy NumPython NP > (ok, I'm making them up now) ... point is, I got sorely confused as to what > the current "numerics in python" package was. Hi Mark, go to: http://sourceforge.net/project/showfiles.php?group_id=1369 and install Numeric-21.3, NOT numarray. Numarray is a rewrite of Numeric (mostly backwards-compatible, but internally better) which will eventually replace it, but it's not production-ready yet. NumPy is just another name for Numeric :). Both NumPy and Numeric are commonly and interchangeably used in the community, get used to it. Installing Numeric is as easy as untarring the .tar.gz, and typing the usual 'ython setup.py install'. Everything goes where it should. You should also grab the manual: http://www.pfdubois.com/numpy/numpy.pdf It's mandatory reading to make real use of Numeric. Cheers, f. From twisted at itamarst.org Sun Jul 14 22:11:12 2002 From: twisted at itamarst.org (Itamar Shtull-Trauring) Date: Sun, 14 Jul 2002 22:11:12 -0400 Subject: ANN: Twisted 0.19.0 Message-ID: <3D322F40.80504@itamarst.org> Twisted is an event-based framework for internet applications, written in Python and licensed under the LGPL. For more information, visit: http://www.twistedmatrix.com Join the list at: http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python Our IRC channel is #twisted on irc.openprojects.net. What's New in 0.19.0 ==================== - cReactor, a C-based reactor for faster networking. - Reimplemented OSCAR protocol (for AIM and ICQ). - Added a new MVC-based web framework. - Refactoring of Deferreds. - Support for persisting to abstract object tree (this is equivalent to pickle, except that the output is Python source code.) - Processes can now be run setuid/setgid. - Huge number of bugfixes, including much improved SSL support, and lots more documentation. What is Twisted? ================ Twisted is an event-based framework for internet applications. It includes a web server, a telnet server, a chat server, a news server, a generic client and server for remote object access, and APIs for creating new protocols and services. Twisted supports integration of the Tk, GTK+, Qt or wxPython event loop with its main event loop. The Win32 event loop is also supported, as is basic support for running servers on top of Jython. Twisted supports TCP, SSL, UDP, Unix sockets and subprocesses out of the box. Twisted currently supports the following protocols, all implemented in pure python, most of them as both servers and clients: - NNTP - FTP - HTTP - SOCKSv4 - SMTP - IRC - telnet - POP3 - AOL's instant messaging TOC - OSCAR, used by AOL-IM as well as ICQ (client only) - DNS - finger - Echo, discard, chargen and friends - Twisted Perspective Broker - LDAP is available as a separate plugin From matt_gerrans at hp.com Tue Jul 9 17:27:32 2002 From: matt_gerrans at hp.com (Matt Gerrans) Date: Tue, 9 Jul 2002 14:27:32 -0700 Subject: File size error in os.stat with large files. References: <28bbdc67.0207091119.6d9ecd48@posting.google.com> Message-ID: > You have to compile python with large file support to handle files > over 2GB. To test whether you have this enabled: Do you know why the binaries are not compiled with large file support as default? Does it cause other problems or does it slow down os.stat()? Also, if this is on Windows, short of recompiling Python, you could try these two things (I don't have time to create a 2+ GB file to test whether they actually work! If you are running Windows, you can try it out and let us know): from win32com.client import Dispatch fs = Dispatch('Scripting.FileSystemObject') fileob = fs.GetFile('c:\\temp\\tkinter.txt' ) print fileob.size Also, another trick that is even more likely to yield correct results on the Windows platform (sorry) is to use win32api.FindFiles() (which I think is implemented with the FindFirstFile() and FindNextFile() APIs to build a list). For each matched file, the tuple contains information from WIN32_FIND_DATA, which includes two 32-bit values: nFileSizeHigh and nFileSizeLow. So this should do the trick: import win32api fileinfo = win32api.FindFiles( 'c:\\temp\\tkinter.txt' )[0] size = (long(fileinfo[4]) <<32) + fileinfo[5] - Matt From peter at engcorp.com Mon Jul 8 00:02:40 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Jul 2002 00:02:40 -0400 Subject: How to organize test cases with PyUnit References: <3D2898DC.B59538B1@engcorp.com> <3D290992.A9AD9AD9@engcorp.com> Message-ID: <3D290EE0.C9A97B1E@engcorp.com> Roy Smith wrote: > > Peter Hansen wrote: > > Rename the runTest() > > method to start with the text "test", and then change the __main__ > > content to be simply 'unittest.main()' instead of the dictEntries.run > > that you have. > > OK, that seemed to work, even though I'm still not sure I understand all > the subtleties of what's going on, and what role all the various classes > (TestCase, TestSuite, TestResult, TestLoader, etc) play. I don't really either, but I've never needed to. Basically just subclass TestCase and do the above and you may never need to either. :) > After writing just a few test cases, I've come to the conclusion that > the names of the individual test methods are meaningless, except to > dictate what order the tests run in. I've taken to just naming them > test101, test102, etc (leaving plenty of room in the numbering system to > insert additional tests). The doc strings seem to be the place to get > creative, since those are what's printed. Is it really important the order the tests are run in? Sometimes it is for me, though rarely, so in those cases I'll prefix the name with test01 or whatever, but I still put a useful name in it like test01_CheckLength()... I never like to feel like I'm doing extra/wasteful work to maintain things, like "leaving plenty of room" to insert additional tests. > I don't see it mentioned in the documentation, but it seems that if you > make multiple subclasses of unittest.TestCase, the names of those > classes get sorted and run in order as well. So, I'm inclined to adopt > the same scheme of just naming the classes class101, etc. I thought they were run in order of definition in the file, though I could be wrong. Since I *never* care about the order of the TestCases, though, I just keep useful names for them too, instead of numbers. -Peter From glongman at ilangua.com Tue Jul 30 10:32:24 2002 From: glongman at ilangua.com (Graeme Longman) Date: Tue, 30 Jul 2002 15:32:24 +0100 Subject: Searching for email address References: <3D469D2A.28154B51@ilangua.com> Message-ID: <3D46A378.F87C95DA@ilangua.com> Found one. If anyone needs something similar check out: http://www.regxlib.com/ Cheers. Graeme Graeme Longman wrote: > Hi, > > I'm writing some code which searches html for email addresses. Does > anyone out there have a good regular expression syntax for searching for > the email string, I'm sure this must've been done a few times before. > > Thanks in advance, > Graeme > > -- > http://mail.python.org/mailman/listinfo/python-list From bgong at solution-soft.com Tue Jul 23 00:10:59 2002 From: bgong at solution-soft.com (Benia) Date: 22 Jul 2002 21:10:59 -0700 Subject: Help! Message-ID: Hello, guys, Could you tell me the nntp server address of this groups? reguards, Benian From andymac at bullseye.apana.org.au Sun Jul 21 01:23:34 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 21 Jul 2002 16:23:34 +1100 (edt) Subject: unloading imported modules In-Reply-To: Message-ID: On 20 Jul 2002, [iso-8859-1] Fran?ois Pinard wrote: > So, when the reference count of a module drops to 0, and I get that this > is possible, then the module is unloaded. Isn't it? Also, I wonder if > a module coming from an `.so' file be effectively reloaded. And then, if > the previous copy (the memory area in which the `.so' is paged) gets freed? AFAIK, dynamicly loaded extension modules (*.so, *.DLL) can't be satisfactorily unloaded or reloaded. While it might be possible in theory, in practice there are all sorts of platform specific gotchas which thwart attempts to implement this. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From aleax at aleax.it Fri Jul 5 11:45:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Jul 2002 15:45:53 GMT Subject: [Newbie] How to output dictionary sorted on content (not keys) References: <3d243af0.465960@news.texas.net> Message-ID: Achim Domma wrote: > "Eric Brunel" wrote in message > news:ag1fj0$inr$1 at wanadoo.fr... >> I don't which one of these two or Achim's one is the most efficient. > > I also don't know, but you can make it in one line: > > for count,name in dict([ (count,name) for name,count in > myDict.items() ]).items(): print count,name > > wether this is good code or not is another question ... ;-) > > Achim I'm not sure what you believe you're achieving with this long line. The items of any dictionary are in arbitrary order, as defined by the implementation's needs for speed (which dictate dict implementation by hashing). So there's no useful defined purpose in making a dict out of a sequence of pairs and then immediately looping on that dict's items. Maybe you did some tests and it seemed to you that this changed the ordering in some useful way, rather than just replacing one arbitrary order with another one fully as arbitrary...? If you want to output a histogram in ascending count order with a single long statement, this is indeed definitely feasible, and it's just as definitely a horrible idea. But, purely for instructional purposes, here's how one could work it out...: [approach 1] the crux of the matter is being able to make a .sort call (which sorts in-place and returns None) and THEN iterate on the now-sorted list. Unfortunately given the one-statement constraint we can't use an ordinary assignment to give a name to the list, sort it, and then loop on it. But, list comprehensions ALSO bind names, so...: for count, name in ( [ None for x in ( [(count, name) for name, count in myDict.items()],) if 0] or x.sort() or x): print count, name Basically this trick uses 'or' to join expressions which are mostly acting as para-statements but returning false values -- None for x.sort(), an artificial empty list for [ 1 for x in ... if 0 ] -- with side effects (sorting x for x.sort(), binding name x for the list comprehension). In other words. this dirty trick is a pretty general one, which doesn't make it any less dirty, of course. Approach 2 is (to me) a bit more interesting but less general. You could say it relies on a bin-sort rather than Python's normal (and excellent) samplesort. A dict is clearly a nice way to do a bin-sort -- except that you lack an immediately obvious way to walk in a sorted way over the bins themselves. No problem -- min and max are there just for you. So here's approach 2 in a clear, multistatement way: auxdict = {} for name,count in myDict.iteritems(): auxdict.setdefault(count, []).append(name) for key in range(min(auxdict.keys()), max(auxdict.keys())+1): for name in auxdict.get(key, []): print key, name Pretty clear idea, I hope? So, we just need to wrap this up into a single statement, e.g.: for k, n in [ (key, name) for auxdict in ( {}, ) for x in ( [ auxdict.setdefault(count, []).append(name) for name, count in myDict.items() ], ) for key in range(min(auxdict.keys()), max(auxdict.keys())+1) for name in auxdict.get(key, []) ]: print k, n Now, I don't really know why people are so obsessed about wrapping things up as "a single statement" rather than going for speed, clarity, concision, elegance, and all other aspects of code that can sensibly be considered good ones. But anyway, if "wrapping up into a single statement" is what rocks your boat, for whatever reason, you can hardly complain that Python doesn't LET you do it. It may be silly, but then, some of Monty Python's routines were also silly, but still hilarious, no? Alex From opus at value.net Thu Jul 18 04:30:46 2002 From: opus at value.net (Opus) Date: Thu, 18 Jul 2002 01:30:46 -0700 Subject: Newbie : Processes management under W2K In-Reply-To: Message-ID: <3D361A46.27855.49D6D84@localhost> Right click on the taskbar, select Task Manager. Win2K also lets you hit CTRL-ALT-DEL to bring up a 'Windows Security' window from which you can select Task Manager. This is also the best way to lock it while you are away. If you are looking for services that are running, 'Net Start' from CLI window should do you. On 18 Jul 2002 at 0:53, Marc wrote: > Hi everybody, > > in order to kill a specific app, i'd like to know how to get the list > of all processes currently running under Win2000 with name, pid, etc.. > > thanks in advance ! > > Marc > -- > http://mail.python.org/mailman/listinfo/python-list --Opus-- Priests have no hats, Cardinals have those little red beanies, the Pope has a collection of big hats...God must have a huge frigging Sombrero up there in heaven. - Unknown -------------------------------------------------------- Get added to my Humor list: mailto:opus at value.net?subject=ADD_HUMOR Get added to my Neat list: mailto:opus at value.net?subject=ADD_NEAT Get my PGP public key: mailto:opus at value.net?subject=PSEND&body=send%20PublicKEY.asc Visit My Home Page: http://value.net/~opus/ From aleax at aleax.it Sat Jul 20 04:15:59 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 20 Jul 2002 08:15:59 GMT Subject: A better self References: <190720021018041866%pecora@anvil.nrl.navy.mil> <3D385A46.6DC47857@astro.cornell.edu> Message-ID: <3%8_8.106325$vm5.3640993@news2.tin.it> Grant Griffin wrote: ... >>to return various quantities. In a language that boasts of how > > I don't remember any "boasting". Python is for the humble (except for > maybe Tim and Fredrik ). Nah, ALL of us bots are unhumble -- even I, the one programmed for occasional human-like errors in order to better fool you all. > with self: > result=sin(t)*x**y+sqrt(z) # A pretend formula > > I don't know if there's a technical reason (in terms of either Python > grammar or C implementation) why this wouldn't work, but perhaps it's not If we adopted the Visual Basic variant of this, with a leading dot to distinguish fields of the with-ed objects (as others have often suggested), technical feasibility would be guaranteed. Without such a tweak, it's something of a mess. Is this statement computing a local variable result, or a field self.result, for example? Either interpretation could be quite desirable, and any choice between them seems rather arbitrary. Access to local variables inside a with would be slow, since each time it would have to be preceded by a lookup in the with-ed object. Etc, etc. WITH the leading-dot convention, and some drastic simplification about what happens on nested with (e.g.: all leading-dot names always only refer to the innermost with -- there is just NO way to refer to outer-nested withs), I think it would be feasible. Desirable, I dunno...: > any-construct-that's-in-pascal-and-ada-but-not-in-C > -can't-be-all-bad--ly y'rs, yes but, if it's also in Visual Basic ... ??? Alex From deltapigz at telocity.com Tue Jul 9 20:53:25 2002 From: deltapigz at telocity.com (Adonis) Date: Tue, 9 Jul 2002 20:53:25 -0400 Subject: writing python extension modules Message-ID: <3d2b8580$1_1@nopics.sjc> is there a simple hello world style program that can show me the extreme basics on writing python extensions, i do not need some big code just simple, and i can easily pick up the rest as i go along, i have googled, and have checked out activestate, and nothing, in particular i will be compiling in msvc++6sp5, but want to maintain a xplatform touch to it. any jelp would greatly be appreciated. Adonis From peter at engcorp.com Sun Jul 7 10:54:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Jul 2002 10:54:10 -0400 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> <3D282413.1010801@ob_scure.dk> Message-ID: <3D285612.762E590C@engcorp.com> Alex Martelli wrote: > > You're welcome! I take advantage of the occasion to mention that > Paul Dubois is among the nominees for the "Programmers' Choice" > award, http://www.activestate.com/Corporate/Awards/ActiveAwards.html > (so am I, but I never contributed to Numeric!-), open for everybody > to vote until July 17. If you find Numeric the best thing since > sliced bread, visiting the site and voting for Paul might be a nice > way to signal your appreciation. Unfortunately it is not possible to vote only for the Python programmers, making it impossible for me to vote in an ethical manner. I know nothing of most of the other areas (Perl, etc.) and I won't resort to random voting just to get in my votes for Paul, you, or the others. (I assume I didn't miss something there. I left the others unselected and it refused my submission.) -Peter From raims at dot.com Sat Jul 20 10:25:00 2002 From: raims at dot.com (Rhymes) Date: Sat, 20 Jul 2002 16:25:00 +0200 Subject: Python 2.3 References: <8r1hjuk58o67amhuvfna5htpe2gtl3gnlr@4ax.com> Message-ID: <5jkiju4n9pgu1e6a39vqlnt918v585j3c5@4ax.com> On 19 Jul 2002 18:37:27 -0400, aahz at pythoncraft.com (Aahz) wrote: >In case anyone cares about this specifically, it's supposed to be >"before the end of 2002". Thanks -- Rhymes rhymes at myself.com " ride or die " From sholden at holdenweb.com Wed Jul 24 11:23:32 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 24 Jul 2002 11:23:32 -0400 Subject: SOLVED: Write \x1a to binary file References: Message-ID: "Harald Schneider" wrote in message news:ah1jph$jab$03$1 at news.t-online.com... > Thanks a lot! > > I was a little bit fast with my request. Due to a bug, the end of my file > was overwritten, so that the end marker \x1a was deleted. > In fact, it is sufficient to open the file with mode 'b' to write all kind > of binary data (on Win32, running Active Python 2.1). > > BUT: > One strange side effect, I recogniced ... > - I write \x1a to the end of a file. > - I close it and reopen in text mode > The result: the last byte gets cut off ... even when nothing is written to > that file! > This is maybe an old thread, so perhaps you've already realized that \x1a is CTRL/Z, which DOS-based systems recognize as terminating a text file. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ ----------------------------------------------------------------------- From neil at neiljmac.com Mon Jul 22 07:06:13 2002 From: neil at neiljmac.com (Stafford Drake) Date: 22 Jul 2002 04:06:13 -0700 Subject: j2ee vs. python (and what our evil competitors are saying about python) References: <96c7f32.0207081518.52ea644a@posting.google.com> Message-ID: <6cbc6538.0207220306.3647e4b7@posting.google.com> I believe these people are doing a good job of making themselves look silly. The best thing you can do is to post a list of good Python resources for those of your customers who are interested and let them make up their own minds. (BTW your timesheet app looks excellent). Regards, SD curt at journyx.com (curt finch) wrote in message news:<96c7f32.0207081518.52ea644a at posting.google.com>... > Our free web timesheet app is written totally in Python. > One of our competitors is saying the following > things about python to our customers. Help me make them look stupid. > Please? > > ps. enjoy our free stuff at http://pnk.com/wt3.html > > thanx for any comments you can provide > > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > > > > > > > > > > > > > > > > Summary > Python is often used as pseudocode to conduct rapid development. Its > major users are web sites that do not reuse code and often conduct > “throw away” development to meet internet development time > tables. It is a very new language and has very little support compared > to the Java development community. It is also not J2EE compliant. > > Platform Drawbacks > As a new relatively untested development platform in the licensed > software community, Python has certain deficiencies with which all > users and developers should be aware. > > > > > Issues and concerns > > ? No integrated GUI (Graphic user interface) support. > > ? No compiler to the native code. > > ? No automatic garbage collection. > > ? Does not have vast number of libraries as that of Java, > Perl, C++; etc. > > ? Since Python is an interpreted language, it requires > frequent run-time checks and thus does not provide the speed, > performance and efficiency of compiled languages like Java, Perl and > C++, which is a major issue. > > ? Python does not provide multiple ways to perform tasks as do > most other languages. > > ? It takes a lot of time for Python to adjust to the > indentation style of the structuring code. > > ? Since Python is relatively a new language, there are only a > few resources available for information on its latest developments. > > ? Limited documentation- only two English language books exist > which provide tutorials or a library reference for Python. > > ? The language is restricted to fewer code modules. > > ? Lacks native threading capabilities. > > ? Lacks basic tools such as integrated source level debuggers. > > ? No packaging methods for software distribution. > > ? Lacks tools to solve typographical and type mismatch classes > of errors. > > ? Python cannot write docstrings in C++. > > ? Python is difficult to read. > > ? Dynamic loading is not available on all systems, requiring > that a developer use static loading. > > > > > > > Application Areas > ? Prototyping and development > > ? Platform independent graphic user interface applications > > ? Internet scripting/applications > > ? Automated test harnesses > > ? System administration applications > > ? Shell scripting/OS Scripting > > ? Text processing > > ? Database Interfaces > > ? Application Extensions > > ? Distributed Programming > > > > Python users > ? Yahoo > > ? Infoseek From richie at entrian.com Fri Jul 19 06:56:41 2002 From: richie at entrian.com (Richie Hindle) Date: Fri, 19 Jul 2002 11:56:41 +0100 Subject: Help with win32ui.CreateFileDialog References: <3D36C23D.A487E18A@gmx.de> <3D3743DB.2080109@skippinet.com.au> Message-ID: <6frfjukao9m5j423sasophbr7al5bfimgt@4ax.com> [Thomas] > I am running into a problem with win32ui.CreateFileDialog during the > selection of multiple files. I am successful in selecting files only up > to a certain number. [Mark] > I fear the limitation is in MFC itself. You're right. The offending line of code is: TCHAR m_szFileName[_MAX_PATH]; // contains full path name after return in afxdlgs.h. Whoever wrote that (and didn't handle FNERR_BUFFERTOOSMALL) wasn't thinking about multiselect. The hoops that either MFC or win32ui would need to jump though to make this work are detailed in Q131462, at: http://support.microsoft.com/directory/article.asp?ID=KB;EN-US;Q131462& -- Richie Hindle richie at entrian.com From none at nospam.org Thu Jul 18 12:00:32 2002 From: none at nospam.org (Frank Fejes) Date: Thu, 18 Jul 2002 11:00:32 -0500 Subject: starting other programs from within python References: <20020716.171155.619290071.333@beer.com> <3D349AA0.1AE34452@engcorp.com> <20020717.123645.824272813.337@beer.com> Message-ID: On Wed, 17 Jul 2002 11:36:57 -0500, hejduk wrote: > In article <3D349AA0.1AE34452 at engcorp.com>, "Peter Hansen" > wrote: > I'm using python 2.2, on slak linux using gnome, and i'm monitoring the > memory usage with gtop. > > my main concern really is whether i'm starting the processes in the > right manner. would spawnv or something else be better? i'm new to > threads so i don't know whether they need to be stopped manually or > whether they'll shut down automatically. If your goal is simply to execute applications from a menu, threads seem like overkill to me. I'd simply use the usual fork/exec methods. In Python, these are in the os module along with the spawn methods you refer to. --frank From ld at nospam.com Thu Jul 11 23:01:57 2002 From: ld at nospam.com (Larry) Date: Fri, 12 Jul 2002 03:01:57 GMT Subject: Recomendations on Books References: Message-ID: "Ray Tux" wrote in message news:hfrX8.3972$7W6.2920 at nwrddc02.gnilink.net... > Hello I am a beginer to programming and I have chose Python. I was just > wandering if you guys could recomend some good Python Beginers books. Python: Developer's Handbook (Other Sams) Andre DOS Santos Lessa, Andre S. Lessa I was just in Barnes and Nobles and had a chance to look at this book. I am fairly new to Python also and I found this by far the best book of what they had there. It was $45 bucks at B&N but I just ordered it myself from Amazon.com via a used book. My price was $4.95 plus shipping for a total of about $9.00. Larry From Chris.Barker at noaa.gov Fri Jul 26 14:53:11 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Fri, 26 Jul 2002 11:53:11 -0700 Subject: Numeric data question References: <3D3EF9AD.A0F661BC@noaa.gov> Message-ID: <3D419A95.F4FDA598@noaa.gov> terry wrote: > I will have found out how to properly ask it. That is the first step in a newsgroup...how do I ask my question? > You're example is what is not acceptable (to the accounting > community) My example was just that, an example. It was not intended to be a decent implimenation, just an example of how one could write such a class, and an example of how such a class could interact with other Python numeric types, which is how I read your original question. However, asside from being very incomplete, I wander what was unacceptable about it? It used python long integer micropennies for internal storage, so you would have no floating point problems and unlimited size. Maybe not a well optimized solution, but it sounds more accurate that what VB uses, according to another poster's description. Anyway, you would have some work to do, and have to know what you're doing to do it right, maybe Tim Peters' FixedPoint class will fit your needs (and Tim Peters does know what he is doing). > I've also used routines that are based on > strings and integers. They all share the common trait of being > ugly. If you wrote a python class that way, the uglyness would be hidden from the user. Fortran did not offer that level of encapsulation. Good luck, -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From brian at sweetapp.com Tue Jul 9 13:35:57 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 9 Jul 2002 10:35:57 -0700 Subject: Securing SimpleXMLRPCServer? In-Reply-To: <1026214951.12828.94.camel@lestat.howden.press.net> Message-ID: <003b01c2276f$1aae7850$bd5d4540@Dell2> > I apologise for being a nuisance. I've added the code in, as per > Brian's comments below, but still get an error, when running the client: > > xmlrpclib.Fault: converted'> The exception is now totally different! Please post the revised server code. Cheers, Brian From tjreedy at udel.edu Fri Jul 19 13:39:20 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Jul 2002 17:39:20 GMT Subject: A better self References: <3D3724C0.F3286A11@astro.cornell.edu> <190720021018041866%pecora@anvil.nrl.navy.mil> Message-ID: "Louis M. Pecora" wrote in message news:190720021018041866%pecora at anvil.nrl.navy.mil... > Many people have suggested doing something like the following (which is > reasonable) to eliminate self. from mathematical expressions: > > t, x, y, z=self.t, self.x, self.y, self.z > result=sin(t)*x**y+sqrt(z) # A pretend formula > > My question is how much overhead is added by the assignments in the top > line? I suspect not much at all, but then I do not know how the > interpreter handles these things. You are correct. Reference to local variables is optimized to be fast via array lookup*. If you use a variable at least twice (as in quadratic formula, for example), you might actually gain by copying to a local. Certainly, copying a global or builtin method to a local for repeated use is a standard Python speedup trick. Note that when you do the copying, you can also rename, thus allowing both self-explanatory attribute names and short formulas in standard form. Consider def mortgage_pay(self): i = self.interest_rate n = 12*self.years p = self.principal return Terry J. Reedy * IE, when "meth(self, a): b = self.attr; return (a+math.sin(b))/b" is compiled names 'self', 'a', and 'b' become slots 0, 1, and 2 in a behind-the-scenes localvars array. There is no runtime dict lookup as there is for globals and self attributes. From sneavreet+nospam at innocent.com Sun Jul 7 06:36:26 2002 From: sneavreet+nospam at innocent.com (Anders Dahlberg) Date: Sun, 7 Jul 2002 12:36:26 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <3D275E8A.3000003@ob_scure.dk> <3D276B81.9090003@ob_scure.dk> Message-ID: Hello, comments inline > > With Python, you can exploit multiple CPUs only by multi-*processing* -- > > and here, it's possible that Windows' multi-processing inefficiencies > > may byte you (with Unix-like systems, often multiple processes or > > multiple threads in one process have quite comparable performance). > > Ok, thanks. > The actual job is easily parallelisable (is that a word? :-) in that it > can be broken into a number (about 500) of calls to a function that > takes one integer as input, ie. > calcUnit(unitnum) > (This assumes that a database connection is available through a class or > global variable to the function). > > I was planning on spawning one single-threaded XMLRPC-server per CPU per > machine and then having a control process on one of the machines with a > thread per process. These threads would fetch unit numbers from a Queue > object and call the XMLRPC server using xmlrpclib. > > Am I correct in beliving that this would utilize all CPUs? (Windows > issues aside). Newbie argument: Why not consider using jython? Same scripting as python, better scaling to multiple cpu's - seems atleast to me as an easier solution than xml-rpc? (maybe it's easier to sell the idea to your boss too, due to java-hype and all ;) > Best Regards > Thomas Jensen /Anders From bokr at oz.net Wed Jul 24 20:23:12 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Jul 2002 00:23:12 GMT Subject: Multikey dictionary References: <3d3d596e.357860250@news.skynet.be> Message-ID: On Tue, 23 Jul 2002 13:26:57 GMT, henk_derudder at hotmail.com wrote: >Sory for reposting this, I forgot to mention a subject in my first >post :-) > >Hi, > >What datatypes can one use as key in a dictionary? Pretty much anything non-mutable. It'll complain if you give it something unhashable. > >Can I use for example two longs as key (kind of a double key)? sure, just put them in a tuple and use that as key. >>> d={} >>> a=[1] >>> b=[2] >>> d[ (a,b) ] = 'zee' Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable >>> >>> d[ (1,2) ] = 'one comma two' >>> d[ (3,4) ] = 'three comma four' >>> d[(1,2)] 'one comma two' >>> a=(1,2) >>> d[a] 'one comma two' >>> a=(3,4) >>> d[a] 'three comma four' > >If not, are there examples on how to achieve this? > Regards, Bengt Richter From maxm at mxm.dk Fri Jul 5 01:51:46 2002 From: maxm at mxm.dk (Max M) Date: Fri, 05 Jul 2002 07:51:46 +0200 Subject: Sorting a dictionary by value References: Message-ID: <3D2533F2.1040908@mxm.dk> Roy Culley wrote: > I'm sorry if this is a novice question but I have searched google > and the python FAQ and haven't found an answer. > > I have a large dictionary where I want to sort and print based > on the largest values in a dictionary and not the keys. > > Now in perl you can do: > > @Keys = sort { $Hash{$b} <=> $Hash{$a} } keys %Hash; > > Is there any such magic for python? # the basic sort sortedList = [(key, theDict[key]) for key in theDict.keys()] sortedList.sort() # if you want most frequent first sortedList.reverse() # plain printout for frequency, word in sortedList: print 'word: %s, freq: %s' % (word, frequency) # or for a faster printout of large amounts of text print '\n'.join(['word: %s, freq: %s' % (item[1], item[0]) for item in sortedList]) regards Max M Hmmm seems to me that I answered this only yeasterday. Oh wait ... I did ;-) From jonathan at onegoodidea.com Fri Jul 26 03:53:09 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Fri, 26 Jul 2002 08:53:09 +0100 Subject: python class question References: Message-ID: On 25/7/2002 19:38, in article Xns9256D2197BD87cliechtigmxnet at 62.2.16.82, "Chris Liechti" wrote: >> class xrml(SimpleItem.SimpleItem): >> def init_db(self): >> try: >> dbc = getattr(self, connection) > > why not: > dbc = self.connection Because that won't work. Look again at the code above. It gets an attribute of self with the *name* stored in 'connection'. I don't know where 'connection' comes from here. The code that you've shown us Axel would never have worked, so I'm guessing it is the result of playing with the original code. I'm guessing it should have read something along the lines of: dbc = getattr( self, self.connection ) presumably Zope (warning: I know nothing about Zope) fills in 'self.connection' with the name of the connection method that should be called so that the code can be database independent (though that could have been achieved much more simply). >> except: > > one should only catch specific exceptions, otherwise you'll make you life > harder (by difficult to debug problems) > > better would be: > except AttributeError: The error is unlikely to be an AttributeError, it's more like to be some kind of database connection error. Presumably the Zope machinery wouldn't fill in the object with an incorrect database connection name/method. >> Now I tried to modify the last line as follows: >> self.DB = dbc() >> and getting a very strange error (Error Type: UnpickleableError >> Error Value: Cannot pickle objects). > > don't know Zope but it look like that it uses pickle to store your instaces > and the DB object cannot be picked. thats probably because the connection > to a database cannot be stored, it must be terminated and rebuild, but > thats doesn't seem to be supported by the db object. Yup, that looks likely. >> Now my question is: what the hell am I doing here? Especially what is >> DB?? connection seems to be equally important, how can I find out what >> type of thing this is? A "return self.connection" delivers a >> "MySQL_database_connection". Is this a string, or an object? > > that's an object. it just that the opjects __str__ or __repr__ method > returns a string for display purposes. No, I'd say (as above) that 'self.connection' is a string, which means that 'self' has a method (or instance variable that refers to a class?) called 'MySQL_database_connection'. See what 'self.MySQL_database_connection' is. >> The code works well (queries and all else) if I use DB instead of >> self.DB, but this makes me unable to use DB from other member >> functions, doesn't it? (I'm quite a Python newbie i fear ... :-)) Then perhaps you should just do the same in the member functions, i.e., call the machinery that creates a database connection. You could always wrap it in a method that returns a database connection. Anyway, this seems a confusing idiom for getting a database connection. I think you're missing something simple. Are you even meant to talk to the database? Isn't the point of object persistence that it manages the database for you? Ho hum. Jonathan From trentm at ActiveState.com Thu Jul 11 17:43:00 2002 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 11 Jul 2002 14:43:00 -0700 Subject: Automating MSDEV studio build process In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E201922151C2@admin56.narex.com>; from BPettersen@NAREX.com on Thu, Jul 11, 2002 at 03:20:03PM -0600 References: <60FB8BB7F0EFC7409B75EEEC13E201922151C2@admin56.narex.com> Message-ID: <20020711144300.A8149@ActiveState.com> [Bjorn Pettersen wrote] > Does anyone have any experience automating a nightly build process using > Python in combination with MSDevStudio? I remember some discussion here > about it a while ago, but I couldn't find any reference to it through > Google... You don't need to bother with generating makefiles and calling nmake. You can just call 'msdev' directly on your .dsw or .dsp files to build them. H:\>msdev /? Usage: MSDEV [myprj.dsp|mywksp.dsw] - load project/workspace [] - load source file /? - display usage information /EX - execute a VBScript macro /OUT - redirect command line output to a file /USEENV - ignore tools.options.directories settings /MAKE [] [...] - build specified target(s) [ - ] [[|ALL] - [DEBUG|RELEASE|ALL]] /CLEAN - delete intermediate files but don't build /REBUILD - clean and build /NORECURSE - don't build dependent projects Cheers, Trent -- Trent Mick TrentM at ActiveState.com From jnix at medi.physik.uni-oldenburg.de Mon Jul 1 17:23:00 2002 From: jnix at medi.physik.uni-oldenburg.de (Johannes Nix) Date: 1 Jul 2002 14:23:00 -0700 Subject: Pythoniac: Thoughts on a hardware Python processor References: Message-ID: <5ff724ea.0207011323.66058e47@posting.google.com> Richard Jones wrote in message > > Ooh... from there I found: > > http://www-2.cs.cmu.edu/~koopman/stack_computers/index.html > In the early 80ties, the UCSD Pascal system was based on a virtual stack machine, the P-Machine, resulting in a highly portable operating system which was itself written in Pascal. I remember that in some German computer magazine, a hardware implementation, the P-engine was discussed. I wonder if it would make sense to modify a Modula-3 compiler so that the output runs on a hardware stack machine, and then implement Python in Modula-3. Modula-3 is an interesting compiled, strongly-typed language which has some important things in common with Python. Because of the modularity and safety characteristics of the language, this would be a very nice thing, I guess. For example, as there exists automatic garbage collection, no reference counting would be necessary. Johannes From Jonathan_Epstein at nih.gov Thu Jul 18 09:50:24 2002 From: Jonathan_Epstein at nih.gov (Jonathan Epstein) Date: Thu, 18 Jul 2002 09:50:24 -0400 Subject: re/sre woes with Python 2.0 References: <2KhZ8.22$HD.214554@mencken.net.nih.gov> Message-ID: "John Hunter" wrote in message news:m2r8i2gskj.fsf at mother.paradise.lost... > >>>>> "Jonathan" == Jonathan Epstein writes: > HTH, > John Hunter It did indeed ... many thanks. -Jonathan From spam at ob_scure.dk Sat Jul 6 17:18:02 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sat, 06 Jul 2002 23:18:02 +0200 Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> Message-ID: <3D275E8A.3000003@ob_scure.dk> William Park wrote: [snip] > If your cronjob can tackle 1MB but not 1GB, then I don't think this is > programming language issue. Rather, you should look at your algorithm and > data structure. I am inclined to agree. The current implementation is very inefficient in it's database aceess (lots of small queries with no supporting indexes, furthermore the same data is often read multiple times). > If your company is private for-profit company, then use money argument: It is. > > - Anyone who knows Python or Unix shell will have the necessary > analytical skills. And, there can easily be found on > or . The company is based in Denmark, and I belive that the amount of Danish people in the group is rather small? However I recently heard that some danish universities uses Python as the primary language in CS. > - Scaling to multiple CPU is OS issue. Much easier with Linux (no > comment on Windows :-) I've heard that Python threads don't scale (well?) to multiple CPUs ? Maybe that's only on Windows? I was planning on (be it Python) using XML-RPC for inter-process/-machine communications. > - Scaling to GB is algorithm issue. Python makes development easier, > because it's easy to write and read. > > Mostly, he saves money because he will be able to find right people. The > fact that they happen to know the right language is just bonus. Well said. -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From fredrik at pythonware.com Wed Jul 24 11:07:20 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 24 Jul 2002 15:07:20 GMT Subject: Mastering Regular Expressions 2nd Ed. References: Message-ID: Tom Harris wrote: > Massive regular expressions are certainly difficult to maintain, and I > sometimes wonder if they are the best solution to some problems. when in doubt, the answer is no. for further discussion, see: http://www.google.com/search?q=zawinski+two+problems > Lexical analysis is tokenisation, parsing is making sense of the > tokens, is that correct? exactly. > Is the moral to leave logic to the programming language, not try to > use regexes to do it? exactly. (why do you ask when you know the answer ;-) for some discussion on using REs for lexical analysis, and python to do (simple) parsing, see: http://effbot.org/guides/xml-scanner.htm From zopestoller at thomas-guettler.de Tue Jul 30 07:41:34 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 30 Jul 2002 13:41:34 +0200 Subject: Good XML tools? References: Message-ID: <3D467B6E.9070305@thomas-guettler.de> M wrote: > Hi all, > > > Can you recommend any good XML packages for Python? I looked at the > PyXML but it seems to be lacking proper documentation (=unusable). > > Are you aware of any package that provides DOM/XPath for Python? > > Good documentation is a must, only hackers doing their favorite > OSS project in their spare time can spend time reading source > code instead of proper documentation... The xml tools of 4suite are good. thomas From pinard at iro.umontreal.ca Sat Jul 13 19:41:31 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 13 Jul 2002 19:41:31 -0400 Subject: XML overuse? (was Re: Python to XML to Python conversion) In-Reply-To: References: <7x65zj60ku.fsf@ruckus.brouhaha.com> Message-ID: [Christopher Browne] > Yacc and Lex provide nice formal ways to describe grammars, can work with > the "Langues-du-jour," and it would be very instructive to see that they > _are_ usable for building parsers for small languages. Python users are blessed with many lexers/parsers systems. Even if I glanced around, I surely do not know them all. My favorite so far is SPARK, which is not only very elegant, but also quite simple to use and powerful at what it can recognise. I also learned to like PLY. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From jonathan at onegoodidea.com Tue Jul 9 13:08:28 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Tue, 09 Jul 2002 18:08:28 +0100 Subject: 8 Queens Problem References: <00172807.C22236@smiths-aerospace.com> Message-ID: On 9/7/2002 17:03, in article mailman.1026230956.30903.python-list at python.org, "Justin Sheehy" wrote: >> Would this solution qualify as tail-recursive? > > Yes. The only recursive call that you make is in tail position. I'd say no - because the algorithm relies on continuing execution after return of the recursive call (the outer for loop continues). With tail-recursive code you can safely throw the current stack frame and replace it with a new frame for the recursive call. When that call returns it will return to the original caller (make sense?). This means that a tail recursive function can be optimised to not consume stack - and thus become iterative. A tail-recursive function is one that has the pattern: def f( ... ): ... return f( ... ) ... i.e., there should be no recursive call that doesn't immediately return the result of that call. But yes, Python doesn't optimise the tail-recursion away so it doesn't matter. Jonathan From anton.wilson at camotion.com Fri Jul 26 14:12:27 2002 From: anton.wilson at camotion.com (anton wilson) Date: Fri, 26 Jul 2002 14:12:27 -0400 Subject: thread wierdness Message-ID: <200207261812.OAA19811@test-area.com> I'm trying to create a simple thread with the following code: ============================================ import time, thread, thr_test, sys def do_computations(str): thr_test.set_priority("") #set the priority of this thread really high compute() def compute(): i = 0 x = 0 while i < 1000: for y in range(10000): x = x + 1 x = x - 1 i = i + 1 i = i * 1 sys.setcheckinterval(2000) thr_test.set_priority("") #set the priority of main thread really high thread.start_new(do_computations, ("",)) sys.setcheckinterval(10) compute() ======================================== I spawn 1 additional python thread and then both of them could do compute. The following printouts from within the kernel scheduler itself show the process that was running on the CPU at the time the schduler was run, the new process to chosen to run next, and the time that the change was made in microseconds. Instead of the two high-priority threads I thought I created, I see 3 threads with the PIDs 1374, 1375, and 1376. Additionally there is a huge gap in time (multiple seconds) on the 6th line when process 1374 was scheduled and the 7th line when it was removed from the CPU. This breaks my assumption that python threads will switch every 10 byte codes. Does anyone have any suggested explanations? [(1374) (1375) - 778582] [(1375) (1374) - 778598] [(1374) (1375) - 778618] [(1375) (1376) -778678] [(1376) (1375) - 778696] [(1375) (1374) - 778713] [(1374) (1376) - 506072] [(1376) (1375) - 506107] [(1375) (1376) - 506150] [(1376) (1375) - 506184] [(1375) (1374) - 506213] [(1374) 1068 - 506496] From petitmermet at mat.ethz.ch Fri Jul 26 08:18:28 2002 From: petitmermet at mat.ethz.ch (Marc Petitmermet) Date: Fri, 26 Jul 2002 14:18:28 +0200 Subject: Solaris 9, python 2.1.3, find Message-ID: I have a new SunBlade 100 with Solaris 9 and the latest patches for this OS installed. Now I'd like to install python 2.1.3 from source with tkinter enabled. Although I have correctly configured Modules/Setup to point to the correct location of the libraries and header files of tcl/tk, the compilation (./python setup.py build) stops with telling me that "libtk8.3.so: open failed: No such file or directory". And now to the funny things: If I issue the command find /usr/local -name libtk8.3.so -print the library cannot be found although it is located in /usr/local/tk8.3.4/lib/libtk8.3.so. If I do the following: find /usr/local -follow -name libtk8.3.so -print the library is found. The man page for "find" states that follow is "Always true. Causes symbolic links to be followed". I think that this is not true because in may case /usr/local is a link to /p1/local on a second disk. If "find" cannot find the libraries with the default options I wander if python can follow links. Of course I can enter "-L/p1/local/tk8.3.4/lib" in the Setup file but it really should also work with links. Is this a python or Solaris 9 problem or did I something wrong with setting up the second disk? Any hints are appreciated. Thanks in advance. Regards, Marc From b.maryniuk at forbis.lt Wed Jul 3 09:21:36 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 3 Jul 2002 15:21:36 +0200 Subject: baffling bug in this bit of code! In-Reply-To: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> References: <3D22F87E.8030009@NOSPAMembl-heidelberg.de> Message-ID: <200207031521.36595.b.maryniuk@forbis.lt> On Wednesday 03 July 2002 15:13, Daniel Jaeggi wrote: > print "max_y = ",y Should be: print "max_y = ", max_y ...I guess... :-) -- Sincerely yours, Bogdan M. Maryniuck "...Unix, MS-DOS, and Windows NT (also known as the Good, the Bad, and the Ugly)." (By Matt Welsh) From jb at cascade-sys.com Fri Jul 12 04:33:34 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 12 Jul 2002 01:33:34 -0700 Subject: What does "Sparse is better than dense" mean? (Python Zen) References: <0UlX8.69924$vm5.2553930@news2.tin.it> <8DvX8.58418$Jj7.1534077@news1.tin.it> Message-ID: <3D2E945E.39EC0935@cascade-sys.com> Alex Martelli wrote: > Not hard at all -- PEP 7 does that too, yet every time I see > that construct... > } > else { > my blood still boils!-) Oh, yeah. That's completely brain dead. My point is I don't have any qualms about ignoring those several points on which I happend to disagree. > Further, PEP 7 is enforced for patches to Python -- sensibly, mind you, > as we wouldn't want Python's C sources to be a mixmax of styles -- but... "It's good to be the king." --jb -- James J. Besemer 503-280-0838 voice http://cascade-sys.com 503-280-0375 fax mailto:jb at cascade-sys.com From dbasch at yahoo.com Tue Jul 30 16:19:35 2002 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 30 Jul 2002 13:19:35 -0700 (PDT) Subject: Win32/Python serial port event character problem In-Reply-To: <200206292038.g5TKcHu10071@smtp.swissonline.ch> Message-ID: <20020730201935.88034.qmail@web20805.mail.yahoo.com> Chris, I had a quick question about flow control in serialwin32.py. On line 120,: http://www.geocities.com/dbasch/flowcontrol.txt if RTSCTS is selected by the user then RTS and DTR are enabled (with handshaking). Why are both RTS and DTR enabled? If RTSCTS is not selected by the user then the RTS and DTR lines are still enabled but nothing is done with them. Can you explain why? OK, so that was 2 questions :). Thanks once again, Derek T Basch --- Chris Liechti wrote: > Derek Basch wrote in > news:mailman.1025380000.22796.python-list at python.org: > > > Sorry to post this again but it didn't get any > > responses. Maybe better luck this time. > > well 14hrs isn't that much time on a weekend... some > people only look into > news once per week. > > > I use the following code to read data from the > serial > > port when a certain event character ('\n') is > > received: > ... > > Has anyone ever dealt with this? Is using the > event > > character not a reliable method in windows? > > no sorry, i haven't used the event mode. > > .... > > This is driving me batty so any help is greatly > > appreciated. > > > my tip is: use http://pyserial.sf.net > > and read the characters in a separate receiver > thread. that thread can then > trigger on any character or sequence (e.g. using a > Queue to communicate > with other threads) > > > > -- > http://pyserial.sf.net > Chris > __________________________________________________ Do You Yahoo!? Yahoo! Health - Feel better, live better http://health.yahoo.com From marklists at mceahern.com Sat Jul 13 10:08:55 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 13 Jul 2002 09:08:55 -0500 Subject: switch recipe? In-Reply-To: Message-ID: [Christian Tanzer] > Not so. As long as one of the iterators is finite, zip will work: > > >>> from __future__ import generators > >>> def repeat(*args): > ... """Return a repeating alternator for args.""" > ... while args: > ... for a in args: > ... yield a > ... > >>> for i, j in zip(range(5), repeat("a","b","c")): > ... print i, j > ... > 0 a > 1 b > 2 c > 3 a > 4 b I just saw Office Space for the first time last night. One of the characters in the movie develops a prototype for a Jumping To Conclusions mat. That's certainly what I did about zip, assuming that it had similar behavior to map when it came to unbounded iterators. As you point out, that's not true. Because I want to do something to the zipped items, it doesn't seem like zip solves all my problems, though. map would, if it had the same behavior as zip--namely that it stopped once one of the iterators ran out of items. Below is a version that shows the use of zip. Here are the key lines: weaved = zip(iterator, alternator) generated = [color_item(x, y) for x, y in weaved] Perhaps what I'm still looking for is a way to weave-two-iterators-with-a-function all at once. One solution would be to modify or wrap repeating_alternator() so that it was finite--then I could just use map. Thanks! // mark #! /usr/bin/env python from __future__ import generators import unittest def repeating_alternator(*args): """Return a repeating alternator for args.""" while args: for a in args: yield a def weave_items(iterator, alternator, weave_item): """Iterate over iterator, applying weave_item to each item with its pair in alternator. """ for item in iterator: yield weave_item(item, alternator.next()) def color_item(item, color): template = "<%(color)s>%(item)s" return template % locals() class test(unittest.TestCase): def test(self): iterator = range(10) colors = ("red", "organge", "yellow", "green", "blue", "indigo", "violet") alternator = repeating_alternator(*colors) expected = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] weaved = zip(iterator, alternator) generated = [color_item(x, y) for x, y in weaved] self.assertEquals(expected, generated) def test_empty(self): r = repeating_alternator() self.assertRaises(StopIteration, r.next) if __name__ == "__main__": unittest.main() - From eric.brunel at pragmadev.com Mon Jul 1 07:53:21 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 1 Jul 2002 11:53:21 +0000 Subject: WindowsError in time.sleep !?!??!! References: Message-ID: Eric Brunel wrote: [snip] > Does anybody have an explanation and/or a workaround for this problem? We > may of course delete this statement, but it doesn't sound quite safe: we > have many time.sleep in our code, and if we don't understand why this is > happening, it may break another one later... We tried to delete the statement, and it actually crashes later, but on an even stranger line: it's an if statement, just comparing a plain variable to an empty string (something like "if v == '':"). And we get the same error: WindowsError, access denied... Can somebody help? TIA... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From unlearned at DELETETHIS.learn2think.org Tue Jul 30 10:16:57 2002 From: unlearned at DELETETHIS.learn2think.org (Daniel Fackrell) Date: Tue, 30 Jul 2002 08:16:57 -0600 Subject: MIDI Music References: Message-ID: <3d469fdb$1_3@hpb10302.boi.hp.com> > "Seth Ainsley" sethtoday at hotmail.com> wrote in message > news:mailman.1027979743.26610.python-list at python.org... > I wanted to ask a question: is there a way to put MIDI music into > a Python program? I've always thought it would be neat. Or, if I > can't use MIDI music, can I use WAV format instead? Maybe I could copy > the MIDI file and change the extension to .wav...it's a > thought...please give me some ideas here. If I can do it, can someone > post the code? > Thanks in advance, > Seth Does this help? http://www.speech.kth.se/snack/ This site includes instructions and examples. -- Daniel Fackrell (unlearned at learn2think.org) When we attempt the impossible, we can experience true growth. From opengeometry at NOSPAM.yahoo.ca Tue Jul 2 16:00:09 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 2 Jul 2002 20:00:09 GMT Subject: Add parent directory to path? References: <3D21F62D.9050801@wag.caltech.edu> Message-ID: Rick Muller wrote: > I often use the little hack > > import sys > sys.path.append('..') > > to add the parent directory to the python path. It's nice, e.g., if I > want to keep a directory below the program directory that contains test > scripts, but still let them easily import the parent directory's modules. > > This hack worked on Unix and Windows/Cygwin, which up until recently > were my only build targets. Now I just got a Apple OS X box, and I find > that, despite the BSD heritage, this little hack no longer works. Is > there a good platform-independent way of doing this? I figure that > something like this should live in os.path, but I didn't find anything > appropriate. > > Thanks in advance for any help anyone can offer. > > Rick What does this have to do with the original post of this thread? Please start new thread for new subject. -- William Park, Open Geometry Consulting, 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin From shagshag13 at yahoo.fr Wed Jul 17 11:38:54 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Wed, 17 Jul 2002 17:38:54 +0200 Subject: how to ask google, altavista or another search engine... Message-ID: hello, i'm looking for a python script able to ask to a web search engine (google, altavista or another search engine) and/or able to parse a result page. any other helps / advices / urls are welcome... thanks in advance, s13. From mertz at gnosis.cx Thu Jul 18 13:08:39 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 18 Jul 2002 13:08:39 -0400 Subject: [Announce] Gnosis (XML) Utils 1.0.3 In-Reply-To: <1026992252.2034.4.camel@fnsnb40> Message-ID: This release contains some improvements to gnosis.xml.objectify: * Reorganized single-file module into subpackage with test/ and doc/ subpackages/directories. * Added caching of dynamic object creation. This leads to a considerable speedup where the same-named XML subnode occurs many times in the XML file (a frequent situation). * Allowed "objectification" of a DOM tree, as well as the prior filename/filehandle. Especially in Jython contexts, one is sometimes delivered a a pre-build DOM rather than raw XML. It may be obtained at: http://gnosis.cx/download/Gnosis_Utils-1.0.3.tar.gz The current release is always available as: http://gnosis.cx/download/Gnosis_Utils-current.tar.gz Try it out, have fun, send feedback! David Mertz (mertz at gnosis.cx) ------------------------------------------------------------------------ BACKGROUND: Gnosis Utilites contains a number of Python libraries, most (but not all) related to working with XML. These include: gnosis.xml.pickle (XML pickling of Python objects) gnosis.xml.objectify (Any XML to "native" Python objects) gnosis.xml.validity (Enforce validity constraints) gnosis.xml.indexer (XPATH indexing of XML documents) gnosis.indexer (Full-text indexing/searching) [...].convert.txt2html (Convert ASCII source files to HTML) gnosis.util.dtd2sql (DTD -> SQL 'CREATE TABLE' statements) gnosis.util.sql2dtd (SQL query -> DTD for query results) gnosis.util.xml2sql (XML -> SQL 'INSERT INTO' statements) gnosis.util.combinators (Combinatorial higher-order functions) gnosis.util.introspect (Introspect Python objects) ...and so much more! :-) SUMMARY:

Gnosis_Util 1.0.3 (Thu 07-18-2002) From mtaylor at lowebroadway.com Fri Jul 12 05:15:02 2002 From: mtaylor at lowebroadway.com (Moray Taylor) Date: 12 Jul 2002 02:15:02 -0700 Subject: Transferring an excel file through HTTP References: <79b54d28.0207111451.35b583b2@posting.google.com> Message-ID: "Emile van Sebille" wrote in message news:... > Chris > > I have a question about clients (on windows) uploading Excel > > spreadsheets (.xls) to a unix server. These spreadsheets contain > > information that wil be used to store and update a database. I need to > > be able to safely pass the information in the spreadsheet so that I > > can parse it and update accordingly. However, when I upload through my > > web page, the text that once was a nicely formatted excel spreadsheet > > becomes jarbled and illegible. Passing the information (presumably > > through a large string) messes it up understandably as there are text > > format issues and such. I've explored such things as the COM and > > win32com modules but am a little hesitant as my CGI script is not > > operating on a windows platform. I'm using Python 2.2. Can someone > > point me in the right direction? Thanks! > > > > The easy answer is to save in excel as tab delimited output and upload > that. > > Maybe someone else knows an easy answer to the hard answer? ;-) Are you sure there isn't any FTP going on here, FTP has ASCII and BINARY transfer systems, if you use the ASCII one on a BINARY file, it will fry it. Moray From juenglin at informatik.uni-freiburg.de Wed Jul 3 07:13:52 2002 From: juenglin at informatik.uni-freiburg.de (Ralf Juengling) Date: 03 Jul 2002 13:13:52 +0200 Subject: determining instance attributes Message-ID: Hi, how can an instance easily find out all its non-method instance attributes? Cheers, Ralf From otis_usenet at yahoo.com Thu Jul 18 18:29:58 2002 From: otis_usenet at yahoo.com (OtisUsenet) Date: 18 Jul 2002 15:29:58 -0700 Subject: i++ in Python? Message-ID: <5606b639.0207181429.2c6d2569@posting.google.com> Hello, Python newbie question. How does one do something like this in Python: # assign the value of j to i and then increment j by 1 i = j++ I checked the FAQ at http://www.python.org/doc/FAQ.html, but this simple question wasn't covered :) I can't find it in 2 Python books either. Thank you. From aleax at aleax.it Sun Jul 7 06:45:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Jul 2002 10:45:33 GMT Subject: Using Python for processing of large datasets (convincing managment) References: <3D27152C.8020108@obscure.dk.X> <7x4rfcf8xi.fsf@ruckus.brouhaha.com> <3D28176E.4030709@ob_scure.dk> Message-ID: Thomas Jensen wrote: ... > One of the tasks of the program will be to calculate the standard > deviation of rows of daily values (which are the result of another > calculation, etc). I was planning on using lists and tuples like this: > [(date, value), (date, value), ...] > How well will this perform i wonder? Since lists and tuples are Python > structures, won't they still be "slow" to traverse? If you have substantial numeric computations to perform on large arrays, you're almost surely better off using the Numeric package to extend Python, particularly if performance is an issue. Alex